Record concurrency audit findings
This commit is contained in:
317
docs/roadmap/audit/04-concurrency.md
Normal file
317
docs/roadmap/audit/04-concurrency.md
Normal file
@@ -0,0 +1,317 @@
|
||||
# Concurrency Audit
|
||||
|
||||
Reviewed on 2026-11-30 against commit
|
||||
`f02e7ec8deabc0ad7527803298c317f0cfcff21b`.
|
||||
|
||||
## Scope And Evidence
|
||||
|
||||
The review followed goroutine ownership, shared mutable state, channel
|
||||
lifetimes, cancellation, subprocess supervision, local session locking,
|
||||
destructive commands, remote publication, and input acquisition. It included
|
||||
interactions among application orchestration, stages, manifests, artifact
|
||||
storage, HTTP/subprocess adapters, and object storage.
|
||||
|
||||
Codebase-memory-mcp supplied symbol discovery and caller/callee tracing. Direct
|
||||
source inspection supplemented incomplete same-named Go method indexing, and a
|
||||
non-test-source search checked the inventory of goroutines, channels,
|
||||
synchronization primitives, and cancellation operations. The maintained Go
|
||||
1.27.4 `os/exec` implementation was inspected for wait and stream-copy lifetime
|
||||
semantics.
|
||||
|
||||
Existing checks passed with `GOTOOLCHAIN=go1.27.4`:
|
||||
|
||||
```sh
|
||||
go test -race -count=1 ./...
|
||||
go test -race -shuffle=on -count=5 ./internal/stage ./internal/artifacts ./internal/adapters/whisperx ./internal/adapters/subprocess
|
||||
go vet ./...
|
||||
```
|
||||
|
||||
No race-detector warning was observed. The findings below are source-established
|
||||
ordering/lifetime hazards; this pass did not dynamically reproduce their
|
||||
specific interleavings. Existing tests were inspected to establish what they
|
||||
exercise. No production code or tests were added or modified. No live S3
|
||||
service or paid downstream provider was used. Native execution evidence is
|
||||
from Linux, not macOS.
|
||||
|
||||
Passing race tests cover only exercised memory-access interleavings. They do
|
||||
not establish cross-process filesystem exclusion, atomic remote creation, or
|
||||
correct behavior after the exceptional reaping timeout described below.
|
||||
|
||||
## Current Concurrency Architecture
|
||||
|
||||
Narratio executes its fixed pipeline stages sequentially. Application
|
||||
orchestration owns the invocation and session lock; stage code owns its local
|
||||
work, and adapters own HTTP and subprocess lifetimes. ConfigKit configuration
|
||||
resolution completes before stage execution. The manifest is invocation-owned
|
||||
mutable authority rather than a generally concurrent store.
|
||||
|
||||
| Area | Implemented ownership and synchronization |
|
||||
| --- | --- |
|
||||
| Run, standalone preflight, restore, and final cleanup stage | One per-session OS file lock spans local state transitions. Finalization precedes release. Restore plans local changes under that lock. |
|
||||
| Transcription | A bounded `errgroup` owns speaker workers and joins them before returning. A mutex serializes collection checkpoints and promotion of saved manifest evidence. Jobs have distinct output paths. |
|
||||
| WhisperX HTTP | One immutable client can serve workers. Each attempt/replay has its own audio handle and multipart reader. Mutexes protect close/error state; context callbacks close sources to release reads. |
|
||||
| Subprocesses | One goroutine calls `Cmd.Wait`; a buffered channel reports completion. The supervisor handles cancellation, timeout, and capture failure, with process-group termination on supported platforms. Stdout/stderr copying is concurrent. |
|
||||
| Diagnostics | Per-stream redactors normally have one copying owner. A shared mutex protects diagnostic file writes, tails, and limit reporting; safe final flush depends on stream-copy completion. |
|
||||
| Configuration and shared schemas | Configuration acquisition belongs to an invocation. Bundled schema compilation uses `sync.Once`, followed by read-only schema access. |
|
||||
| Remote publication | Immutable objects and a commit precede current-pointer selection. Lock creation/replacement uses provider conditions; publication rechecks initially unlocked sources before selecting the pointer. This is not a distributed transaction. |
|
||||
|
||||
Manual whole-session cleaning is the important exception to local lock
|
||||
participation, as described in CN-01.
|
||||
|
||||
## CN-01 — P1: Whole-session cleaning bypasses and can dismantle session exclusion
|
||||
|
||||
Status: Open
|
||||
|
||||
**Relevant code.**
|
||||
[clean_command.go](../../../internal/app/clean_command.go):
|
||||
`cleanSelectedSession` (line 70) and `cleanScopedTarget` (line 115);
|
||||
[paths.go](../../../internal/artifacts/paths.go): `buildSessionPathsFromRoot`
|
||||
(line 228);
|
||||
[local.go](../../../internal/artifacts/local.go):
|
||||
`AcquireSessionLockForContext` (line 204) and `acquireSessionLockForPaths`
|
||||
(line 229);
|
||||
[runner.go](../../../internal/app/runner.go): `withLockedInvocation`;
|
||||
[restore_command.go](../../../internal/app/restore_command.go):
|
||||
`restoreSessionState`.
|
||||
|
||||
**Circumstances.** A run, restore, or standalone preflight holds the session's
|
||||
`.lock` while `session clean SESSION` or `session clean --all` executes in
|
||||
another process. Cleaning validates the target and immediately calls recursive
|
||||
removal without acquiring an execution lock. The lock file itself lies inside
|
||||
the removed session tree.
|
||||
|
||||
A possible ordering is:
|
||||
|
||||
1. Invocation A holds the lock on the original `.lock` inode and starts work.
|
||||
2. Cleaning removes its active inputs, outputs, manifest, diagnostics, and lock
|
||||
pathname. Holding an advisory file lock does not prevent these removals.
|
||||
3. Invocation B recreates the session layout and a new `.lock` inode, which it
|
||||
can lock while A still holds the unlinked original inode.
|
||||
4. A continues running or finalizing against pathnames that B now also owns.
|
||||
|
||||
**Consequences.** Active work can lose its files or recreate part of a supposedly
|
||||
cleaned session. More seriously, two invocations can pass the local exclusion
|
||||
boundary and overwrite each other's manifest/products. Cancellation and restore
|
||||
recovery markers cannot repair a lock-identity split after the fact.
|
||||
|
||||
**Potential remediation.** Make destructive manual cleaning participate in the
|
||||
same local coordination scheme as the other mutating operations. Keep the
|
||||
coordination identity outside every tree that cleaning can delete, or retain
|
||||
an equivalent stable admission gate while deleting/recreating session paths.
|
||||
For `--all`, coordinate new session admission as well as already enumerated
|
||||
sessions; checking existing lock files once leaves another creation race.
|
||||
Choose wait-versus-busy-error behavior deliberately.
|
||||
|
||||
A stable workspace gate plus session locks can preserve unrelated-session
|
||||
concurrency. A single exclusive workspace gate is simpler if serializing
|
||||
different sessions is acceptable, but that would be a separate operational
|
||||
tradeoff. Merely acquiring the current in-tree lock and then deleting it does
|
||||
not solve the problem.
|
||||
|
||||
**Existing evidence and gap.** Lock contention, cancellation, process-death
|
||||
recovery, and preflight-versus-final-cleanup exclusion have existing coverage.
|
||||
The manual clean tests exercise deletion and path confinement without an active
|
||||
lock holder. The final pipeline `cleanup` stage already runs under the session
|
||||
lock and preserves its root/lock; this finding concerns the distinct manual
|
||||
whole-session commands. It does not require defending against a privileged
|
||||
external filesystem attacker.
|
||||
|
||||
## CN-02 — P2: Session initialization's no-overwrite check is not atomic
|
||||
|
||||
Status: Open
|
||||
|
||||
**Relevant code.**
|
||||
[operator_helpers.go](../../../internal/app/operator_helpers.go):
|
||||
`writeLocalFile` (line 27);
|
||||
[session_init_command.go](../../../internal/app/session_init_command.go):
|
||||
`initializeSession` (line 96), particularly local installation and the remote
|
||||
`Exists`/`Upload` sequence;
|
||||
[object_store.go](../../../internal/adapters/storage/object_store.go):
|
||||
`UploadConditional` and `WriteCondition`;
|
||||
[s3_backend.go](../../../internal/adapters/storage/s3_backend.go):
|
||||
`UploadConditional` and `uploadReader`.
|
||||
|
||||
**Circumstances.** Two `session init` invocations target the same absent output
|
||||
without `--force`. Locally, both can pass `os.Stat` before either performs
|
||||
`os.WriteFile`. That write uses create/truncate behavior rather than exclusive
|
||||
creation. Remotely, both can observe `Exists=false` before unconditional uploads
|
||||
to the same key. A different ordinary writer creating the destination during
|
||||
either interval has the same effect.
|
||||
|
||||
**Consequences.** Initialization can overwrite an output without the requested
|
||||
force authorization, and both callers can report success. Local writes can
|
||||
also truncate or mix content under an unlucky open/write ordering. Remote
|
||||
initialization loses whichever independently authored session document was
|
||||
uploaded first.
|
||||
|
||||
**Potential remediation.** Enforce absence at the write itself. For local
|
||||
non-forced creation, use an exclusive create such as
|
||||
`os.OpenFile(..., O_WRONLY|O_CREATE|O_EXCL, ...)`, with normal write/close error
|
||||
handling. For remote non-forced creation, use the existing
|
||||
`UploadConditional` boundary with `RequireAbsent=true` and translate a failed
|
||||
condition into the existing already-exists/conflict outcome. The preliminary
|
||||
existence lookup can remain an operator hint, but cannot authorize a later
|
||||
unconditional write.
|
||||
|
||||
Keep deliberate forced replacement separate. This fix needs neither a
|
||||
distributed lock nor a new crash/power-loss guarantee. Existing initialization
|
||||
tests cover local/remote creation and configuration semantics, but do not race
|
||||
two creators against the same target. Existing storage conditional-write tests
|
||||
already protect the necessary provider-side mechanism.
|
||||
|
||||
## CN-03 — P2: The exceptional subprocess reap timeout releases ownership too early
|
||||
|
||||
Status: Open
|
||||
|
||||
**Relevant code.**
|
||||
[execution.go](../../../internal/adapters/subprocess/execution.go):
|
||||
`executeOwnedCommand` (line 32) and `terminateAndReap` (line 73);
|
||||
[run.go](../../../internal/adapters/subprocess/run.go): `Run` (line 41);
|
||||
[diagnostics.go](../../../internal/adapters/subprocess/diagnostics.go):
|
||||
`diagnosticWriter.Write`, `Flush`, and `logWriters.Close`;
|
||||
[result.go](../../../internal/adapters/subprocess/result.go):
|
||||
`boundedResultWriter`;
|
||||
[Scriptorium adapter](../../../internal/adapters/scriptorium/subprocess.go):
|
||||
`RunArtifact` and `RenderArtifact`.
|
||||
|
||||
**Circumstances.** After cancellation or capture abort, graceful and forceful
|
||||
wait timers expire before the wait channel yields a result. `terminateAndReap`
|
||||
returns an error without receiving from `waitCh`. `executeOwnedCommand` then
|
||||
reads `cmd.ProcessState`, and `Run` proceeds toward diagnostic flush/closure
|
||||
and caller return, even though the goroutine running `cmd.Wait` may still be
|
||||
active.
|
||||
|
||||
This is an exceptional path, for example when process reaping or output-copy
|
||||
completion is delayed beyond the internal wait windows. It is not necessary
|
||||
to assume that normal cancellation always reaches it. Go's `Cmd.Wait` sets
|
||||
`ProcessState` and joins stream copying before returning. `WaitDelay` closes
|
||||
pipes when its timer expires, but its implementation still waits for copying
|
||||
goroutines; it cannot interrupt an arbitrary blocked destination `Write`.
|
||||
Process-group disposal does not join the Go wait goroutine.
|
||||
|
||||
**Consequences.** There is no completion-channel synchronization for reading
|
||||
`ProcessState` on this branch. A delayed wait can subsequently write that field.
|
||||
Stream copy can also overlap final redactor flushing, whose per-stream pending
|
||||
state relies on a single owner rather than a flush/write mutex. Callers can
|
||||
close a stdout result file after `Run` returns while its copying goroutine
|
||||
still owns a write to it. A blocked write can also stall final flushing or
|
||||
leave the wait/copy goroutines alive. Returning an error does not by itself
|
||||
make those shared resources safe to reuse or close.
|
||||
|
||||
**Potential remediation.** Keep one supervisor responsible for the command and
|
||||
all associated I/O until completion is joined. Signal-escalation deadlines and
|
||||
completion/ownership are different concerns: do not treat expiry of the former
|
||||
as proof of the latter. Inspect `Cmd` state and flush/close writers only after
|
||||
the wait result is received. Where bounded pipe teardown is necessary, own
|
||||
and close the relevant pipes before joining their copying operations.
|
||||
|
||||
The simplest safe approach can retain bounded graceful/forceful escalation
|
||||
while joining completion afterward. If returning before completion remains a
|
||||
requirement, it needs an explicit ownership handoff that also protects
|
||||
caller-owned output destinations; adding a mutex around `ProcessState` reads
|
||||
or starting an unowned background reaper would not suffice. Scope shutdown
|
||||
claims accurately for delayed kernel I/O rather than introducing an absolute
|
||||
termination-time guarantee.
|
||||
|
||||
**Existing evidence and gap.** Tests exercise ordinary cancellation, timeout,
|
||||
capture overflow, retained descendant streams, and descendant disposal after
|
||||
leader exit. `TestTerminateAndReapPreservesWaitAndCleanupErrors` starts with an
|
||||
already populated wait channel. Those tests passed, including repeated race
|
||||
runs, but do not establish safe ownership after the final wait timer expires.
|
||||
No dynamic race or permanent goroutine leak was reproduced in this pass.
|
||||
|
||||
## CN-04 — P2: S3 audio provenance can combine two object generations
|
||||
|
||||
Status: Open
|
||||
|
||||
**Relevant code.**
|
||||
[prepare.go](../../../internal/stage/prepare.go):
|
||||
`materializeS3AudioInputs` (line 423) and `listS3AudioObjects`;
|
||||
[s3_audio.go](../../../internal/audio/s3_audio.go):
|
||||
`MaterializeS3Audio` (line 35) and `downloadObjectAtomic`;
|
||||
[download_writer.go](../../../internal/adapters/storage/download_writer.go):
|
||||
`DownloadTo`;
|
||||
[s3_backend.go](../../../internal/adapters/storage/s3_backend.go):
|
||||
`Read` and `DownloadTo`.
|
||||
|
||||
**Circumstances.** Preparation lists object generation A with size N and ETag
|
||||
A. Before downloading that key, an ordinary uploader replaces it with different
|
||||
generation B of the same size. The download fetches the current body, B.
|
||||
Materialization checks the expected size and hashes those bytes, while
|
||||
preparation records size/ETag from the earlier listing, A.
|
||||
|
||||
The S3 `Read` operation already returns metadata correlated with its response
|
||||
body. `S3Backend.DownloadTo` discards that metadata, and the audio result
|
||||
returns a checksum without a downloaded generation. Nothing on this path
|
||||
detects the mismatch before installing the file and recording its provenance.
|
||||
|
||||
**Consequences.** The manifest associates B's bytes/checksum with A's source
|
||||
identity. A later listing of B normally causes a redundant download. A more
|
||||
consequential sequence is a remote rollback to the original A: the recorded
|
||||
ETag/size then match A again, while the local B bytes still match their recorded
|
||||
checksum, so the prepared-copy reuse check can accept B for current source A.
|
||||
This undermines the existing source-identity-plus-checksum reuse evidence.
|
||||
|
||||
**Potential remediation.** Preserve metadata from the same object read used to
|
||||
stream the body. Compare its key/size/generation with the selected identity and
|
||||
fail or reacquire on drift, or explicitly adopt that observed generation and
|
||||
return it for the manifest record. Either approach must keep the recorded
|
||||
identity and materialized bytes from one read together. The existing `Read`
|
||||
boundary provides this information; a second independent listing after download
|
||||
does not reliably bind the body to a generation.
|
||||
|
||||
This is a per-input provenance correction, not a requirement for a bucket-wide
|
||||
or whole-session atomic snapshot. Preserve streaming, sibling-temp installation,
|
||||
and the existing reuse checks. Restore's committed-object checksum/generation
|
||||
verification is a separate additional check; this finding specifically follows
|
||||
normal preparation's audio record construction.
|
||||
|
||||
**Existing evidence and gap.** Audio tests cover changed advertised generations,
|
||||
corrupt or missing prepared copies, failed downloads, size mismatches, and
|
||||
cancellation. They do not replace the remote object between listing and reading
|
||||
or exercise the rollback/reuse sequence. This finding follows the concrete
|
||||
metadata/body data flow; no live-storage interleaving was reproduced.
|
||||
|
||||
## Other Reviewed Behavior
|
||||
|
||||
- Speaker work is joined before the stage returns. Loop jobs are captured
|
||||
separately, concurrency is bounded, and the first worker error cancels
|
||||
sibling adapter contexts. Accepted completions serialize through one mutex
|
||||
and save detached collections before updating live manifest authority.
|
||||
- Analysis executes configured artifact work sequentially. It shares the
|
||||
checkpoint mechanism with transcription without adding another concurrent
|
||||
writer to the same invocation's manifest.
|
||||
- HTTP body factories own independent handles for replay. Body/source locks,
|
||||
the once-completed close channel, and cancellation callbacks avoid double
|
||||
closing and release blocked reads in the existing tests. Shared HTTP client
|
||||
settings are read-only during speaker work.
|
||||
- Normal subprocess completion receives the wait result before final stream
|
||||
handling. Buffered wait/abort channels avoid requiring a receiver at every
|
||||
send, and only the supervisor calls `Cmd.Wait`. CN-03 concerns the exceptional
|
||||
completion timeout, not that normal protocol.
|
||||
- Run, restore, preflight, and final pipeline cleanup share a session lock.
|
||||
Terminal manifest persistence narrowly detaches cancellation while holding
|
||||
that lock; adapter work and ordinary checkpoints retain operation contexts.
|
||||
- Remote lock creation/replacement uses provider preconditions. Publication's
|
||||
final lock-check/pointer-write interval is an expressly documented limited
|
||||
race window, not a newly discovered distributed-transaction defect. Read-only
|
||||
inspection similarly does not promise a transactional local/remote snapshot.
|
||||
- Test-fake request/object operations and shared schema initialization have
|
||||
synchronization. Their mutable setup fields are configured before use;
|
||||
this audit does not impose concurrent reconfiguration on those types.
|
||||
|
||||
## Review Outcome
|
||||
|
||||
Four findings warrant consideration. CN-01 is the highest-priority data-safety
|
||||
gap; CN-02 and CN-04 concern check/use races across persistence boundaries.
|
||||
CN-03 identifies unsafe ownership on an exceptional shutdown path despite
|
||||
passing normal-path race tests. The current architecture does not need a
|
||||
general concurrency framework to address them.
|
||||
|
||||
Prior findings remain in [01-correctness.md](01-correctness.md),
|
||||
[02-efficiency.md](02-efficiency.md), and [03-complexity.md](03-complexity.md).
|
||||
This pass does not duplicate them, implement remediations, or establish the
|
||||
absence of other races, deadlocks, or leaks.
|
||||
|
||||
The documentation-link check and whitespace validation also passed. Only this
|
||||
audit record was changed.
|
||||
Reference in New Issue
Block a user