From 7a9bbbde9f850debc87e17e6d305c755b6b53fd8 Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Mon, 30 Nov 2026 19:56:00 +0000 Subject: [PATCH] Record resource management audit findings --- docs/roadmap/audit/05-resources.md | 285 +++++++++++++++++++++++++++++ 1 file changed, 285 insertions(+) create mode 100644 docs/roadmap/audit/05-resources.md diff --git a/docs/roadmap/audit/05-resources.md b/docs/roadmap/audit/05-resources.md new file mode 100644 index 0000000..b373301 --- /dev/null +++ b/docs/roadmap/audit/05-resources.md @@ -0,0 +1,285 @@ +# Resource Management Audit + +Reviewed on 2026-11-30 against commit +`f0e45b60350f930e4de05d4d7c76ffc9ca350077`. + +## Scope And Evidence + +The review traced file descriptors, temporary files/directories, memory and +buffer retention, network bodies and transports, timers, cancellation callbacks, +goroutines, process supervision, and cleanup ownership. It followed their +lifecycles across application orchestration, stages, manifests, artifact +resolution, file operations, and HTTP/subprocess/object-storage adapters. + +Codebase-memory-mcp supplied symbol discovery and caller tracing. Direct +source inspection and a non-test-source search supplemented incomplete indexing +of same-named Go methods. Acquisition sites were matched to normal, error, and +cancellation cleanup paths. Previous audit records were checked to avoid +duplicating their findings. + +These existing checks passed with `GOTOOLCHAIN=go1.27.4`: + +```sh +go test ./... +go test -count=1 ./internal/fileops ./internal/audio ./internal/adapters/storage ./internal/adapters/whisperx ./internal/adapters/subprocess ./internal/stage +go vet ./... +``` + +The focused run exercised existing body-close, cancellation, temporary-file, +failed-transfer, bounded-output, checkpoint, and publication tests. Those tests +support the baseline resource mechanisms; they do not reproduce every finding +below. No production code or tests were added or modified. No benchmarks, +heap profiles, descriptor-exhaustion experiments, disk-filling tests, live S3 +requests, or paid-provider calls were performed. Native execution evidence is +from Linux. + +## Current Resource Ownership + +Narratio runs its fixed stages sequentially and bounds concurrent speaker +transcription. The invocation owns its session lock and composed collaborators; +stages own local attempts and product promotion; adapters own HTTP bodies, +subprocesses, and transfer mechanics. The manifest is the durable progress +ledger. Failed attempts and diagnostics are intentionally retained under +`runs/` until authorized cleanup, while subprocess applications own their +separate state and caches. + +| Resource | Implemented lifecycle | +| --- | --- | +| Session locks | A held file descriptor owns the OS lock. Run, preflight, and restore defer release through terminal persistence. | +| Speaker workers | A bounded `errgroup` joins workers before stage return. Checkpoint updates are serialized and retain the selected complete-collection behavior. | +| HTTP uploads/responses | Multipart attempts and replays own independent audio handles. Cancellation closes sources; the attempt closes all tracked bodies and its response body. | +| Subprocesses and logs | The shared supervisor owns process groups and a wait goroutine. Normal completion joins stream copying before final flushing/closure. Diagnostic streams and result stdout have explicit per-invocation limits. | +| Ordinary file replacement | Sibling temporary files are closed and either renamed or removed on handled errors. Canonical promotion follows validation. | +| Remote control objects | Bounded readers enforce byte limits during transfer, close bodies on every exit, and retain only control-document-sized payloads. | +| Remote products/audio | Transfers stream into temporary files, with validation before installation. RS-02 concerns the missing transfer-time enforcement of already-known sizes. | +| Publication sources | Sources are opened and retained through publication. RS-01 concerns how this scales with the complete source inventory. | +| Configuration and schemas | ConfigKit owns resolution. Configuration acquisition owns downloaded session-file cleanup; compiled bundled schemas are retained once for reuse. | + +## RS-01 — P2: Publication retains one open descriptor per source + +Status: Open + +**Relevant code.** +[publish.go](../../../internal/stage/publish.go): `publishStage.Run`; +[publish_sources.go](../../../internal/stage/publish_sources.go): +`openPublishRunFiles` (line 249), `openPublishSourceUnderRoot`, and +`closePublishSources`; +[publish_transfer.go](../../../internal/stage/publish_transfer.go): +`buildPublishTransferPlan` (line 24), `uploadPublishTransfers` (line 151), and +`closePublishTransfers` (line 309). + +**Circumstances.** Publication first opens every declared current-run archive +file and retains those descriptors. It then opens every previous-cache source, +opens each selected local publication output, and adds the committed manifest. +All remain open until the stage's deferred cleanup. Uploading is sequential; +completed transfers do not release their source descriptors as they finish. + +For R run files, P previous-cache files, and O newly published outputs, the +retained source-descriptor count is R+P+O+1, plus locks, network connections, +diagnostic handles, and temporary directory traversal handles. A product can +also be opened separately for its run archive and publication destination. +Artifact families, per-artifact logs/configuration, speaker outputs, and +previous-session products all contribute to this count. + +**Consequences.** A sufficiently large valid inventory can exhaust the +process's descriptor limit before uploading begins, even though the transfer +algorithm needs only one active upload. Publication then fails with an +open-file error and retrying the same inventory has the same pressure. +Successful/error defers generally close the descriptors afterward: this is +over-retention and capacity scaling, not a demonstrated permanent normal-path +descriptor leak. + +The audit host's soft descriptor limit was 1,048,576; this review did not attempt +to exhaust it. That limit is an environment setting, not a Narratio guarantee. +The source-count dependency remains relevant to deployments with lower limits; +no universal failure threshold is asserted. + +**Potential remediation.** Separate the complete immutable destination mapping +from possession of all its source handles. Use a bounded source-opening window +and close a source after its verified transfer/reuse check, preserving confined +opening, checksum validation, and hashing/uploading through the same descriptor. +Keep the current-pointer write after every declared object has been accepted. + +An upfront validation pass can remain bounded as well. Review the documented +upfront source-rejection behavior when designing that pass; merely replacing +verified descriptors with unchecked pathname uploads would discard an existing +safety boundary. If pinning every original inode for the entire attempt is a +deliberate requirement, disk-backed verified snapshots offer a bounded-FD +alternative with an explicit disk/I/O tradeoff. Raising the descriptor limit +is an operational mitigation, not removal of the scaling dependency. Avoid +imposing a new artifact-count restriction as the default fix. + +**Existing evidence and gap.** Publication tests cover declared-source +confinement/replacement rejection, immutable mapping, upload failure, and pointer +ordering. Their small inventories do not establish behavior near a low +descriptor limit. Retain those safety checks when changing handle lifetime. + +## RS-02 — P2: Known-size downloads consume the full response before rejecting oversize + +Status: Open + +**Relevant code.** +[restore_execute.go](../../../internal/app/restore_execute.go): +`executeRestoreDownloadAction` (line 97), `downloadRestoreTemp`, and +`verifyRestoredObject` (line 282); +[prepare_previous.go](../../../internal/stage/prepare_previous.go): +`hydratePreviousSessionArtifacts` (line 35), `writePreviousTemp`, and +`validatePreviousTemp`; +[s3_audio.go](../../../internal/audio/s3_audio.go): +`downloadObjectAtomic` (line 95) and `validateLocalAudio`; +[publish_transfer.go](../../../internal/stage/publish_transfer.go): +`verifyExistingImmutableObject` (line 219); +[temp_download.go](../../../internal/adapters/storage/temp_download.go) and +[s3_backend.go](../../../internal/adapters/storage/s3_backend.go): streaming +download implementations. + +**Circumstances.** These callers know an expected object size from a committed +declaration, selected source identity, or already-hashed local upload source. +They nevertheless stream the entire remote body into a temporary file and check +size only after the download completes. The underlying `DownloadTo`/`Download` +paths copy to EOF without a caller-supplied byte boundary. + +Examples include restoring a small committed artifact whose remote key was +accidentally replaced with a much larger object, or downloading audio after its +listed object was replaced. The content will eventually be rejected when its +declared size/checksum disagrees, but every returned byte has already consumed +staging space. A faulty or unexpectedly long response can consume far more +space than the already-selected object identity permits. + +**Consequences.** An invalid transfer can fill the workspace or system temporary +volume, interfere with other operations, and hold the session lock for a large +unnecessary download. Handled failures generally remove the temporary file and +preserve the canonical destination; that cleanup does not prevent temporary +exhaustion or the effects on other writers before removal. + +**Potential remediation.** Enforce the existing expected size while streaming. +For a known-size object, inspect metadata from the opened response and perform +a bounded size-plus-one read/copy so the caller can distinguish exact content +from oversize and stop promptly. Close the body and remove partial staging on +failure. A larger `Content-Length` can reject early, but the actual byte count +must remain authoritative. Retain checksum/generation validation and canonical +installation ordering. + +This does not require buffering artifact bodies or using the small-control- +object helper for large payloads. Preserve the current meaning of unknown-size +audio; a universal audio cap would be a separate policy choice. For committed +objects, a declared zero-byte size is known, rather than an unknown-size signal. +Errors should identify the responsible transfer boundary and expected byte +count. The observed-size metadata work in CN-04 is a related acquisition seam, +but provenance correctness and transfer-space enforcement are distinct concerns. + +Stopping at a size already required by validation adds no new user-data limit. +Aggregate workload size and intentionally retained outputs still require the +existing [capacity guidance](../../operations.md#local-state-layout) and +[retention policy](../../operations.md#cleanup). This finding does not promise +to prevent every disk-full condition or reserve disk space. + +**Existing evidence and gap.** Tests establish that short/wrong-size downloads +fail and preserve destinations, and that failed temporary downloads are removed. +The bounded control-object tests demonstrate early metadata rejection and +limit-plus-one enforcement. The large-payload callers above do not use an +equivalent transfer boundary, and existing tests do not establish that an +oversized body is stopped before it is fully staged. + +## RS-03 — P3: Publication's temporary manifest has cleanup gaps before ownership transfer + +Status: Open + +**Relevant code.** +[publish_commit.go](../../../internal/stage/publish_commit.go): +`writeCommittedSessionManifest` (line 99); +[publish.go](../../../internal/stage/publish.go): the helper call followed by +`appendCommittedSessionManifest`; +[publish_transfer.go](../../../internal/stage/publish_transfer.go): +`appendCommittedSessionManifest` (line 117) and `closePublishTransfers`. + +**Circumstances.** The writer creates a file in the system temporary directory. +If writing or closing fails, it returns an empty pathname without removing the +file. The descriptor is closed or a close is attempted, but the created path +remains. On successful writing, a later `os.Open` in +`appendCommittedSessionManifest` can fail before adding the path to the +transfer collection. The caller has no separate removal defer for that gap. +Descriptor exhaustion from RS-01 is one possible cause of this second failure. + +**Consequences.** Failed publication can leave partial or complete +`narratio-committed-session-manifest-*.json` files outside the session's `runs/` +tree. Repeated disk-pressure, permission, or open-file failures can accumulate +untracked temporary files. Session cleanup does not own this system-temp +location. These are disposable publication intermediates, not intentionally +retained attempt diagnostics. + +**Potential remediation.** Give the creator cleanup responsibility immediately +after creation, retaining that responsibility on every error. On successful +return, make the caller responsible for removal until the transfer plan +explicitly accepts ownership. Normal transfer cleanup can then remain the +successful-path owner. Straightforward deferred removal with a clear handoff +is sufficient; no general temporary-resource framework is needed. + +**Existing evidence and gap.** Normal publication puts `TemporaryPath` on the +transfer and `closePublishTransfers` closes/removes it. This finding concerns +the earlier error paths, not a successful-publication leak. Existing tests do +not inject temp-manifest write/close or ownership-handoff open failures. + +## Previously Recorded Resource Findings + +- **EF-01**, in [02-efficiency.md](02-efficiency.md), already records local + recording copies buffered through `os.ReadFile`. One large speaker recording + can require recording-sized RAM even though the repository has a streaming + copy primitive. It remains the clearest existing memory-pressure finding. +- **CN-03**, in [04-concurrency.md](04-concurrency.md), already records the + exceptional subprocess reap-timeout ownership gap. Its effects include live + wait/copy goroutines and premature writer cleanup. It remains relevant to + resource release after cancellation and is not duplicated here. +- **EF-05** records nested inspection-error aggregation whose formatting can + allocate quadratically. That finding also remains relevant without becoming + a new memory-retention issue in this pass. + +## Other Reviewed Lifecycles And Deliberately Retained Behavior + +- Ordinary file/root handles have local closes or explicit ownership returns. + Restore planning closes inspected files and traversed roots; installation + processes temporary objects sequentially. Shared file-replacement helpers + remove sibling temporary files on handled pre-rename failures. +- Downloaded remote session configuration normally transfers its removal + callback to invocation-owned configuration acquisition. Error and + cancellation paths invoke cleanup; successful command finalization closes + that acquisition. Audita's synthetic preflight directory has a local removal + defer. +- WhisperX response bodies, original upload bodies, and replay bodies have + cleanup paths. Per-attempt timeout contexts are canceled after use, and + retry/lock-wait/supervisor timers are stopped where appropriate. Multipart + cancellation callbacks are unregistered or complete through source closure. + No additional normal-path goroutine/timer leak was established. +- HTTP transport pooling and shared compiled schemas have useful reuse + lifetimes. The current CLI does not establish a further unbounded connection + or schema-retention defect merely because those resources remain reusable. + SDK/library-owned pools are not reimplemented in Narratio. +- Diagnostic redaction/tails and adapter result buffers are individually + bounded. Scriptorium requirement inspection uses a bounded stdout writer + despite retaining its JSON in memory. Notarius lanes are validated/staged + one at a time rather than retaining every lane's bytes together. +- Manifests keep current stage/collection state rather than an append-only + invocation history. Whole-collection checkpoint copying and serialization + have a cost, but are deliberately selected behavior rather than a new leak. +- Original tool bundles, failed runs, debug files, reference snapshots, and + subprocess-owned state/caches follow their selected retention/ownership + rules. This audit does not introduce automatic pruning or reinterpret retained + diagnostics as leaked temporary files. Ordinary aggregate disk use remains + an operator capacity/quota responsibility. + +## Review Outcome + +Three new findings warrant consideration: descriptor capacity during +publication, late oversize rejection during known-size transfers, and an +error-path temporary-file ownership gap. They arise within helpers and across +stage/adapter boundaries. The earlier audio-copy memory and subprocess +lifetime findings should also be included when prioritizing remediation. + +No additional ordinary correctness defect was established independently of +these resource findings. The review does not establish absence of other leaks +or exhaustion conditions. The expected direction is shorter resource lifetimes, +streaming, and explicit ownership, rather than new global limits or a generic +resource-management framework. + +The documentation-link check and whitespace validation also passed. Only this +audit record was changed.