From ee94d7902571117e9dea654b6c207544a19c979b Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Tue, 24 Nov 2026 16:01:14 +0000 Subject: [PATCH] Record test coverage and effectiveness audit findings --- docs/roadmap/audit/08-testing.md | 418 +++++++++++++++++++++++++++++++ 1 file changed, 418 insertions(+) create mode 100644 docs/roadmap/audit/08-testing.md diff --git a/docs/roadmap/audit/08-testing.md b/docs/roadmap/audit/08-testing.md new file mode 100644 index 00000000..196baa73 --- /dev/null +++ b/docs/roadmap/audit/08-testing.md @@ -0,0 +1,418 @@ +# Test Coverage And Effectiveness Audit + +## Baseline And Scope + +Reviewed revision `7569dd78e4efda2303c0d9f57c369ef597b64e14` on 2026-11-24 +against the [testing policy](../../policy/testing.md). Production code is +unchanged from `3887d89b763b7040efc866d4a57eb910d8778730`; intervening commits +record the preceding audits and a documentation correction. This pass changes +only this report. It adds no tests and changes no production code. + +The review combined a fresh repository-wide coverage run with code-graph +discovery and risk-directed inspection of tests, production branches, fixtures, +and their callers. It considered both missing protection and tests whose +maintenance cost exceeds their behavioral value. Earlier audit counterexamples +were checked against the current tests rather than treating a passing suite as +proof that those defects are covered. + +Inspected areas include source parsing and ownership, configuration/resolution, +chunk planning, producer assessment and continuation, workers/cancellation, +generated references, semantic reconciliation, D&D extraction/normalization, +schemas and prompt assets, accepted-result reuse, diagnostics, publication, +capture, and assembled CLI/subprocess workflows. This is not a claim that every +test assertion or possible pipeline composition was exhaustively reviewed. + +## Current Architecture And Test Shape + +The application retains its fixed typed pipeline: + +```text +input -> chunk -> ordered steps [per-chunk extract -> merge -> normalize] -> output +``` + +The CLI assembles configuration, registries, native kit integration, state, and +reporting. The framework owns preparation, candidate assessment, one bounded +ready-job pool, generated-reference handoffs, and accepted-result reuse. Artifact +families own domain transformations, identity, validators, codecs, and reference +projections. PromptKit owns model transport and native repair/continuation +mechanics. Embedded assets remain content-only. + +The suite generally follows the requested classical style: real internal +collaborators, temporary filesystems, native engines with controlled provider +clients, and local HTTP servers or subprocesses at external boundaries. Useful +assembled tests exercise actual configuration, registrars, codecs, publication, +qualified fallback, cache eligibility, and native reporting rather than merely +checking a mocked orchestration sequence. + +Examples worth preserving include +[assembled recovery](../../../internal/cli/recovery_contract_test.go), +[executable workflows](../../../internal/cli/native_process_test.go), +[mixed extraction/continuation admission](../../../internal/framework/pipeline/ready_jobs_test.go), +[producer transitions](../../../internal/framework/pipeline/producer_test.go), +[native capture](../../../internal/framework/pipeline/native_capture_test.go), and +[concrete metadata isolation](../../../internal/core/source/chunk_plan_test.go#L226). +The weaknesses below call for focused additions and subtraction, not a new test +framework or a blanket increase in test volume. + +## Measured Coverage + +The fresh default suite passed in 124 packages: 1,352 top-level tests and 1,518 +subtest pass events, with no failed events or skipped individual tests. The D&D +declarations package reported no test files; that is not a skipped behavioral +test. + +Combined statement coverage was **89.2%: 13,961 of 15,652 instrumented +statements**. Cross-package instrumentation was enabled so coverage from +integration callers contributes to the packages they exercise. Selected totals: + +| Package | Combined statement coverage | +| --- | ---: | +| `internal/framework/semanticreconcile` | 95.6% | +| `internal/preflight` | 94.2% | +| `internal/modules/seriatim/input/transcript` | 90.5% | +| `internal/core/source` | 89.7% | +| `internal/cli` | 88.8% | +| `internal/modules/generic/chunk/units` | 88.6% | +| `internal/core/config` | 88.5% | +| `internal/framework/artifactcache` | 87.5% | +| `internal/framework/pipeline` | 86.7% | +| `internal/framework/diagnostics` | 83.0% | +| `internal/framework/evidencecontext` | 81.3% | + +Coverage guided inspection, not a pass/fail threshold. These are statement +measurements, not branch, assertion, mutation, or semantic-quality measurements. +Several concrete defects below execute already-covered statements with values +the suite never supplies. + +The profile reports `cmd/notarius/main.go` at 0%, but +[executable tests](../../../internal/cli/native_process_test.go#L21) build their +child with ordinary `go build`, without child coverage instrumentation. The +executable is exercised; its missing coverage contribution is a measurement +boundary, not sufficient evidence for adding tests. Similarly, `assets` reaches +100% by executing its one production statement; this says nothing about the +quality of its prompt instructions. Low coverage in small generic validators, +trivial accessors, or unused adapters was not promoted into a finding solely +because of the percentage. + +## Findings Summary + +Priorities indicate relative remediation value, not that ordinary runs or the +whole suite are unusable. Existing production defects are cross-referenced; +their test gaps are not additional independent runtime defects. + +| ID | Priority | Deficiency | Proposed test work | +| --- | --- | --- | --- | +| TEST-001 | P2 | Accepted numeric boundaries lack regression cases | Add small package-level boundary cases with the associated fixes. | +| TEST-002 | P3 | Identity/alias fixtures omit valid representational edge cases | Extend resolver and metadata tests without restricting accepted inputs. | +| TEST-003 | P2 | Native-failure assertions accept unrelated errors or encode the wrong category | Tighten the outcome oracle and correct the category assertion with ERR-001. | +| TEST-004 | P3 | Diagnostics tests cover constituent behaviors but not combined failure paths | Add focused runner-level partial-success and finalization regressions. | +| TEST-005 | P3 | Prompt tests pin English wording and repeat asset checks | Remove prose change detectors; retain distinct composition/schema behavior. | +| TEST-006 | P3 | Run-ID test freezes an incidental private representation | Remove the format regex, retaining uniqueness and path-safety checks. | +| TEST-007 | P3 | A worker test relies on wall-clock overlap; related waits diagnose poorly | Use controlled overlap and bounded, cleanup-safe handshakes. | + +## Findings + +### TEST-001 — Accepted Numeric Boundaries Lack Regression Cases + +**Functionality and existing coverage:** +[generic chunk planning](../../../internal/modules/generic/chunk/units/chunker_test.go#L59) +covers ordinary sizes, exact partitions, overlap, invalid options, and the +ConfigKit integer representation. +[Transcript parser tests](../../../internal/modules/seriatim/input/transcript/adapter_test.go#L164) +cover malformed input, ordinary negative/non-finite timestamps, and ordering +beyond floating-point integer precision. +[Reconciliation preparation tests](../../../internal/framework/semanticreconcile/preparation_test.go) +cover small context radii, candidate bounds, invalid limits, and exact material +byte boundaries. These are valuable tests, but their representative numbers do +not protect all accepted arithmetic. + +**Unverified behavior:** The three reproducible defects in the +[correctness audit](01-correctness.md) remain outside those fixtures: + +- A small source with accepted `max_units = math.MaxInt` should produce one + complete chunk, but ceiling-division preallocation overflows and panics. +- A timestamp such as `-1e-1000` should be rejected as negative, but its float + conversion underflows to negative zero before the exact rational is checked. +- A small cited source with `ContextRadius = math.MaxInt` should clamp to the + source bounds, but interval expansion overflows and returns empty evidence + windows as ready material. This last case is an internal API boundary, not the + current production default. + +**Improvement:** With the respective fixes, add narrow tests at `Chunker.Plan` +through supported option decoding, `Adapter.Parse`, and `semanticreconcile.Prepare`. +Use tiny inputs, assert exact coverage/evidence and ordinary return outcomes, +and include zero/tiny-positive/negative-zero timestamp controls. Test accepted +large values against source size rather than copying production defaults. +These cases need no huge allocation, live model, or broad fuzz harness. + +The tests should fail on the current defective results and pass after correction. +Do not make them pass by introducing arbitrary maximum sizes or new timestamp +magnitude restrictions. Additional fuzz/property coverage is optional if it +provides distinct protection; its absence alone is not a finding. + +### TEST-002 — Identity And Metadata Fixtures Omit Valid Representational Edge Cases + +**Functionality and existing coverage:** +[generated-binding resolution tests](../../../internal/framework/pipeline/profile_test.go) +check ordering, kinds, and references using ordinary identifiers. +[Metadata tests](../../../internal/core/source/chunk_plan_test.go#L210) check +deep detachment, concrete container preservation, genuine cycles, unsupported +types, and non-finite numbers. They do not distinguish all valid representations +from the invalid cases that superficially resemble them. + +**Unverified behavior:** The +[complexity audit's BUG-001 and BUG-002](03-complexity.md#additional-correctness-findings) +identify two separate gaps: + +1. `(step="a\x00b", lane="c")` and `(step="a", lane="b\x00c")` are distinct + accepted identity pairs. Concatenating them with a NUL separator aliases the + resolver's producer records. Existing tests never supply the separator inside + an identifier or distinguish the producers using different artifact kinds. +2. A finite metadata value can contain a slice and its shorter prefix view: + `values := []any{"one", nil}; values[1] = values[:1]`. Existing fixtures test + actual cycles, but not this acyclic shared-backing representation. The current + tracker rejects it as a cycle. + +These are programmatic boundary cases; ordinary transcript JSON decoding does +not construct the aliased Go slice. Neither counterexample was newly executed +in this testing pass; the production constructions and current test omissions +were inspected directly. + +**Improvement:** Add a resolver case with the two accepted pairs and different +producer kinds, asserting correct reference compatibility. Add a narrow +`source.CloneMetadata` case that accepts/clones the prefix view, preserves its +finite value, and detaches the result. Retain controls for actual map/slice +cycles and shared non-cyclic values. Keep the metadata rule in the source package +rather than repeating its representation matrix in every validator. + +Do not add an identifier-character ban or reject shared backing arrays to +satisfy the tests. These cases should accompany BUG-001/002, not become a second +implementation of their fixes in test helpers. + +### TEST-003 — Native-Failure Assertions Have An Incomplete Or Incorrect Oracle + +**Functionality and deficiency:** +[TestNativeStructuralFailureIsNotAReconciliationRetry](../../../internal/framework/semanticreconcile/engine_test.go#L109) +controls a provider response of `{"duplicate_groups":null}` and selects zero +native repairs. It checks the failed native result only when `err == nil`: + +```go +if err == nil && (result == nil || result.Validation.Status != promptkit.ValidationFailed || result.Validation.IsValid) { + // fail +} +``` + +Consequently, any unexpected error after the one generation call also satisfies +the test. The fixture can pass without demonstrating the completed failed-check +outcome it is intended to protect. Counting provider calls is appropriate here +because the budget is contractual; it does not replace an outcome assertion. + +At the application boundary, +[TestNativeProducerDoesNotInterpretFailedNativeValidation](../../../internal/framework/pipeline/producer_test.go#L162) +correctly checks safe fallback and absence of interpretation/reassessment, but +does not assert retained native validation details. More significantly, +[TestNilErrorFailedNativeValidationCannotBecomeApproval](../../../internal/modules/dnd/validate/scenedescriptions/combat_semantics/native_execution_test.go#L60) +explicitly requires `errors.Is(err, promptkit.ErrValidation)` for a completed +failed content check. That assertion entrenches the category conflation recorded +in [ERR-001](06-error-handling.md#err-001--completed-native-validation-failures-lose-detail-and-acquire-an-operational-error-category). + +**Unverified behavior:** A completed structural check that rejects content must +remain non-usable, retain meaningful diagnostics, and stay distinguishable from +an operational inability to validate. Current assertions can miss the distinction +or actively reject its correction. + +**Improvement:** For the pinned native fixture, require the expected nil Go error, +present result, failed validation status, invalid flag, useful validation details, +and the test-selected call bound. At Notarius's producer/validator boundary, use +controlled native failures to verify content diagnostics and genuine operational +cause preservation separately. Remove the incorrect sentinel expectation when +addressing ERR-001; retain unavailable-validator classification, no approval, +no fabricated semantic guidance, and existing retry/fallback protections. + +Assert structured categories, cause identities, and only the smallest useful +diagnostic fragments. Do not pin the upstream validator's complete English error, +duplicate PromptKit's whole test suite, or add another retry layer. + +### TEST-004 — Diagnostics Tests Miss Failure-Path Composition + +**Functionality and existing coverage:** +[reverse-completion coverage](../../../internal/framework/pipeline/runner_concurrency_test.go#L317) +proves canonical diagnostic ordering when all chunks succeed. +[Ordered-step failure coverage](../../../internal/framework/pipeline/runner_concurrency_test.go#L266) +protects completed predecessor output and suppression of later steps. +[Aggregator tests](../../../internal/framework/diagnostics/aggregator_test.go#L43) +exercise warning bounds and occurrence overflow, while +[pipeline diagnostic tests](../../../internal/framework/pipeline/diagnostics_test.go#L20) +exercise successful finalization. These constituent tests do not cover their +important combinations. + +**Unverified behavior:** + +- A warning-bearing chunk completes, then another chunk fails before its lane + can continue. Diagnostics from completed work should survive without accepting + an incomplete lane's artifacts. ERR-002 shows that they currently disappear. +- A primary execution failure coincides with aggregate diagnostic failure. The + caller should retain the primary cause and discover the aggregation failure; + ERR-003 shows that finalization suppresses that second error and loses the + collected prefix. + +See [ERR-002/003](06-error-handling.md#err-002--successful-extraction-diagnostics-disappear-when-the-lane-never-continues) +for the production branches. The green full suite does not contradict those +findings; it never supplies the necessary combined state. + +**Improvement:** Add a deterministic runner regression with one worker, one +completed diagnostic-bearing chunk, and a later failing chunk in the same lane. +Assert the returned diagnostics, terminal cause, and absence of incomplete-lane +publication. If the correction introduces sparse-result collection, add a +controlled out-of-order case with a higher completed chunk index, checking +canonical ordering and no duplication from completed lanes. + +Separately combine a primary failure with otherwise valid groups that trigger an +existing aggregate bound, or exercise the narrow shared finalization boundary +if the fix introduces one. Assert both inspectable causes and the selected +bounded/incomplete diagnostic outcome. These tests belong to orchestration; +repeating the aggregator's full matrix in the CLI is unnecessary. Do not raise +limits, demand warnings for unfinished work, or convert best-effort cache I/O +into mandatory failure as a side effect. + +### TEST-005 — Prompt Tests Contain Prose Change Detectors + +**Relevant tests:** +[registry prompt pairs](../../../assets/registry_extraction_test.go#L15), +[scene prompt pairs](../../../assets/scene_descriptions_test.go#L75), +[combat prompt pairs](../../../assets/combat_turns_test.go#L15), +[registry normalization prompts](../../../assets/package_test.go#L149), +[generic reconciliation prompts](../../../internal/framework/semanticreconcile/assets_test.go#L12), +and [spell prompt pairs](../../../internal/modules/dnd/extract/spells/prompt_assets_test.go#L12). + +**Deficiency:** These tests mix useful native-contract/input assertions with +literal fragments of authored English, such as `proper name or a stable, +individually distinguishing`, `must not invent a proper noun`, `same physical +place`, and `canonical spelling exactly`. Equivalent instruction wording can +fail the test; contradictory instructions can pass as long as those fragments +remain. String containment does not prove the semantic behavior of the model. + +[TestExtractionPromptComposition](../../../assets/prompt_composition_test.go#L11) +also uses production prose as message-location sentinels. Its test-generated +transcript/reference sentinels provide a stable way to observe input placement, +but its evidence/endpoint/combat-policy phrases couple ordering checks to text +editing. The issue is the oracle, not the importance of those domain policies. + +**Improvement/removal candidates:** Remove assertions that freeze non-contractual +English, including their now-unused rule tables. Narrow mixed tests to the distinct +behavior they protect: actual native preparation, declared schemas/default +selection, fixed input binding/cache hints, and correction guidance without +regenerating source material. Use test-controlled sentinels for supplied content. +Where two tests then protect exactly the same composition behavior, consolidate +at the assets owner; preserve module tests that exercise different routing or +execution behavior. Shared assets and focused prompt review keep authored +instructions coherent without pretending that word matches measure extraction +quality. Do not replace these checks with prompt hashes or whole-prompt snapshots. + +Retain [automatic embedded-prompt preparation](../../../assets/package_test.go#L61), +which discovers actual declarations and verifies loaded schemas, and +[required-property compatibility checks](../../../assets/schema_compatibility_test.go#L14). +Field names, enums, opaque-ID exclusions, selected public defaults, and the +established follow-up-message contract are genuine contracts even when exact +values/counts are involved. This finding is not a blanket ban on string assertions +or a recommendation to remove all prompt tests. Optional live semantic evaluation +may complement review, but belongs outside the deterministic default suite. + +### TEST-006 — Run-ID Test Freezes An Incidental Private Format + +**Functionality and deficiency:** +[TestDefaultRunIDGeneratorProducesUniqueSafeIDs](../../../internal/cli/run_id_test.go#L14) +generates 256 IDs for the same timestamp and checks uniqueness and path safety. +It additionally requires the exact regex `^run-123456789-[0-9a-f]{32}$`. + +The current [operations guide](../../operations.md) describes isolated run state, +not a consumer contract for timestamp formatting or random hexadecimal width. +A correct change to the private representation could therefore fail this test +despite preserving its meaningful guarantees. Conversely, the regex itself does +not prove independent run allocation or collision handling. + +**Improvement/removal candidate:** Remove the exact private-format assertion, +retaining controlled-timestamp uniqueness and the existing path-safety validation. +Retain separate output allocation/collision and partial-write tests in the same +file. This is a small narrowing, not a reason to delete the whole test. + +Distinguish this from the +[versioned session-ID vector](../../../internal/cli/session_test.go#L5): stable +cross-run routing is an explicitly selected behavior, so its versioned identity +test has contractual value. Do not remove exact expectations indiscriminately. + +### TEST-007 — Concurrency Tests Need Controlled Overlap And Better Failure Bounds + +**Functionality and deficiency:** +[TestRunnerBoundsConcurrentLaneContinuations](../../../internal/framework/pipeline/runner_concurrency_test.go#L394) +sleeps for five milliseconds inside each merge, then requires observed peak +concurrency to equal two. The sleep encourages overlap but does not establish it: +a delayed runnable worker can miss the window even when the runner is correct. +The test can therefore fail because of scheduling rather than a worker-limit +defect. This is a static reliability risk; the focused repeated run did not +exhibit a failure. + +The related +[reverse-completion test](../../../internal/framework/pipeline/runner_concurrency_test.go#L317) +uses unconditional receives from `started` and `done`. A scheduling regression +or early runner error can leave the test waiting until the global Go test timeout, +instead of reporting the missing event locally. Its existing handshakes are more +useful than sleeps, but their failure/cleanup path is incomplete. + +**Unverified behavior and improvement:** Explicitly hold started continuation +jobs at release gates and observe the test-selected limit before releasing them. +Then verify completion and zero retained activity, without relying on elapsed +wall time to make overlap happen. Use test-scoped cancellation/deadlines or +`testing/synctest` as appropriate, release gates on failure, and join started work. +The existing +[mixed-ready-jobs test](../../../internal/framework/pipeline/ready_jobs_test.go#L34) +provides a local example of controlled scheduling. + +Keep the runtime worker-limit protection; rewriting these tests is preferable to +deleting them. A local test watchdog diagnoses a regression and does not establish +a new production timeout or performance guarantee. No general deadline helper +framework is necessary. + +## Validation And Limits + +The complete suite was run with fresh, cross-package atomic coverage using the +available Go 1.27.0 toolchain and cached declared dependencies. Equivalent +reproduction commands are: + +```sh +testing_audit_dir=$(mktemp -d) +GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go test -mod=readonly -count=1 \ + -coverpkg=./... -covermode=atomic \ + -coverprofile="$testing_audit_dir/coverage.out" -json ./... \ + > "$testing_audit_dir/tests.jsonl" +GOTOOLCHAIN=go1.27.0 go tool cover -func="$testing_audit_dir/coverage.out" +``` + +The coverage profile's repeated block locations were unioned for package totals; +per-test-package percentages under `-coverpkg=./...` were not mistaken for each +package's local coverage. JSON test events supplied the test/package counts. +Generated profiles and logs remained outside the repository. + +Three relevant scheduling tests also passed 20 shuffled repetitions: + +```sh +GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go test -mod=readonly \ + -shuffle=on -count=20 ./internal/framework/pipeline \ + -run '^(TestRunnerBoundsConcurrentLaneContinuations|TestRunnerBoundsExtractJobsAndStabilizesReverseCompletion|TestRunnerSharesWorkerLimitBetweenExtractionAndReadyContinuation)$' +``` + +No mutation-testing tool was run and no deliberate production/test mutations +were made. The counterexamples from earlier audits provide concrete evidence +of inadequate input/assertion protection, not a measured mutation score. The +[earlier concurrency audit](04-concurrency.md#validation) already records a fresh +full race run at unchanged production code; this pass did not repeat that run. +No credentials, production transcripts, live providers, or paid inference calls +were used. Passing fake-provider tests establishes application behavior for the +supplied responses, not real-model extraction quality. + +The review does not recommend 100% coverage, a mandatory fuzz inventory, new +live-provider release gates, or tests for every trivial helper. Test additions +should accompany concrete behavior fixes; removal/narrowing should target the +incidental assertions identified above. Earlier audit findings remain open and +are not resolved by this report. Report links and the final documentation diff +are checked before committing.