Files
scriptorium/docs/roadmap/audit/04-concurrency.md

9.5 KiB
Raw Blame History

Concurrency Audit

Reviewed on 2026-11-24 at source revision 900d956aee54eb1e471358211107b3a132ffa6c8.

Scope And Results

Reviewed application-owned shared state, goroutine/channel ownership, cancellation, shutdown, CLI acquisition/delivery, and concurrency-sensitive tests. Used codebase-memory-mcp to locate concurrency primitives, state, and their callers, then checked source and the relevant library contracts. Checked PromptKit's public concurrency/observer contract in the selected v0.25.0 module, rather than assuming a local upstream checkout matched it. This was not an exhaustive audit of upstream library implementations.

Two findings warrant consideration: the existing production artifact-reader cancellation defect, reconfirmed across an actual HTTP connection, and a test-only worker-lifetime weakness. No additional production data race, deadlock, or unsafe channel operation was substantiated. Passing race tests do not establish cancellation or liveness correctness.

Current Architecture

ConfigKit resolves configuration before engine construction. CommandKit and its integrations own native CLI acquisition and presentation; PromptKit owns execution, retries, admission, and backend queues. The HTTP service constructs one engine and shares it across requests. Handler options and restricted-reader settings are initialized before serving; execution inputs and optional report collectors are request-local. ReleaseKit owns release mechanics. See the component overview and adapter internals.

1. File Acquisition Can Outlive Request Cancellation (P2, Previously Known)

Relevant code: restrictedArtifactReader.Read, readFileArtifact, and readArtifactFile in artifact_reader.go, lines 52–67, 84–96, and 123–148; their invocation through Handler.ServeHTTP in handler.go.

Circumstances: A file read starts while its context is live, then the client disconnects, an operation budget expires, or shutdown cancels the request. The reader checks context only on entry and does not pass it to the file helpers. An existing FIFO inside the allowed root can block opening or remain in io.ReadAll while a writer keeps it open without completing input. The configured byte limit does not bound that wait.

Consequences: The HTTP handler/engine invocation can remain pending after the request context is canceled, retaining a request goroutine and potentially an open file until an external filesystem participant releases it. Repeated abandoned requests can accumulate pending work in a long-running server. The reader can subsequently return successful data despite cancellation. This is not a claim that input preparation has already acquired a backend admission slot, or that every synchronous filesystem call must stop immediately.

Evidence: A temporary standalone diagnostic used the real HTTP handler and restricted reader with a small Runner stub, a loopback HTTP connection, and a synthetic FIFO. Opening its writer established that acquisition had passed the initial context check. Canceling the HTTP client canceled the server request context, but the handler was still pending after a bounded 200 ms observation. Only writing and closing the FIFO released it; the reader returned a nil error with ctx.Err() == context.Canceled. The diagnostic then joined the handler, client, and server and completed under the race detector without a race report. The real-engine operation-budget manifestation is already documented in finding 3 of the correctness audit. This is the same unresolved defect, not a second independent production bug.

Potential remediation: Thread the context through acquisition and check it during reads and before successful completion. Align unsupported-file handling with the selected upstream ordinary reader, which avoids opening an existing FIFO as a regular artifact. If non-regular streaming sources are intended, their acquisition needs an explicitly cancellation-aware design. Preserve the existing lexical-root and byte-limit policy. A goroutine wrapper that merely abandons a blocked read would conceal, rather than fix, the lifetime problem. No symlink sandbox, forced-interruption guarantee, or graceful-drain guarantee is needed to address this defect.

2. Shared-Capacity Test Does Not Own Workers On Failure Paths (P3, Test Only)

Relevant code: TestHandlerSharesBackendCapacityAcrossConcurrentRequests, particularly lines 1087–1118 of handler_test.go, and its blockingLLMClient.Generate, lines 437–456.

Circumstances: The first handler runs in a goroutine with an uncancelable request context. Its fake generator waits for client.release or context cancellation. The test closes release only on the successful path, after several assertions. An earlier t.Fatal bypasses that release and the normal join. Separately, if a capacity regression admits the second request to the blocking client, the test's synchronous second ServeHTTP call waits for the release that the test will perform only after that call returns. That call has no test-controlled deadline or cancellation.

Consequences: A failing assertion can leave the first worker pending; a capacity regression can stall the test instead of producing a bounded, useful failure. The first-start and first-completion timers do not protect the intervening synchronous call. This affects test reliability and regression diagnosis, not production capacity enforcement.

Evidence: Source inspection of the failure/control-flow paths. The current successful path passed both the full race suite and five focused repetitions; those runs do not exercise the missing failure cleanup. No capacity regression was introduced to force this test to fail.

Potential remediation: Give the requests test-controlled cancellable contexts, register cleanup before launching the first worker, and cancel and join owned work on failure as well as success. Bound the second request so unexpected admission cannot trap the test before its cleanup runs. Keep one clear owner for closing release, and retain the existing behavioral checks for capacity rejection, shared peak concurrency, and response privacy. This needs focused cleanup, not a new fixture framework or production time limit.

Other Ownership And Ordering Checks

  • Server shutdown: In serveWithListener, lines 57–64 of server.go, the AfterFunc callback writes cancellationCloseErr before closing closed. If stopping the callback succeeds, it cannot run; otherwise the serving goroutine receives from closed before reading the error. This supplies the required synchronization without a mutex. Callback ownership and channel closure are single-owner. Server.Close intentionally closes connections without joining arbitrary context-ignoring handler work; that is the selected shutdown contract, not an additional finding.
  • Shared engine and reader: One engine is constructed before serving; request overrides do not rewrite its defaults. PromptKit supports concurrent runs and owns backend synchronization. Restricted-reader settings are read-only during service, with per-call handles and bodies. Existing tests protect cross-request admission, retry sharing, and canceled capacity waits.
  • Report observation: Each opted-in request creates its own collector. PromptKit delivers observer callbacks synchronously; the handler snapshots only after Run returns. No collector is shared between requests or handed to an application-owned background goroutine. Its lack of a mutex is not a race in this lifecycle.
  • CLI and configuration: The bootstrap sink belongs to its invocation. Server acquisition occurs before listening; native comparison effects are sequential. The process environment is deliberately shared under ConfigKit's native bootstrap semantics, not a per-request credential snapshot. No concurrent reload path was found. Delivery is sequential and report-file rendering occurs outside reporter callbacks, avoiding reentrant rendering. Caller-owned output paths have no cross-process serialization contract.
  • Process and tests: Signal-context registration is released with its deferred stop function. Reviewed lifecycle tests use cancellation, channel handoffs, and atomic counters; response/buffer reads follow completion on their normal paths. The specific missing failure cleanup is identified above. No parallel tests changing cwd/environment were found. The local release launcher introduces no separate background-worker ownership.

Validation And Limits

  • Go 1.27.0 on Linux/amd64: go test -race -count=1 ./... passed.
  • Five race-enabled repetitions of the existing server cancellation/bootstrap, concurrent-report isolation, shared backend capacity, retry-capacity, and canceled-capacity-wait tests passed.
  • go vet ./... passed. Documentation links and whitespace were checked.
  • The temporary cancellation diagnostic used no provider, credentials, or external service; all its pending work was released and joined.
  • No production code or repository tests were changed or added. Race detection covers executed paths, not all schedules; this audit does not establish a universal absence of races, deadlocks, or leaks in dependencies or unexercised paths.