code wiki / _hdl_build / _ad_dupguard_test.nx
_ad_dupguard_test.nx source
↩ module page · 40 lines · 2475 B
1// _ad_dupguard_test.nx -- the REUSABLE bug-reproduction gate for the daemon dup-guard
2// bug (two daemons coexisted 2026-06-13 because the old pidfile+/proc check was non-atomic).
3// THE CAPABILITY (partner-built with the team): reproduce the bug CLASS first, then prove
4// the fix. Here: a SECOND acquirer of the held single-instance lock MUST be rejected.
5// Parent acquires ad_acquire_lock; a forked child attempts the SAME lock and MUST fail.
6// With the racy old guard this could not be asserted; with the atomic flock it is
7// deterministic (no timing). GREEN = the guard bites. This gate is the template the
8// team reuses for any concurrency/single-instance bug.
9// Imports ONLY nx_ad_core (re-exports nx_syscalls + ad_acquire_lock; a 2nd direct
10// nx_syscalls import is the documented NXASM rc=6 landmine). license_tier: ORIGINAL
11import "nx_ad_core.nx"
12
13func g_w(s: *u8) -> i64 { var n: i64 = 0; while s[n] != (0 as u8) { n = n + 1 } sys_write(1, s, n); return 0 }
14func g_wn(v: i64) -> i64 { let bb: *u8=sys_mmap(28); var m: i64=v; if m<0{m=0-m;sys_write(1,"-" as *u8,1)}; let t: *u8=sys_mmap(28); var k: i64=0; if m==0{t[0]=48;k=1}; while m>0{t[k]=(48+(m%10)) as u8;m=m/10;k=k+1}; var i: i64=0; while i<k{bb[i]=t[k-1-i];i=i+1}; sys_write(1,bb,k); return 0 }
15
16func main() -> i64 {
17 let lock: *u8 = "/tmp/_ad_dupguard_test.lock" as *u8
18 __syscall(263, AT_FDCWD, lock as i64, 0, 0, 0, 0) // idempotent: drop any leftover lock so re-runs (daemon guardrail) pass
19
20 // parent acquires the single-instance lock
21 let pl: i64 = ad_acquire_lock(lock)
22 if pl < 0 { g_w("DUP-GUARD GATE: RED reason=parent-could-not-acquire\n" as *u8); sys_exit(1); return 1 }
23
24 let pid: i64 = sys_fork()
25 if pid == 0 {
26 // child = a "second daemon start": the lockfile already EXISTS (parent created it
27 // via O_EXCL), so the child's O_EXCL create MUST fail with EEXIST -> rejected.
28 let cl: i64 = ad_acquire_lock(lock)
29 if cl < 0 { sys_exit(0) } // correctly rejected -> the guard WORKS
30 sys_exit(1) // wrongly acquired -> the bug (two holders)
31 }
32
33 let st: *i64 = sys_mmap(16) as *i64
34 sys_wait4(pid, st, 0)
35 let crc: i64 = (st[0] >> 8) & 0xff
36 if crc == 0 { g_w("DUP-GUARD GATE: GREEN atomic-O_EXCL-rejects-2nd-acquirer (bug-class fixed)\n" as *u8); sys_exit(0); return 0 }
37 g_w("DUP-GUARD GATE: RED reason=2nd-acquirer-got-the-lock (bug reproduced)\n" as *u8)
38 sys_exit(1)
39 return 1
40}