diff --git a/docs/roadmap/audit/08-testing.md b/docs/roadmap/audit/08-testing.md new file mode 100644 index 0000000..1490e02 --- /dev/null +++ b/docs/roadmap/audit/08-testing.md @@ -0,0 +1,279 @@ +# Test Coverage And Effectiveness Audit + +Reviewed on 2026-11-24 at source revision +`cb04d324c1aafc348ca368c23a3d7a953af33a1f`. + +## Scope And Assessment + +Evaluated both missing behavioral protection and unnecessary test coupling +against the [testing policy](../../policy/testing.md), especially test ownership, +independent assertions, regression protection, proportional integration tests, +and removal of incidental change detectors. Reviewed the graph inventory of +118 top-level test functions across 18 test files, relevant source/contracts, +and representative assertions and fixtures. Coverage and targeted compiler +overlays supplied additional evidence; they did not replace source review. + +The suite predominantly follows the policy: real ConfigKit/PromptKit/CommandKit +collaborators, temporary files, controlled loopback providers, useful presence +and error/privacy checks, and representative CLI/HTTP/process integration. +However, high statement coverage coexists with demonstrated behavioral blind +spots and assertions that reject harmless implementation changes. + +The architecture remains a thin executable: ConfigKit resolves configuration, +PromptKit owns execution/admission, CommandKit owns native CLI presentation, +and Scriptorium owns HTTP adaptation, report-file effects, and process lifecycle. +One server engine is shared; request inputs and terminal collectors are local +to each request. ReleaseKit owns release mechanics. See the +[component overview](../../internal/overview.md). + +## Coverage And Effectiveness Evidence + +The unchanged baseline passed: + +```bash +go test -count=1 -coverpkg=./... -coverprofile=/tmp/scriptorium-testing-audit.BmISwp/coverage.out ./... +go tool cover -func=/tmp/scriptorium-testing-audit.BmISwp/coverage.out +``` + +The merged cross-package profile covers 484 of 521 statements: **92.9%**. +Repeated profile blocks were merged by source location; these are not the +cross-instrumented percentages printed separately by each test binary. + +| Production package | Covered / total statements | Coverage | +| --- | ---: | ---: | +| `cmd/scriptorium` | 4 / 5 | 80.0% | +| `internal/adapter/cli` | 241 / 262 | 92.0% | +| `internal/adapter/http` | 173 / 188 | 92.0% | +| `internal/config` | 49 / 49 | 100.0% | +| `internal/report` | 17 / 17 | 100.0% | + +The root and adapter-guard packages contain tests without production statements; +defaults introduce no executable statements. No coverage threshold is proposed. +For example, the thin `main` wrapper's missing coverage does not justify another +test when process identity/status and signal behavior already have protection. + +Six temporary Go compiler overlays changed only files outside the worktree: + +| Control | Result | What it demonstrates | +| --- | --- | --- | +| Hash every artifact as the empty input | Full suite passed | Expected hashes reuse the production helper. | +| Swap collector cached-token/cache-write-token mappings | Full suite passed | Distinct usage fields lack distinct test data/assertions. | +| Rebuild the HTTP engine per request, retaining startup validation | Full suite passed | Tests do not establish engine lifetime at server composition. | +| Reintroduce a no-op `--schema-dir` flag on `run` | Full suite passed | A missing operand masks acceptance of the removed flag. | +| Decode untyped numbers with `UseNumber` | Selected HTTP tests failed | An assertion pins `float64`, not JSON numeric behavior. | +| Reword the generic model-generation failure message | Error-mapping tests failed | Full error prose is pinned despite unchanged status/code/privacy. | + +The first four are deliberately defective controls, not current production +defects. The last two preserve the relevant external semantics; their failures +are evidence of incidental coupling. These probes are not an exhaustive +mutation score. Overlays apply to packages compiled by the test invocation; +separate subprocess builds can use the original tree. + +## Important Behavioral Gaps + +### 1. Known Correctness Defects Lack Their Decisive Boundary Cases + +**Priority:** P2 for precision/cancellation; P3 for filename identity. +**Policy:** Previously observed regressions, boundary conditions, data integrity, +and cancellation deserve focused protection. + +The following existing tests pass despite the defects already reproduced in +the [correctness audit](01-correctness.md): + +- `TestHandlerModelOverrideAcceptsJSONCompatibleExtraParams` in + [handler_test.go](../../../internal/adapter/http/handler_test.go), lines + 1375–1417, uses only small exactly representable numbers and a recording + Runner. It never checks that a large integer reaches the provider unchanged. + Add a representative HTTP-to-real-engine-to-loopback-provider case with + `9007199254740993`, including nested values. Compare losslessly rather than + decoding the observed request back through float64. +- `TestRestrictedArtifactReaderReadsContainedFiles` in + [artifact_reader_test.go](../../../internal/adapter/http/artifact_reader_test.go) + covers cleaning, absolute paths, and traversal, but no whitespace-significant + filename. Add distinct padded/unpadded files with different contents and + verify that the requested file's identity and bytes survive resolution. +- `TestRestrictedArtifactReaderRejectsCanceledAndMalformedReferences` checks + contexts canceled before acquisition. Generation/retry/capacity deadline + tests exercise other collaborators, not the injected reader. Add bounded, + platform-appropriate coverage for cancellation after acquisition begins and + for unsupported non-regular inputs, with cleanup that always releases owned + work. Retain a representative real-engine or HTTP cancellation check. Follow + the selected remediation rather than requiring streaming FIFO support or + immediate interruption of every filesystem operation. + +Extend the existing owners rather than creating a general input-format matrix. +These cases protect established contracts; they do not introduce new resource +caps or a symlink sandbox. + +### 2. The Artifact-Hash Assertion Uses Its Own Implementation As The Oracle + +**Priority:** P3. **Relevant test:** +`TestRestrictedArtifactReaderReadsContainedFiles`, line 85 of +[artifact_reader_test.go](../../../internal/adapter/http/artifact_reader_test.go). + +The expected hash is computed with the same private `artifactHash` helper that +the reader uses. A helper returning one fixed hash for all content therefore +satisfies the assertion. The constant-hash overlay passed the entire suite, +including the real HTTP/server paths. Input identity can regress without a +failure even though the hash helper has 100% statement coverage. + +Replace the self-referential assertion with an independent expected digest for +fixed test data, or compare the selected upstream ordinary reader's metadata +through its public API. Exercise different content with independently meaningful +expectations. Keep the reader's body/URI/containment checks. There is no need +to test the cryptographic library exhaustively or establish a new global +uniqueness guarantee for arbitrary hashes. + +### 3. Collector Fixtures Do Not Distinguish All Usage Fields + +**Priority:** P3. **Relevant test:** `TestCollectorProjectsOnlyTerminalAggregates`, +lines 25–66 of [report_test.go](../../../internal/report/report_test.go), and +`Collector.Observe` in [report.go](../../../internal/report/report.go). + +The fixture distinguishes prompt, completion, and total counts but leaves both +cached-token counts at their identical zero defaults. JSON assertions check +only that each count object has three members, not the names/values of all +required members. Swapping cached-token and cache-write-token projections passed +the full suite despite this package's 100% coverage. Report consumers could +receive incorrect accounting while all existing assertions remain satisfied. + +Use distinct nonzero cached/cache-write values and meaningful Known/Complete +combinations. Assert each required JSON `value`, `known`, and `complete` member +and its semantics. Replace the member-count-only assertion; preserve zero versus +unknown and incomplete-count protection. This is local projection testing, not +duplication of PromptKit's billing or provider-parser test matrix. + +### 4. Server Tests Miss The Lifetime-Owning Composition Boundary + +**Priority:** P2 for shared admission; P3 for constructor failure. +**Relevant tests:** `TestHandlerSharesBackendCapacityAcrossConcurrentRequests` +in [handler_test.go](../../../internal/adapter/http/handler_test.go), and +`TestServeStartupHTTPAndCancellation` / `TestServeListenAndConfigurationFailures` +in [lifecycle_test.go](../../../internal/adapter/cli/lifecycle_test.go). + +The handler capacity test constructs one engine itself and injects it. It proves +that this supplied engine shares admission, but cannot establish that `serve` +owns and retains one engine. The real-server test verifies generation and +cancellation without overlapping capacity-limited runs. An overlay rebuilding +the engine per HTTP request passed the full suite, despite violating the +explicit [shared-engine constraint](../../policy/architecture.md#definition-support-and-request-state). + +Move or consolidate the representative shared-capacity scenario into the +existing server harness: configure one backend with capacity one and no queue, +hold the first provider request, and verify the second HTTP request is rejected +without a second provider dispatch. Check completion/release after unblocking. +Once the stronger scenario subsumes the lower-level case, remove that duplicate +case while retaining distinct HTTP error/privacy and retry-override protection. + +Also cover a resolved configuration whose engine construction fails because of +a missing message file or malformed template. Current server failure cases +cover loading/domain/YAML errors and listener errors, but not this intermediate +stage; `frameworkFailure` has 0% coverage. Verify the typed failure, nonzero +status, and that listening is not attempted. Do not manufacture an unreachable +LoadError merely to cover that helper's branches, move capture into ordinary +configuration inspection, or freeze new diagnostic prose from the unapproved +[diagnostic recommendation](06-error-handling.md). + +### 5. A Removed-Flag Test Can Pass For The Wrong Usage Error + +**Priority:** P3. **Relevant test:** `TestRemovedSourceAndSchemaFlagsAreRejected`, +lines 33–44 of [app_test.go](../../../internal/adapter/cli/app_test.go). + +The `run` cases omit the required prompt operand and check only Usage/status 2. +After a temporary overlay reintroduced `--schema-dir` on `run`, the test still +passed because the invocation remained invalid for another reason. The full +suite also passed that control. Its other command rows do not cover a flag +accidentally added only to `run`. + +Use otherwise-valid base invocations, explicit controlled configuration where +needed, and an assertion that distinguishes rejection of the removed flag +from unrelated usage/configuration errors. Prefer supported typed categories +or a minimal flag-specific diagnostic fragment, not a whole-message snapshot. +Retain the deliberately selected hard-cutover protection; this is not a reason +to delete all removed-interface tests. + +### 6. Failure Cleanup In The Capacity Test Is Incomplete + +**Priority:** P3; previously recorded test defect. **Relevant test:** +`TestHandlerSharesBackendCapacityAcrossConcurrentRequests`, lines 1087–1118 of +[handler_test.go](../../../internal/adapter/http/handler_test.go). + +The first worker uses an uncancelable request context; release/join occurs only +after several assertions. An early fatal failure bypasses cleanup. An incorrectly +admitted second synchronous request can wait for a release the test performs +only after that request returns. Happy-path timeouts do not bound this middle +call. This can obscure the very regression being tested with a hang or leaked +worker. See [concurrency finding 2](04-concurrency.md#2-shared-capacity-test-does-not-own-workers-on-failure-paths-p3-test-only). + +Register cancellation/release/join cleanup before launching work, bound the +second request, and keep one owner of channel closure. If consolidating the +scenario into the server test above, carry these protections into its replacement +instead of maintaining two versions or building a generic concurrency fixture. + +## Removal And Consolidation Candidates + +### 7. Remove Incidental Representation And Prose Assertions + +**Priority:** P3. **Policy:** Correct internal refactors should remain inexpensive; +exact error wording is appropriate only when contractual. + +- In `TestHandlerModelOverrideAcceptsJSONCompatibleExtraParams`, lines 1407–1415 + of [handler_test.go](../../../internal/adapter/http/handler_test.go), the deep + equality expectation fixes untyped JSON numbers to Go float64. A UseNumber + overlay failed this assertion even though `json.Number` preserves JSON numeric + semantics and is accepted by the selected PromptKit API. Remove this concrete- + type requirement, not the scalar/object/array mapping protection. Replace it + with lossless semantic/wire assertions and consolidate it with the precision + regression above. Do not normalize both sides through float64 again. +- In `TestHandlerPublicErrorMapping`, lines 1690–1748 of the same file, every + case repeats a complete message and requires exact equality. Rewording + "model generation request failed" to "model generation failed" caused five + failures while status, code, JSON shape, and cause privacy remained unchanged. + The [HTTP contract](../../api.md#error-responses) does not promise those exact + sentences. Remove the repeated prose expectations and equality assertion; + retain status/code/precedence, a usable nonempty message, and private-cause + exclusion checks. Preserve any wording that is actually contractual. + +No whole test function needs deletion solely because it calls a private helper +or overlaps an integration path. The concrete removal opportunities are the +assertions above, the self-referential hash expectation, and lower-level cases +that become redundant after a stronger owner-boundary test replaces them. +In particular, the standalone recording-Runner extra-parameters test can be +consolidated into the lossless provider-wire case once it covers the same JSON +shapes; the standalone shared-capacity test can be removed after the server-level +replacement preserves its meaningful protection. Do not remove either first +and leave its behavior unprotected. + +## Useful Protection To Retain And Work Not Justified By This Audit + +- Keep architecture import/removal guards: they protect expressly adopted + ownership constraints, rather than arbitrary directory preferences. +- Keep actual stdout bytes, numeric presence/zero overrides, status/domain + outcomes, report delivery failures, classified-field redaction, terminal + collector isolation, source-context selection, and no-provider preparation + checks. These protect application contracts even when native libraries do + most of the work. +- Using the upstream native renderer as the expected report formatter is a + valid integration oracle; it is not the same as reusing the local hash helper. +- Do not add exhaustive upstream grammar/format matrices, mock internal call + choreography, or tests for every uncovered return. Standard library failures + and impossible constructor states need no artificial fault-injection layer + solely to increase coverage. +- Resource-budget proposals and richer diagnostics in earlier audits require + decisions first. Their absence is not a reason to create tests that silently + establish new timeouts, memory limits, rollback, or disclosure guarantees. + +## Validation And Limits + +The normal coverage run and four full-suite defective-overlay runs passed. +The two targeted representation/prose controls failed as described; those are +intentional audit observations, not baseline failures. No new production bug +was introduced or retained. Only this audit document was added to the repository; +all overlay sources and coverage artifacts remained outside the worktree, and +no repository production code or tests were edited. + +This was a focused policy/effectiveness review, not exhaustive mutation testing +or proof that all important behaviors are covered. Prior race-audit results +remain evidence for unchanged source; this pass did not rerun the full race +suite or propose a coverage/mutation-score gate. Documentation links and +whitespace were checked.