From 8cfe330194ea0a4d06ede98655d886ede0dcc4e1 Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Tue, 24 Nov 2026 15:28:37 +0000 Subject: [PATCH] Record resource management audit --- docs/roadmap/audit/05-resources.md | 192 +++++++++++++++++++++++++++++ 1 file changed, 192 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..4751014 --- /dev/null +++ b/docs/roadmap/audit/05-resources.md @@ -0,0 +1,192 @@ +# Resource Management Audit + +Reviewed on 2026-11-24 at source revision +`029cb863280c37cb9688162e4542ddd5cba23ef4`. + +## Scope And Results + +Reviewed application-owned memory/buffer lifetimes, file handles, network +connections, timers, goroutines, cancellation, error cleanup, and resource +limits. Used codebase-memory-mcp to locate acquisitions and their callers, +checked the source and contracts, and ran relevant existing tests and small +standalone diagnostics. Checked the selected PromptKit v0.25.0 handoff where +resource ownership crosses the application/library boundary; this was not an +exhaustive audit of upstream implementations. + +Two additional deployment-dependent resource-budget gaps warrant consideration: +HTTP connection/body lifetimes and aggregate input memory. Neither violates an +existing promise that these resources have a fixed bound. Two unresolved +cleanup findings from the concurrency audit also apply here. No additional +ordinary file-close leak, unowned recurring timer, or persistent application +result-history retention was substantiated. + +The proposed controls below are options for an explicit deployment/product +decision, not new mandatory limits or guarantees established by this audit. + +## Current Architecture + +ConfigKit owns acquisition through resolved configuration; PromptKit owns +execution, backend admission, retries, and provider clients. CommandKit owns +native CLI workflows and presentation. Scriptorium owns its inbound HTTP +transport, restricted artifact policy, CLI report-file effects, and process +lifecycle. The server retains one engine; requests have separate inputs, +results, and optional terminal collectors. ReleaseKit owns release mechanics. +See the [component overview](../../internal/overview.md) and +[adapter internals](../../internal/adapters.md). + +## 1. HTTP Connections Can Retain Resources Outside The Execution Budget + +**Classification:** Deployment-dependent weakness; additional lifetime controls +require a policy choice. + +**Relevant code:** `serveWithListener`, particularly lines 47–51 of +[server.go](../../../internal/adapter/cli/server.go), and `Handler.ServeHTTP`, +lines 53–78 and 128–185 of +[handler.go](../../../internal/adapter/http/handler.go). + +**Circumstances:** The server sets ReadHeaderTimeout but leaves ReadTimeout, +IdleTimeout, and WriteTimeout unset. A client can send complete headers and +then stall partway through a body below MaxRequestBytes. The JSON decoder +continues waiting before Engine.Run starts. Idle keep-alive connections and +response writes have no configured application-side lifetime bound either. +In Go's server, zero IdleTimeout falls back to ReadTimeout, also zero here. +The engine operation budget intentionally excludes decoding and delivery. + +**Consequences:** A stalled upload can hold a connection descriptor, handler +goroutine, and decoding state without consuming a backend admission slot. +Many such clients can exhaust resources independently of model concurrency +settings. Idle clients retain connection resources; a reader that stops +consuming a sufficiently large response can also retain a pending write and +its encoded buffer. Byte limits bound sizes, not these lifetimes. This matters +when clients can reach the listener without corresponding gateway controls, +including malfunctioning clients on an otherwise trusted network. + +**Evidence:** A temporary diagnostic launched the actual `serve` command on +loopback with normal defaults. It sent complete HTTP headers, a declared +1,024-byte body, and an incomplete JSON prefix containing a one-second run +timeout. The connection remained pending through an 11-second observation, +beyond the configured 10-second header timeout. Closing the connection and +canceling the command released the diagnostic server. This establishes the +body-read case; idle/write implications follow from the server fields and the +installed Go standard-library documentation, not a separate saturation test. + +**Potential remediation:** For gateway deployments, explicitly select and +document body-progress/read, idle, response-delivery, and connection/request +controls at that boundary as appropriate. For direct deployments, consider +application-owned configurable timeouts or phase-specific read/write deadlines +through standard net/http APIs. Values and defaults need an explicit decision; +a short global WriteTimeout can incorrectly cut off legitimate long inference +because it starts before response delivery. Merely adding a context deadline +around a blocking body decoder does not establish an underlying read deadline. +Keep the engine operation budget's existing meaning and the selected shutdown +contract; this finding does not request a new graceful-drain guarantee. + +## 2. Existing Byte Limits Are Not An Aggregate Memory Budget + +**Classification:** Capacity-planning weakness; additional budgeting is an +optional deployment/product decision, not a misimplemented per-file limit. + +**Relevant code:** `Handler.ServeHTTP` input mapping in +[handler.go](../../../internal/adapter/http/handler.go), `readArtifactFile` in +[artifact_reader.go](../../../internal/adapter/http/artifact_reader.go), and +the handoff through `newEngine` in +[engine.go](../../../internal/adapter/cli/engine.go). + +**Circumstances:** The request limit counts encoded references, whereas the +artifact limit applies independently to each referenced file. PromptKit +materializes the supplied artifacts for rendering. A small request can name +many individually permitted files, and the same file can appear under distinct +input names. Consequently, neither the encoded request cap nor the per-file +cap bounds the sum of acquired file bodies to that configured byte value. + +**Consequences:** For N files of up to B bytes, materialized input alone can +approach N × B, before rendering and other copies. Fifty permitted 16 MiB +files can therefore require 800 MiB of input bodies for one run. Simultaneous +admitted runs add their working sets. This can exhaust a modest host even +though each individual request and file meets its documented limits. + +**Evidence:** A temporary diagnostic used the real application ConfigKit load, +PromptKit engine, restricted reader, and a synthetic in-process model client. +With a six-byte per-file limit and backend concurrency one, one successful +run read two six-byte files: twelve acquired bytes. Only tiny synthetic files +were used; no large-memory workload or performance benchmark was run. +Selected-library source inspection also confirmed that ordinary Engine.Run +acquires backend admission before loading the input bodies. Backend limits +therefore do protect that phase for limited backends; this is not an +admission-ordering defect. They do not make one admitted run's footprint +equal to a single-file cap. + +**Potential remediation:** Document and size the complete resource envelope: +number/size of inputs, rendering expansion, admitted runs, and delivery buffers. +Choose appropriate existing file and backend limits for the deployment. If a +harder memory envelope is needed, consider an explicit aggregate artifact +budget and whole-HTTP-request admission, using a native PromptKit capability +or an upstream extension for library-owned acquisition where appropriate. +A gateway can bound requests/connections but cannot infer referenced-file +bytes from the encoded request size alone. Any additional rejection policy +needs agreement; preserve valid definition semantics and avoid recreating +PromptKit's orchestration or constructing separate per-request engines. + +## Previously Recorded Cleanup Findings Still Apply + +- **Canceled file reads (production, P2):** + [Concurrency finding 1](04-concurrency.md#1-file-acquisition-can-outlive-request-cancellation-p2-previously-known) + covers `Read`/`readArtifactFile` in + [artifact_reader.go](../../../internal/adapter/http/artifact_reader.go). + Cancellation after entry can leave a FIFO read pending, retaining its + goroutine and potentially an open descriptor until external input releases + it. The deferred Close cannot run until the read returns. Thread context + through acquisition, perform cooperative checks, and align unsupported-file + handling with the ordinary upstream reader. This remains the confirmed + cleanup defect, not merely a proposal for new resource caps. +- **Capacity-test failure cleanup (test only, P3):** + [Concurrency finding 2](04-concurrency.md#2-shared-capacity-test-does-not-own-workers-on-failure-paths-p3-test-only) + covers `TestHandlerSharesBackendCapacityAcrossConcurrentRequests` and its + blocking client in [handler_test.go](../../../internal/adapter/http/handler_test.go). + Early failures bypass the successful-path release/join, and unexpected + second-request admission can stall the test. Add test-controlled cancellation, + failure-path cleanup/join, and a bound on the second request. No production + limit change is needed. These are the existing findings, not new discoveries. + +## Other Lifecycle Checks And Selected Tradeoffs + +- Ordinary restricted file reads defer Close immediately after a successful + Open, including stat, size-limit, and read-error returns. The max-plus-one + read detects oversize data without integer overflow. The cancellation case + above is the outstanding exception to timely cleanup, not a missing defer. +- CLI `writeNativeReport` closes its file after native rendering and joins + rendering/close errors. Resultless failures do not open the report. Main + streams and output retention remain caller-owned; nontransactional writes + and partial files are documented choices, not handle leaks. +- The server closes listeners/connections on cancellation and unexpected exit, + and stops or joins its AfterFunc callback. Signal registration has a deferred + stop. There is no application-owned recurring ticker or background work queue. +- Collectors retain only one terminal metadata snapshot per opted-in request. + The application adds no cross-request result cache or execution history. + Configuration diagnostics/bootstrap writers are invocation-local; server + configuration/engine lifetime is process-scoped rather than per request. +- Complete artifact bodies and JSON response encoding before size enforcement + are selected designs. The response cap is a wire-size policy, not a bound on + provider output or peak encoding memory. This audit does not propose silently + replacing those designs with custom streaming/serialization. Their working + sets belong in the capacity envelope discussed above. +- Provider connection pooling, engine timers, and framework source handles are + upstream-owned. The application does not create a new engine/client per HTTP + request. The ReleaseKit launcher uses exec, and its adopted delivery workflow + registers cleanup for its temporary bootstrap directory. + +## Validation And Limits + +- Go 1.27.0 on Linux/amd64: uncached focused HTTP limit/artifact-reader, CLI + delivery/failure, and terminal-collector tests passed. +- Both temporary diagnostics completed under the race detector. They used + loopback or in-process collaborators, no paid provider, and no credentials; + their controlled connections/work were released. +- Confirmed no application/tool code changes since the preceding audit; its + successful full race suite and vet results remain applicable evidence for + unchanged paths, not new resource-leak coverage. +- Documentation links and whitespace were checked. Only this audit document + was added; no production code or repository tests were changed. +- No memory/descriptor saturation, production measurements, or performance + benchmarks were conducted. No diagnostic attempts to prove that all possible + resource leaks or exhaustion cases are absent.