GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | |||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | |||||||||||||||||||||||||||||||||
GeezerVison is showing github.com — audit fixes: cron lock, accounting race, O(n²) hot paths, /style wiring by gnanam1990 · Pull Request #260 · Twigpine/zero Conversation
|
ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Free Run ID: 📒 Files selected for processing (7)
🚧 Files skipped from review as they are similar to previous changes (2)
WalkthroughThe PR adds cross-process file-based locking to cron and audit ChangesCron Job File-Based Locking and Atomic Mutation
Session Atomic Check-and-Append, Audit Tail-Read, and Audit Locking
Agent Response Style and TUI Transcript Dedup
OAuth Lock Windows Contention Handling
Sequence Diagram(s)sequenceDiagram
participant fireJob
participant Store as cron.Store
participant lockFile as Lock File (O_EXCL)
participant sessions as sessions.Store
fireJob->>Store: Mutate(job.ID, mutateFunc)
Store->>lockFile: lockJob (O_CREATE|O_EXCL + token)
lockFile-->>Store: unlock closure
Store->>Store: Get(id) — re-read under lock
alt job removed mid-run
Store-->>fireJob: ErrJobNotFound
fireJob->>fireJob: print removed, return
else job found
Store->>Store: mutateFunc(current, readErr)
Note over Store: preserve Paused, advance schedule
Store->>Store: writeJob(persisted)
Store->>lockFile: unlock()
Store-->>fireJob: persisted job
fireJob->>sessions: AppendRun
end
sequenceDiagram
participant specialist as specialist/accounting
participant sessions as sessions.Store
participant predicate as specialistEventMatcher
specialist->>sessions: AppendEventUnlessExists(sessionID, input, matcher)
sessions->>sessions: lock session
sessions->>sessions: ReadEvents()
sessions->>predicate: exists(events)?
alt event already exists
predicate-->>sessions: true
sessions-->>specialist: (_, appended=false, nil)
else not found
predicate-->>sessions: false
sessions->>sessions: appendEventLocked(input)
sessions-->>specialist: (event, appended=true, nil)
end
sessions->>sessions: unlock session
sequenceDiagram
participant append as AuditStore.append
participant lockFile as Lock File (O_EXCL)
participant tail as lastSequence
participant fullScan as lastSequenceFullScan
append->>lockFile: lockAudit (O_CREATE|O_EXCL + token)
lockFile-->>append: unlock closure
append->>tail: lastSequence()
tail->>tail: read bounded tail window
tail->>tail: parse last JSON record
alt record fits in window
tail-->>append: record.Sequence
else record likely exceeds window
tail->>fullScan: lastSequenceFullScan()
fullScan->>fullScan: ReadEvents() and max()
fullScan-->>tail: max sequence
tail-->>append: max sequence
end
append->>lockFile: unlock()
Estimated code review effort🎯 4 (Complex) | ⏱️ ~75 minutes Note 🎁 Summarized by CodeRabbit FreeYour organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login. Comment |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
Zero automated PR reviewVerdict: No blockers found Blockers
Validation
ScopeHead: This deterministic review checks validation status and basic diff hygiene. A human reviewer still owns product judgment and design quality. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
…uth) The Windows smoke run failed TestMutateIsAtomicUnderConcurrency with "...lock: Access is denied" (FireCount 19/20). On Windows a concurrent holder's os.Remove leaves the lock file in a delete-pending state, so an O_EXCL create races it with ERROR_ACCESS_DENIED (os.ErrPermission) rather than ErrExist — the retry loop only treated ErrExist as contention and hard-failed. Treat os.ErrPermission as contention (retry) in the new cron lock and in the oauth lock it mirrors (oauth's own concurrent test exposed the same pre-existing bug under the added load). Unix is unaffected — it returns ErrExist.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
I read the diff end-to-end, built the PR branch (go build ./... clean), and ran every new test (all PASS). Verdict below is Request changes because of one cross-process correctness gap in the hooks audit fix; the rest of the PR is solid.
1. AuditStore.append is NOT cross-process atomic; the tail read alone doesn't deliver the claimed guarantee.
internal/hooks/hooks.go:500 (append) holds only the in-process store.mu. lastSequence() (hooks.go:528) re-reads the file tail fresh each call, which is enough to observe another process's prior writes, but the read-then-write is not atomic across processes. Two processes can both lastSequence() → 50, both assign Sequence = 51, and both O_APPEND-write — producing two records with the same sequence number. The PR's own comment ("a concurrent process's appends … are still observed — unlike an in-memory counter, which would collide sequences across processes") oversells what the tail read buys: it eliminates the stale-counter collision but not the check-then-append collision. The audit log is a shared global file, so this matters precisely in the multi-process scenario the PR targets.
The new test TestAuditStoreSequenceTailRead (audit_sequence_test.go) only exercises sequential two-store usage (store #1 writes 50, store #2 writes #51). It does not race two stores appending concurrently, so it cannot catch this. A -race-style concurrency test (two stores, N goroutines each, assert all Sequence values are unique) would fail under the current implementation.
Fix direction: take a cross-process file lock around the lastSequence() + append write (the same O_EXCL-with-stale-reclaim pattern already used in internal/cron/lock.go and internal/oauth/lock.go), or use an OS atomic append-with-sequence primitive. The in-process store.mu can stay as the fast path. This is the same class of race the PR correctly closes for cron (Store.Mutate) and specialist accounting (AppendEventUnlessExists) — the audit path is the odd one out.
2. fireJob → AppendRun can resurrect a deleted job directory.
internal/cli/cron_run.go:191 calls store.AppendRun(job.ID, rec) after store.Mutate has returned and released the per-job lock. A Remove landing in that window deletes the job dir; AppendRun then os.MkdirAlls it back (cron/store.go AppendRun), leaving an orphaned runs.jsonl with no metadata.json. List won't list it (it skips dirs without metadata.json), but Runs will still return the orphaned records. Narrow, but the comment "Record the fire only after confirming the job was not removed mid-run, so AppendRun cannot resurrect a deleted job's directory" claims the window is closed when it isn't. Either move AppendRun inside Mutate's lock window, or have AppendRun stat metadata.json and bail if absent.
3. lastSequence ReadAt error path can spuriously fail on a short final read.
internal/hooks/hooks.go:498: if n, err := file.ReadAt(buf, start); err != nil && n < len(buf) { return 0, err }. ReadAt is permitted to return io.EOF with a short read when fewer than len(buf) bytes are available at the offset (e.g. the file was truncated between Stat and ReadAt). On a 0-padded tail read this would surface as io.EOF and abort the append. In practice the file is only ever appended so this is unlikely, but io.EOF should be treated as a non-error when n > 0 (the standard Read-style handling), matching how lastEventSequence in internal/sessions/store.go handles its tail loop.
4. oauth.acquireFileLock stale-reclaim compares a file to itself.
internal/oauth/lock.go:62: stale, _ := os.ReadFile(lockPath); if data, rerr := os.ReadFile(lockPath); rerr == nil && string(data) == string(stale) { _ = os.Remove(lockPath) }. This reads the file twice and compares it to itself — string(data) == string(stale) is always true when both reads succeed, so the guard is a no-op. Pre-existing (only the Windows ErrPermission line was added in this PR), but worth fixing while the lock code is being touched: the intent was presumably to re-read after Remove races and bail if the token changed.
5. accountingMu + AppendEventUnlessExists double-locking is now redundant for in-process callers.
internal/specialist/accounting.go:42 still takes accountingMu.Lock() before calling appendSpecialistEventOnce, which itself takes the session lock. accountingMu is now only a cheap fast-path that doesn't provide the real guarantee (the comment says so). That's fine, but the in-process mutex is now strictly redundant — AppendEventUnlessExists's session lock already serializes all in-process callers. Removing accountingMu would simplify; keeping it is harmless. Just flagging in case it was meant to be removed.
6. appendSpecialistEventOnce drops the "skip append when parent invalid" silently vs. the old path.
internal/specialist/accounting.go (new appendSpecialistEventOnce): when parentSessionID is empty/invalid it returns (false, nil) — "not appended, no error." The old appendSpecialistSessionEvent returned (Event{}, nil) in the same case. Both result in no append, so behavior is preserved. The _, _ = discard in recordSpecialistStop means the difference is invisible. Just noting the parity holds.
7. TestMutateIsAtomicUnderConcurrency is a good test but only exercises in-process concurrency.
internal/cron/mutate_test.go:264 runs 20 goroutines in one process. The whole point of the O_EXCL lock is cross-process safety, which a goroutine test cannot verify. Consider a two-process test (spawn a second go test binary / os/exec helper) that both Mutate the same job against a shared RootDir. Not blocking — the in-process test still validates the lock is taken — but the comment "the lock is not serializing the read-modify-write" would be more honestly demonstrated cross-process.
lockJob (internal/cron/lock.go): O_EXCL + ownership-token release + stale reclaim is the right pattern, and matches the established oauth.acquireFileLock shape. The lock is held only across the RMW in Mutate/Update/Remove, never across job exec — good. The Windows ErrPermission contention handling (commit a090df0) is correct and necessary on Windows where os.Remove leaves a "delete pending" file.Store.Mutate (cron/store.go:343): correctly returns ErrJobNotFound on a removed job (no resurrection), surfaces transient read errors via readErr so the fire path can still advance the schedule, and honors an external StatusPaused landed mid-run. The fireJob restructure around it (cron_run.go:177) is correct.AppendEventUnlessExists (internal/sessions/store.go:528): the check-then-append is correctly done under lockSession (in-process mutex + cross-process file lock), and ReadEvents does not re-acquire the session lock (verified — it only does os.ReadFile), so there's no deadlock. The 24-goroutine test passes, confirming in-process atomicity.specialistEventMatcher preserves the exact dedup semantics of the old specialistEventExists (catch-all runId matching, childSessionId/taskId aliasing, source == "specialist" filter). The parity holds.appendTranscriptRowsDedup (internal/tui/transcript.go:105) is a faithful bulk equivalent of the per-row appendTranscriptRow: unkeyed rows always append, keyed rows dedup against existing rows and earlier new rows. TestAppendTranscriptRowsDedupMatchesPerRow asserts byte-identical output against the per-row path across a mixed keyed/unkeyed/duplicate input — adequate parity coverage. O(n²)→O(n) confirmed./style wiring: agent.Options.ResponseStyle is populated from m.responseStyle (model.go:2863), consumed by responseStyleContext (system_prompt.go), and balanced/empty/garbage all return "" so the prompt is byte-identical to pre-style behavior (asserted by the test). concise/explanatory/review inject a short directive. Verified the directive lands in buildSystemPrompt. This is a real, correct fix for the inert /style command.internal/tui's TestModelCommandPersistsSelectedModelToUserConfig fails on the base commit (673fce1) with anthropic provider requires official baseURL https://api.anthropic.com — an environment/config issue, not introduced here. Confirming so the failure isn't attributed to this PR.
Request changes — the cron lock, accounting atomicity, transcript dedup, and /style wiring are all correct and well-tested. The hooks audit O(1) tail read is a nice performance win within a single process, but the PR's stated multi-process safety claim for the audit log is not actually delivered (P1 #1). I'd like to see either (a) a cross-process lock around AuditStore.append, or (b) the doc/comment claims walked back to "single-process atomic, multi-process best-effort" with the test renamed to not imply cross-process safety.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Requesting changes. I found one blocking correctness gap and one smaller invariant issue in the new primitives.
High: AuditStore.append is still not cross-process atomic.
internal/hooks/hooks.go:499-518 holds only the per-process store.mu, then does lastSequence() followed by an O_APPEND write. The tail read at internal/hooks/hooks.go:531-538 makes the sequence lookup O(1), but it does not make the read-then-write atomic across processes. Two Zero processes can both read the same last sequence, assign the same next Sequence, and append two audit rows with duplicate sequence numbers. That is the exact multi-process case this PR says it fixes for the global audit log. Please put a cross-process file lock around lastSequence plus the append write, or explicitly downgrade the guarantee and tests to single-process/best-effort behavior.
Medium: Store.Mutate locks one cron job ID but writes whatever ID the callback returns.
internal/cron/store.go:192-210 validates and locks id, but then passes the callback result directly to writeJob; writeJob derives the target directory from job.ID at internal/cron/store.go:134-145. A future caller can accidentally return a different or invalid ID, bypassing the lock that was acquired and potentially writing outside the intended job directory. This new atomic primitive should enforce the invariant, e.g. set next.ID = id before writing or reject next.ID != id / invalid IDs.
Verification: git diff --check b64a9d3de97da7a50ab618816b04452ecb7345c8...a090df06a9e70132bb872b597bc8298bd6e912b9 passed. From temporary archives of the PR head, GOCACHE=/tmp/zero-go-cache go test ./internal/cron ./internal/cli ./internal/hooks ./internal/oauth ./internal/sessions ./internal/specialist ./internal/tui ./internal/agent passed outside the sandbox, GOCACHE=/tmp/zero-go-cache go build -buildvcs=false ./... passed, and GOCACHE=/tmp/zero-go-cache go test -race ./internal/cron ./internal/sessions ./internal/hooks passed.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
…uard Addresses the review feedback on this PR. P1 (blocking): AuditStore.append is now cross-process atomic. The O(1) tail read observes another process's prior appends, but the read-then- append was not atomic across processes — two could both read sequence N and write N+1. Wraps lastSequence()+append in a per-file O_EXCL lock (hooks/lock.go, same stale-reclaim + Windows ErrPermission handling as cron/oauth); store.mu stays as the in-process fast path. Adds TestAuditStoreSequenceConcurrent (4 stores x 12 goroutines on one file -> unique dense sequences), which the prior sequential test could not catch. Walked back the comment that oversold the tail read. P2: AppendRun no longer resurrects a removed job. fireJob's AppendRun ran after Mutate released the per-job lock; a Remove in that window let AppendRun's MkdirAll recreate the dir with an orphaned runs.jsonl. AppendRun now takes the per-job lock and bails if metadata.json is gone. Adds TestAppendRunDoesNotResurrectRemovedJob. P2: lastSequence ReadAt tolerates a short final read. ReadAt may return io.EOF with n < len(buf) if the file shrank between Stat and the read; treat EOF as non-fatal and use buf[:n] (matches lastEventSequence). P3: oauth stale-reclaim no-op removed. The double os.ReadFile "stale == data" guard compared the file to itself read twice in a row (always true); staleness is decided by the mtime check, so the guard is dropped (behavior-preserving). Tests under -race; cron/hooks/oauth green. A shared filelock helper would DRY the three near-identical locks — left as a follow-up to avoid churning the already-green cron/oauth packages here.
|
Thanks for the thorough review — all blocking + should-fix items addressed in P1 (audit append not cross-process atomic) — fixed. Wrapped P2 #2 (AppendRun resurrect) — fixed. P2 #3 (ReadAt short read) — fixed. P3 #4 (oauth stale-reclaim no-op) — fixed. Dropped the double P3 #5 / #7 — acknowledged, left as-is. All tests under |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Re-reviewed head 8a5880f against the prior REQUEST_CHANGES. Every P1/P2 from the previous round is resolved, and the previously-correct parts (cron lock, AppendEventUnlessExists, transcript dedup, /style wiring) show no regression.
internal/hooks/hooks.go:504 — append() now wraps the read-then-append in store.lockAudit() (internal/hooks/lock.go), an O_EXCL sibling .lock file with token-based release and stale-mtime reclaim, mirroring the cron/oauth locks. lastSequence() is called inside the lock, so two processes can no longer both read sequence N and write N+1. The overclaiming comment is gone — the new comment accurately states store.mu only serializes this process and lockAudit handles cross-process. TestAuditStoreSequenceConcurrent (4 separate *AuditStore handles sharing one file) exercises exactly the scenario the lock was added for.
internal/cron/store.go:266 — AppendRun now acquires lockJob and stats metadata.json before MkdirAll; a missing dir returns nil (no-op, no resurrection). fireJob (internal/cli/cron_run.go:191) now uses store.Mutate, which returns ErrJobNotFound for a removed job and returns early before AppendRun is reached. Even if a Remove lands in the window between Mutate releasing the lock and AppendRun acquiring it, AppendRun's own metadata check bails. TestAppendRunDoesNotResurrectRemovedJob and TestMutateRemovedJobReturnsNotFound cover both paths.
internal/hooks/hooks.go:649 — ReadAt's error is now checked with !errors.Is(rerr, io.EOF), so a short read (EOF) uses the bytes actually read (buf = buf[:n]) instead of failing. The io import is added. The full-scan fallback for records longer than the 8 KB tail window is preserved.
internal/oauth/lock.go:60 — the double ReadFile that compared the file to itself is removed; stale reclaim now keys off the mtime check alone, with a comment explaining the old no-op guard.
accountingMu is retained but the comment (internal/specialist/accounting.go:14) now correctly describes it as a process-local fast path, with the real dedup guarantee coming from AppendEventUnlessExists under the session lock (in-process mutex + cross-process file lock). The new TestAuditStoreSequenceConcurrent uses 4 independent *AuditStore handles (separate store.mu) as a cross-process stand-in — the only way store.mu wouldn't serialize them is via lockAudit, which is the point.
Update, Mutate, Remove, and AppendRun (internal/cron/store.go). Mutate provides the atomic read-modify-write fireJob needed.internal/sessions/store.go:531): atomic check+append under lockSession; the ReadEvents-doesn't-relock note prevents a future deadlock trap.internal/tui/transcript.go:103): O(n) bulk dedup, byte-identical to the per-row form, tested.responseStyleContext (internal/agent/system_prompt.go) injected into buildSystemPrompt; "balanced"/unknown stays byte-identical, tested.internal/cron/lock.go, internal/hooks/lock.go, internal/oauth/lock.go) — acknowledged in the hooks lock comment as a follow-up for a shared filelock helper.Verdict: APPROVE. All blocking issues are resolved with appropriate tests and accurate comments.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
Successfully merging this pull request may close these issues.
There was an error while loading. Please reload this page.