code wiki / _hdl_build / nx_log_append.nx

nx_log_append.nx source

↩ module page · 53 lines · 2360 B

1// nx_log_append.nx -- TEAM-OWNED durable-log appender: appends the whole 2// content of <src> to <dst> via one O_APPEND write (atomic for the 3// pipe-buffer sizes our log rows have), in pure NishiLang. Born 4// 2026-06-10: pm_plan_durable.log is appended by CONCURRENT sessions; 5// editor-style read-modify-write races, shell heredocs mangle through 6// PS/Git-Bash->wsl quoting, and the no-sh law holds -- so the append 7// becomes a syscall-layer organ instead. 8// 9// Usage: nx_log_append.elf <src> <dst> 10// Exit: 0 = appended (prints byte count), 1 = src unreadable/empty, 11// 2 = dst unwritable, 3 = usage. 12// license_tier: ORIGINAL 13import "nx_syscalls.nx" 14import "nx_itoa_lib.nx" // shared MSB-first emitter (zero-alloc) 15 16func la_puts(s: *u8) -> i64 { var n: i64 = 0; while s[n] != (0 as u8) { n = n + 1 } sys_write(1, s, n); return 0 } 17// MIGRATED to the shared emitter (debt 1785563586). The old body mmapped a scratch buffer 18// per call and never freed it. At PAGE granularity that is 4096B leaked PER CALL -- the 19// defect that took 28.5GB of a 36GB host in nx_ts_lumadiff (2MB input, ~3.66M calls). 20// nxi_* is MSB-first, allocates NOTHING, and emits identical bytes including the sign. 21func la_putn(v: i64) -> i64 { nxi_out(v); return 0 } 22 23const LA_MAX: i64 = 1048576 24 25func main(argc: i64, argv: *i64) -> i64 { 26 if argc < 3 { 27 la_puts("LOGAPPEND usage: nx_log_append.elf <src> <dst>\n" as *u8) 28 return 3 29 } 30 let src: *u8 = argv[1] as *u8 31 let dst: *u8 = argv[2] as *u8 32 let sfd: i64 = sys_openat_rd(src) 33 if sfd < 0 { la_puts("LOGAPPEND src-unreadable\n" as *u8); return 1 } 34 let buf: *u8 = sys_mmap(LA_MAX) 35 var total: i64 = 0 36 var n: i64 = sys_read(sfd, buf, LA_MAX) 37 while n > 0 { 38 total = total + n 39 if total < LA_MAX { 40 n = sys_read(sfd, ((buf as i64) + total) as *u8, LA_MAX - total) 41 } else { n = 0 } 42 } 43 sys_close(sfd) 44 if total <= 0 { la_puts("LOGAPPEND src-empty\n" as *u8); return 1 } 45 let dfd: i64 = sys_openat_append(dst, 0x1a4) 46 if dfd < 0 { la_puts("LOGAPPEND dst-unwritable\n" as *u8); return 2 } 47 let w: i64 = sys_write(dfd, buf, total) 48 sys_fsync(dfd) 49 sys_close(dfd) 50 la_puts("LOGAPPEND bytes=" as *u8); la_putn(w); la_puts(" dst=" as *u8); la_puts(dst); la_puts("\n" as *u8) 51 if w != total { return 2 } 52 return 0 53}