# Resource Management Audit ## Baseline And Scope Reviewed revision `65ce8f7fe55b91244c4114ea95fb87494a1449b9` on 2026-11-24. Production code is unchanged from the preceding audits. This pass adds only this report; it adds no tests, production changes, or benchmarks. The review followed resource acquisition, ownership, bounds, and release across CLI/configuration composition, reference reads, source/chunk materialization, worker execution, native production and assessment, caches, capture, output encoding, and publication. Code-graph searches located resource operations and their callers. Relevant pinned PromptKit v0.25.0 internals were inspected only where they determine Notarius's handle, admission, HTTP, or timer lifecycle. This is not a general audit of upstream libraries. No file-descriptor, response-body, timer, or goroutine leak was confirmed in the reviewed default execution paths. Three resource-efficiency weaknesses warrant consideration: | Finding | Priority | Affected resource | | --- | --- | --- | | RES-001: Disabled capture still constructs large evidence payloads | P2 | Transient heap, buffers, and unnecessary encoding work in ordinary runs | | RES-002: Intermediate results outlive their consumers | P2 | Retained heap during slow sibling work and in returned run values | | RES-003: Enabled capture repeats the full source for every extraction job | P3 | Debug disk space, write volume, and serialization buffers | These are scaling/lifetime weaknesses, not claims that a small ordinary run must exhaust resources. Bounds and numerical examples below come from source analysis, not measured production memory or throughput. ## Current Resource Architecture The CLI owns one invocation's loaded configuration, optional shared native engine, prepared modules, input bytes, cache collaborator, requested debug recorder, and publication directory. Configuration/engine selections are invocation-local. Input is read into memory; parsing, source units, materialized chunks, typed artifacts, and serialized output are batch-oriented rather than streaming. After serial chunking, one bounded pool runs ready extraction and lane-completion jobs. The coordinator dispatches lazily, cancels siblings on failure, drains started jobs, closes its job channel, and joins workers. PromptKit independently owns backend admission, provider transport, operation deadlines, transient retry waits, structural repair, and conversation state. Admission is released before nested validators run. Prepared cache executions are consumed or discarded. Registry/schema memoization belongs to prepared module instances; the spell catalog is a finite process-level initialization. The debug recorder writes incrementally and retains lifecycle/error state, not whole-run payloads. Native capture releases its prepared snapshot at the operation boundary. Individual cache/output/debug writes close temporary files and atomically rename them; normal error paths remove unpublished temporary siblings. Output, cache, and requested debug bundles have distinct, operator-owned retention policies. ## Findings ### RES-001 — Disabled Capture Still Constructs Large Evidence Payloads **Relevant code:** [writeDebugTimed and envelope builders](../../../internal/framework/pipeline/debug.go#L100), [Runner.Run](../../../internal/framework/pipeline/runner.go#L138), [runChunkPlan's deferred evidence](../../../internal/framework/pipeline/runner_chunk_plan.go#L28), [continueLane](../../../internal/framework/pipeline/runner_concurrent.go#L349), [merge/normalize evidence](../../../internal/framework/pipeline/runner_typed.go#L138), and [RecordEvidence](../../../internal/framework/contracts/producer.go#L79). **Circumstances:** Run with debug disabled, including ordinary deterministic or cache-reuse workloads. Arguments are evaluated before `writeDebugTimed` checks `Enabled()` or `RecordEvidence` checks whether a writer exists. Thus the no-op path is reached only after building the payload. Examples include: - raw source content converted to text and base64 at source/chunk boundaries; - every materialized chunk converted to a debug envelope in the deferred chunk outcome, even when `Execution.Capture` is nil; - all chunks and extraction artifacts converted again when each lane continues; - normalized artifacts and final output files converted before disabled output capture calls. `debugContentEnvelope` creates base64 content even for valid UTF-8 data and also retains its text representation; chunk builders copy unit slices/annotations. These are not cheap references to an already serialized object. For a byte slice of length B, base64 alone produces approximately 4B/3 bytes, in addition to the text, container, and annotation allocations. Concurrent continuations can build separate all-chunk payloads for several lanes. **Consequences:** Explicitly disabling evidence does not eliminate substantial debug-only allocation and hashing work. Large transcripts or artifact sets can create avoidable heap pressure and garbage-collection work, and contribute to an out-of-memory failure under concurrent lane completion. No debug file needs to be written for this to occur. This is transient allocation, not a permanent retained-object leak. **Potential remediation:** Check enablement before constructing expensive debug payloads. Simple guards at stage-owned boundaries are sufficient; a small lazy payload helper is also viable if it makes the repeated pattern clearer. Apply the same rule to the deferred chunk outcome, not only `writeDebugTimed` callers. Keep ordinary artifact encoding/validation outside the guard when execution actually requires it. Do not change requested-capture failure semantics or add a new diagnostic scheduler, buffer pool, or input-size restriction. **Verification:** The call sites and helper bodies establish eager evaluation. Existing debug, capture, cache-hit, deterministic-run, and failure tests passed. They protect evidence content and execution behavior, not allocation absence; passing them does not refute this finding. A correction should preserve enabled capture while keeping expensive payload builders off the disabled path. ### RES-002 — Intermediate Results Outlive Their Consumers **Relevant code:** [laneExtractState](../../../internal/framework/pipeline/runner_concurrent.go#L19), [handleCompletion](../../../internal/framework/pipeline/runner_concurrent.go#L254), [finalizeLaneExtract](../../../internal/framework/pipeline/runner_concurrent.go#L334), [typed lane completion](../../../internal/framework/pipeline/runner_typed.go#L54), [RunOutput and final return](../../../internal/framework/pipeline/runner.go#L73), [diagnostic finalization](../../../internal/framework/pipeline/diagnostics.go#L78), and [JSON output encoding](../../../internal/modules/generic/output/json/encoder.go#L229). **Circumstances:** A step contains many chunks, voluminous artifacts, or lanes with different completion times. A fast lane finishes merging/normalizing while another lane is still executing or correcting model output. Two lifetime gaps exist: 1. Each lane's `results` map retains every extracted typed value, serialized artifact, and diagnostic result. `finalizeLaneExtract` appends those results into ordered `values`/`diagnostics` without dropping the map. After continuation completes, `handleCompletion` stores the normalized output but leaves all extraction references in the lane state. The engine retains every lane state until the whole step returns, so completed lanes' extraction data remains live while unrelated sibling work proceeds. 2. After output encoding, `Runner.Run` returns the same `RunOutput` that still contains private `normalizeOutputs`, reuse-eligibility data, and the original diagnostic-group accumulator. The public `OutputFiles` and finalized `Diagnostics` have already been assembled. In particular, encoded output bytes are separate from the retained normalized artifact bytes. Callers keeping the completed result also keep internal intermediates they cannot directly release. `failOutput` similarly finalizes diagnostics without retiring private state. Copying a result into the ordered slice does not itself duplicate every payload: many references point at the same values. The problem is that these references keep the underlying objects/buffers reachable after their final consumer, alongside the separately constructed merged, normalized, and encoded forms. **Consequences:** Worker count bounds active operations but not the total live extraction data. Peak heap can include all lanes' original typed/serialized extractions plus their later-stage outputs, even after most lanes finish. Slow provider responses prolong this retention. Retaining several completed run results in an embedding compounds the unnecessary normalized-byte/diagnostic retention. This is not an indefinitely growing process-global cache: the memory is collectible when the containing engine/result becomes unreachable. **Potential remediation:** Release references at their actual ownership boundaries: - retire the reordering map once ordered values/diagnostics own what continuation needs; - after a continuation returns, have its coordinator retire the completed lane's extraction values/diagnostics and remaining reorder state; - at the outer `Runner.Run` return boundary, preserve public files, finalized diagnostics, and fallback count while retiring private execution accumulators on success and failure. Do not discard normalized artifacts before ordered-step handoffs, evidence projection, or final output encoding finish. Do not clear the contents of shared objects or backing arrays that downstream artifacts still reference; dropping the owner's references is the intended operation. No forced garbage collection, new global memory cap, or pipeline streaming redesign is required for this cleanup. **Verification:** The state fields and absence of release in finalization/completion and return paths substantiate retention. Existing ready-continuation, ordering/cancellation, handoff, output, and retained-diagnostic tests passed; they do not measure heap reachability. Recheck those behaviors when shortening lifetimes, especially slow sibling completion and failures after accepted predecessor work. ### RES-003 — Enabled Capture Repeats The Full Source For Every Extraction Job **Relevant code:** [captureOperationInputs](../../../internal/framework/pipeline/operation_capture.go#L9), [per-chunk extraction call](../../../internal/framework/pipeline/runner_concurrent.go#L289), [full-source debug projection](../../../internal/framework/pipeline/debug.go#L130), [capture serialization](../../../internal/framework/debug/recorder.go#L87), and [atomic JSON writing](../../../internal/core/fileio/fileio.go#L90). **Circumstances:** Enable debug for a large multi-chunk, multi-lane pipeline. Every extraction job calls `captureOperationInputs`, which includes the complete parsed `target.source`, not just the chunk. It also includes reference payloads and the chunk/source-input representations. A full source snapshot is already recorded at run scope. Each operation then serializes another copy into its own `inputs.json`. This applies before extractor execution and also on cache hits. For C chunks, L extraction lanes, and S bytes in the serialized full-source projection, those source fields alone contribute approximately C × L × S bytes. For illustration, 80 chunks × 8 lanes × a 4 MiB source projection is 2.5 GiB, before references, chunk representations, native evidence, or other stage files. This is arithmetic from the write pattern, not a measured bundle. Where chunk count grows with transcript size, this repeated component grows quadratically with the input rather than with only the useful chunk data. **Consequences:** A single requested debug run can consume disproportionately large disk space and serialization buffers. Disk exhaustion can fail required capture, and therefore the invocation, after substantial model work has already completed. Atomic temporary files protect publication but do not remove this capacity risk. Incremental recorder writes avoid a whole-run memory ledger; they do not bound disk usage or the size of each individual JSON serialization. **Potential remediation:** Consider capturing immutable source/reference material once per bundle and using bundle-local references plus operation-specific source ranges/selection metadata. Keep actual inputs recoverable and preserve native prepared/result/exchange evidence; removing selected evidence or truncating it silently is not the recommendation. The CLI's already captured run-level source is a natural reuse point. A bundle-aware representation must account for direct `EvidenceWriter` users rather than assuming every writer has a CLI filesystem root. This is an explicit convenience/capacity tradeoff, not a violation of a selected size guarantee. [ADR-0024](../../adr/0024-publish-artifacts-with-native-reports-and-debug-evidence.md) permits evidence duplication, and the [operation-input test](../../../internal/framework/pipeline/operation_capture_test.go#L17) currently expects self-contained inputs. Review that choice deliberately before changing it. Retain complete available bundle evidence, exact secret omissions, and required-capture failure behavior. Do not add automatic bundle deletion, quotas, a retention daemon, or new operator restrictions as an incidental fix. ## Reviewed Lifecycles Without A Confirmed Leak | Area | Evidence and assessment | | --- | --- | | File descriptors | Reference materialization closes each opened file before proceeding to the next binding, including read/size failures. `os.ReadFile`/embedded `fs.ReadFile` own their handles. Atomic writers close on success and write/chmod errors. Debug latest-link allocation closes its temporary file before replacing it with a link. No defer-inside-a-large-file-loop descriptor accumulation was found. | | Temporary publication files | Ordinary write, chmod, close, and rename failures remove the writer's own unpublished temporary sibling. Existing failed-publication tests check the directory for leftovers. Cleanup cannot be guaranteed when removal itself fails, the process is killed, or the machine stops; no stronger filesystem guarantee is inferred. | | Worker goroutines/channels | Dispatch is lazy rather than allocating one goroutine per chunk. The coordinator drains started work before closing jobs and waiting. Existing tests verify zero remaining active jobs and reusable native capacity after cancellation. Arbitrary extensions ignoring context cannot be forcibly stopped by that mechanism. | | Prepared executions | `RunProducer` defers `Discard` immediately after successful preparation, covering hits, lookup/capture failures, and early returns. Pinned native `RunPrepared` claims the payload and defers clearing execution-only references. Preparation does not start an idle operation timer or occupy admission. | | Timers/retry waits | The local worker cancellation function is deferred. Native operation scopes and request timeouts defer cancellation; native retry wait timers defer `Stop`. The lost-cancel analysis passed. Notarius creates no separate timer/retry service around those APIs. | | HTTP bodies/connections | Provider calls belong to the shared native engine. Inspected built-in transport code defers response-body closure on successful HTTP dispatch before status/decoding exits and bounds response decoding. Standard transport idle connection reuse is intentional; Notarius should not close a caller-supplied shared transport after every operation. No missing Notarius engine-close obligation was found in the pinned API. | | Registry/schema caches | Mutable caches live on prepared module/resolver instances. The ordinary CLI constructs that set per run; stable stage references mean chunk count does not create one distinct registry view per chunk. These are not process-global histories. Long-lived direct reuse with arbitrarily many changing references/schemas can grow instance caches; that different usage needs an explicit lifetime/cache policy rather than an assumed CLI leak. | | Diagnostic/observation buffers | Producer diagnostics and final aggregation enforce group/sample bounds. Private pre-aggregation storage is covered by RES-002. Native debug observation retains member IDs/terminal facts, not full exchanges; the recorder itself retains only lifecycle/error state, and `NativeCapture.Finish` clears its prepared snapshot. | | Output/cache/debug retention | Preserving published output, available partial failure directories, accepted cache entries, and requested evidence is selected behavior. Operator-owned cleanup is documented in [Operations](../../operations.md#cleanup). Absence of automatic eviction/deletion is not itself a leak or authorization to add it. | ## Validation And Limits The following completed successfully at the reviewed revision: ```sh GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go test -mod=readonly -count=1 ./... GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go vet -mod=readonly -lostcancel ./... GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go test -mod=readonly -count=1 go.maximumdirect.net/promptkit -run '^(TestPreparedExecutionDiscardAndFormattingDoNotExposePrivateState|TestPreparedExecutionRetainsTimeoutWithoutIdleTimer|TestCoordinateReleasesCapacityBeforeCallback|TestOperationBudgetInterruptsRetryAndRepair)$' ``` Existing test source was inspected to identify the protection actually provided: worker/native admission release, cancellation, prepared-handle disposal, bounded reference reads, failed cache publication cleanup, recorder failure/finalization, partial output retention, and native deadline/retry lifecycle. The focused upstream tests use fake clients/transports and synthetic time. No credentials, live provider, benchmarks, new tests, or heap-exhaustion experiments were used. Passing functional checks does not prove bounded peak memory or debug size; the findings are supported by retained references, eager construction, and repeated write sites. Whole-input loading and detached mutable validator views are deliberate parts of the current batch-oriented design, not newly discovered leaks. The earlier [efficiency audit](02-efficiency.md) covers repeated full-source indexing/text scans and their allocation cost. The [concurrency audit](04-concurrency.md) already records the missing process-signal adapter and implicit extension concurrency obligations. Those findings remain separate; this report does not imply they have been corrected. Prioritize keeping disabled capture cheap, then shortening intermediate lifetimes. Evaluate bundle-local evidence reuse as a separate capacity/convenience choice. Retain the existing worker/admission separation and ordinary standard-library cleanup; no repository-wide resource manager is indicated. Report links and the final documentation diff were checked locally.