16 KiB
Concurrency Audit
Baseline And Scope
Reviewed revision ef09060b5804ac0197df51bae2708fb0ab4d1053 on 2026-11-24.
Production code remains unchanged from 3887d89b763b7040efc866d4a57eb910d8778730;
the intervening commits contain the earlier audit reports. The audit adds no
new tests or production changes. The accompanying release-policy wording
correction is separate from these findings.
The review used the current code graph to find goroutines, channels, mutexes, atomic operations, once-initialized state, and cancellation paths. It followed their callers and shared data through preparation, extraction, validation, continuation, state/capture, CLI invocation, and shutdown. Pinned CommandKit v0.8.0, ckconfig v0.11.0, and PromptKit v0.25.0 sources were inspected where their callback/context behavior determines Notarius's synchronization obligations. This is not a general audit of those upstream repositories.
The complete default suite passed with fresh race instrumentation, and the copy-lock vet analysis passed. No data race, deadlock, unsafe channel close, or goroutine leak was confirmed in the exercised production paths. Two narrower integration weaknesses warrant consideration: process signals do not enter the implemented cooperative-cancellation path, and concurrency obligations at extension boundaries are insufficiently explicit. These are not race-detector failures.
Current Concurrency Architecture
The fixed typed pipeline remains:
input -> chunk -> ordered steps [per-chunk extract -> merge -> normalize] -> output
Parsing/chunking and ordered-step barriers are sequential. Within a step, one bounded worker pool executes ready extraction jobs and ready lane continuations. The coordinator alone updates lane accounting, restores output order, and selects terminal errors from reported failures. A continuation becomes ready after that lane's extracts finish; workers do not hold slots while waiting for dependencies.
Each prepared lane retains one extractor and one instance of each configured extract validator; those instances are reused across chunk jobs. Typed codecs are also reused. Current production implementations are stateless during operations or protect mutable memoization. Request-local candidates, findings, and producer continuation state remain local to their operation.
One native PromptKit engine is shared across model roles. Native backend admission is separate from worker accounting and is released before nested assessment. Notarius delegates transport/retry/timer/history mechanics to PromptKit rather than adding another scheduler. Candidate/context views are detached per validator; the full parsed source is shared read-only by extraction jobs.
Debug uses scoped operation paths, mutex-protected native/capture state, and a serialized recorder. The CLI finalizes requested capture after runner workers have joined. Cache files use unique temporary names and atomic replacement; registry projections and compiled schemas use synchronized memoization. Configuration loaders belong to one invocation, while registries are populated before execution and then read rather than concurrently registered.
Findings
CONC-001 — Process Signals Bypass Cooperative Cancellation And Cleanup
Priority: P3 — process shutdown integration weakness; not an in-process leak.
Relevant code:
main,
RunWithOptions,
run command finalization, and
worker cancellation/draining.
The main executable calls App.Execute(context.Background(), ...). There is no
OS-signal-to-context adapter in the executable or Notarius CLI. Inspection of the
pinned CommandKit App.Execute confirms that it uses the supplied context and does
not install such an adapter on Notarius's behalf.
Circumstances: A terminal user interrupts a run, or a subprocess supervisor
sends SIGTERM while extraction or validation is in progress. Ordinary Unix signal
handling terminates the process; it does not cancel the context supplied to the
pipeline. In contrast, embedded callers using App.Execute with their own
cancellable context do reach the existing graceful path.
Consequences: The worker drain/join, native cancellation, capture terminalization, and normal failure/report handling cannot run to completion on that process-signal path. A debug bundle can retain its running overview without a terminal outcome, and a temporary file interrupted before rename can remain. This does not imply that atomic cache replacement publishes partial JSON or that kernel resources survive process exit. It also does not claim an existing promise of graceful signal handling: the weakness is that ordinary process cancellation cannot use cleanup already implemented for context cancellation. The subprocess guides ask callers to propagate cancellation, so this distinction is operationally useful.
Potential remediation: Connect supported process signals to a cancellable
root context at the executable boundary, using signal.NotifyContext or equivalent
idiomatic code, and pass that context to native execution. Retain normal context
ownership for embedded consumers. Deliberately choose how repeated signals restore
normal termination or escalate; avoid accidentally swallowing every subsequent
interrupt while waiting for cleanup.
Do not add a separate shutdown worker pool, background cleanup service, automatic artifact deletion, or a new hard shutdown deadline without a concrete requirement. Graceful cancellation remains cooperative; SIGKILL cannot be handled, and a custom collaborator that ignores context cannot acquire a termination guarantee merely from this change.
Evidence and follow-up: This is a static end-to-end context/signal finding, not a signal-injection reproduction. Existing CLI cancellation coverage passes a cancellable context directly, so it does not cover the executable gap. The existing worker cancellation/admission tests substantiate the downstream cleanup path. A future correction should use a focused subprocess test with a local fake backend, an ordinary supported signal, and retained capture evidence; no real provider is needed.
CONC-002 — Extension And Explicit Capture Concurrency Obligations Are Implicit
Priority: P3 — extension-contract documentation weakness; current default implementations were not found to race.
Relevant code: prepareLane, worker execution, runExtractJob, candidate assessment, typed interfaces, and ExecutionOptions/EvidenceWriter. The extension recipe explains typed registration and ownership but does not clearly state the overlapping-call pattern for retained instances and collaborators.
Circumstances: A new extractor or extract validator stores a per-call slice, counter, or candidate in its instance fields without synchronization, assuming that each chunk receives a fresh implementation. Preparation actually constructs one instance for the selected binding, and different workers can call it at the same time. Detaching request data does not isolate the receiver's fields. Similarly, shared codec methods can be invoked by several extraction/assessment jobs, and a shared injected client or preparation callback can be reached from several native calls.
There is a related capture distinction: Runner.Run serializes its Debug
recorder, but an explicit RunInput.Execution.Capture is selected directly by
operationExecution
and scoped without adding one shared writer lock. Separate NativeCapture
instances protect their own state; their mutexes do not serialize calls into a
shared underlying EvidenceWriter. An unsynchronized map/buffer writer supplied
through that route can therefore receive overlapping writes. The current CLI
recorder and concurrent native-capture test writer are synchronized.
Consequences: Extensions or direct framework integrations can introduce data races, mixed candidate state, or lost evidence despite using the typed interfaces and detached request views correctly. Existing tests can remain green because they use stateless implementations or explicitly synchronized test writers. No current default implementation is accused of this defect; the missing signal to implementers is the weakness.
Potential remediation: Document the current call/ownership model in the canonical module-internals guide and add concise interface comments or links at the relevant boundary:
- Prepared extractors and their extract validators can receive concurrent calls within one run; keep per-call state local or synchronize retained mutable state.
- Codecs are shared collaborators, while merge/normalize for one lane follow its completed extraction; do not imply universal concurrent invocation for every module method.
- Parsed source used by extractors is shared read-only; detached validator views do not make arbitrary shared module fields safe.
- Explicit capture writers and shared callbacks must account for the actual parallel call pattern. Link to native client/observer contracts where the requirement belongs upstream rather than duplicating library documentation.
- The runner waits for operation methods it dispatched, not arbitrary background goroutines an extension might start. Any added asynchronous work needs an explicit lifetime relative to its operation and borrowed collaborators.
For explicit capture, prefer making the existing caller-side concurrency obligation clear and pointing to the safe recorder. If support for serial-only writers is desired, select that separately and wrap the shared writer once per run. A different mutex in every operation wrapper would not solve the race. Do not silently promise thread safety for all callbacks, add locks to every stateless module, serialize all extraction, or broaden live-registration support.
Evidence and follow-up: Concurrent native capture coverage uses a mutex-protected writer and atomic callback counters. Existing resolver, schema-cache, source/metadata isolation, and concurrent-runner tests exercise the safe implementations. Documentation clarification alone needs no new runtime test; future mutable extensions should test their own shared-instance behavior where the risk warrants it.
Reviewed Paths Without A Confirmed Defect
| Area | Evidence and assessment |
|---|---|
| Goroutine ownership and channels | laneEngine.startWorkers, collect, and run form one ownership chain: add workers before starting, stop dispatch on observed cancellation, drain each dispatched job's result, close jobs, then wait. The result channel need not be closed because its lifetime ends with the engine and no receiver ranges over it. No separate goroutine is launched per chunk or waiting continuation. |
| Lane state and ordering | Coordinator-only remaining, results, diagnostics, pending continuations, and completed outputs are not concurrently mutated by workers. Continuations are dispatched only after all lane results arrive, providing a channel synchronization boundary for the finalized data. Outputs are restored to configured order; error selection is among reported failures, not all hypothetical failures canceled work might otherwise have produced. |
| Cancellation, continuation, and fallback | Native work uses the job context; delivered candidates are assessed sequentially within that operation. Failed/undelivered responses do not revive earlier candidates. Cancellation does not initiate fallback. After sibling cancellation, started jobs are drained before the runner returns. |
| Nested LLM validation/admission | Worker ownership is not reacquired for nested validation. Producer/native admission is released before assessment; tests with one shared backend slot successfully execute nested validators. There is no observed worker/admission lock cycle. |
| Shared module data | Registry resolver caches and generic schema compilation are mutex-protected; cached views are immutable and public projections copy mutable data. Spell catalog initialization uses sync.Once; case folding is created per call. Production extraction/normalization state is local to each invocation rather than retained candidate state on the module. |
| Validator/request isolation | Candidate bytes are encoded once, then decoded separately for typed validators. Source/chunk/metadata/reference views are detached at validator boundaries; chunks and metadata handed to extraction are owned. Atomic assessment numbers avoid concurrent capture-name reuse. |
| Native callbacks and capture locks | Native observer composition/coordination are synchronous along each execution. NativeCapture guards its own counters/prepared snapshot/error, normal recorder calls are serialized, and the CLI finalizes after workers join. No production lock-order cycle or write-after-finalization path was confirmed. CONC-002 describes explicit external writer obligations. |
| Cache and filesystem concurrency | Stores retain immutable roots; unique temporary files and atomic rename publish whole entries under concurrent replacement. Current-source cache indices use a run-local sync.OnceValue. Concurrent latest updates retain real bundles and a valid relative link; no monotonic timestamp-order promise is inferred from simultaneous starts. |
| Configuration/registry lifetime | Native loaders are fresh per invocation. Pinned ckconfig comparison loads its two sides sequentially, so the invocation-owned selection slice is not concurrently mutated by those callbacks. Domain registries are constructed before worker execution; no hot-registration guarantee or additional lock requirement is inferred. |
| Reporting/observation | The CLI's debug execution group uses native synchronized observation and is snapshotted after worker completion. Diagnostics are local or coordinator-owned before final aggregation; normal process output is published/reported after the runner returns. |
Validation
Both commands completed successfully at the reviewed revision:
GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go test -mod=readonly -race -count=1 ./...
GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go vet -mod=readonly -copylocks ./...
The fresh race run included existing coverage for worker limits and ready continuations, cancellation/draining and admission release, nested validators, concurrent capture, registry reuse, schema compilation, atomic cache replacement, debug allocation/finalization, and CLI cancellation. Test source was inspected to understand what these checks actually exercise. No real credentials, live provider calls, or new test cases were used.
Passing race detection covers executed interleavings, not every possible schedule
or extension. Executable subprocess tests build their child with ordinary
go build, so parent go test -race does not automatically instrument that child.
No process-signal or forced-shutdown experiment was performed. No claim is made
about arbitrary custom modules/writers that ignore context or mutate shared inputs,
or about recovery from SIGKILL, machine failure, or hostile filesystem mutation.
The review supports retaining the current coordinator, worker/admission separation, and synchronization structure. Address the process-signal boundary and clarify extension ownership proportionately; no repository-wide concurrency framework is indicated. Earlier audit findings remain independent and are not resolved by this report. Local report links and the final documentation diff were checked.