Files
notarius/docs/roadmap/audit/06-error-handling.md

260 lines
18 KiB
Markdown

# Error-Handling Audit
## Baseline And Scope
Reviewed revision `67116c42e20b83f584c67f221420960ecfd2bee9` on 2026-11-24.
Production code is unchanged from the preceding audits. This pass adds only this
report, without production changes or new tests.
The review followed errors through configuration/preflight, source/reference
loading, typed codecs, producers, assessment, native continuation, worker
cancellation, cache reuse, capture, output publication, and native presentation.
Code-graph searches and caller tracing were used to inspect error construction,
wrapping, ignored results, fallback branches, and failure-return paths. Relevant
pinned PromptKit v0.25.0, CommandKit v0.8.0, and ckconfig v0.11.0 APIs were inspected
where their contracts determine the meaning of local error handling.
Three diagnostic/classification weaknesses warrant consideration. No new path
was confirmed that turns a terminal pipeline failure into unqualified successful
publication. Existing correctness/concurrency findings remain independent.
| Finding | Priority | Main effect |
| --- | --- | --- |
| ERR-001: Completed native validation failures lose detail and acquire an operational error category | P3 | Misleading classification and less actionable failure/fallback explanations |
| ERR-002: Successful extraction diagnostics disappear when the lane never continues | P3 | Failure-path visibility depends on whether unrelated work completed |
| ERR-003: Failure-output finalization suppresses aggregation errors | P3 | Aggregation failure and previously collected diagnostics can both disappear |
## Current Error-Handling Architecture
The CLI is the composition/publication boundary. It maps identifiable invalid
configuration to native usage outcomes, retains operational causes, and keeps
operation failures distinct from report/diagnostic delivery failures. The pipeline
returns logical files only after successful stage execution; the CLI publishes
them before finalizing requested capture and submitting the completion report.
Modules own interpretation, correction guidance, and supported fallbacks. The
framework assesses complete candidates through the configured validator chain,
distinguishing approval, rejection, failure, and unavailable judgment. PromptKit
owns transport, structural repair, deadlines, and conversation iteration. Native
execution success is not domain acceptance. Strict nonacceptance fails; explicitly
selected permissive mode can construct a checked, disclosed, reuse-ineligible
fallback. Caller cancellation and undelivered responses do not initiate fallback.
The coordinator cancels siblings, drains started work, and chooses a scoped error
by stable ordering rather than arrival time. Parent cancellation takes precedence.
Cache I/O is deliberately best effort with diagnostics; encoding and requested
capture are required boundaries. File publication is individually atomic, not an
all-files transaction, and available output/debug data is intentionally retained
after later failures.
## Findings
### ERR-001 — Completed Native Validation Failures Lose Detail And Acquire An Operational Error Category
**Relevant code:**
[RunProducer.evaluate](../../../internal/framework/pipeline/producer.go#L67),
[combat-semantics validation](../../../internal/modules/dnd/validate/scenedescriptions/combat_semantics/validator.go#L70),
and [terminal fallback handling](../../../internal/framework/pipeline/producer_outcome.go#L13).
The pinned native contracts are defined in PromptKit's
[error declarations](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/engine.go#L89)
and [ValidationResult](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/types.go#L544).
**Failure condition:** Native structural validation completes with a failed
result and nil Go error, after whatever repair allowance was selected. This is
a supported PromptKit outcome, exercised by existing tests. `Validation.Errors`
contains the native content-check diagnostics.
**Expected behavior:** Refuse to interpret/accept that result, retain useful
content-check details in the application failure or fallback explanation, and
preserve the native distinction between a completed failed check and an
operational inability to perform validation. PromptKit reserves `ErrValidation`
for the latter; a completed `ValidationFailed` result is not that Go error.
**Actual behavior:** The producer replaces the result's explanation with
`producer output did not satisfy its native contract`, wrapping a newly supplied
`promptkit.ErrValidation`. The LLM validator similarly substitutes a generic
`native output contract failed` message and that sentinel before marking its
assessment unavailable. Neither path includes `result.Validation.Errors`.
The safety decision is correct: failed output is not interpreted as usable.
However, `errors.Is(..., promptkit.ErrValidation)` now also matches an
application-converted content failure, making it indistinguishable from the
upstream operational category. Without debug, an operator cannot see the supplied
reason for failure; permissive fallback diagnostics inherit the generic text.
With debug enabled, the recorded native result still contains the details, so
this is not complete destruction of evidence.
**Potential remediation:** Use a small application-owned nonacceptance error or
descriptive error construction for completed failed validation, carrying the
available native diagnostic details without copying the whole response into the
error. Keep genuine native Go errors and their causes unchanged. Apply the same
distinction to producer and LLM-validator boundaries; keep the validator's
unavailable-assessment classification.
Distinguish the defensive nil-result case from a present failed result, since it
has no native validation details to report. Preserve strict/permissive outcomes
and `ValidationFailed` checks. Do not send these operational/content diagnostics
through an extra application semantic retry, extend native repair budgets, or
turn internal codes into model-facing guidance. Reuse native result types rather
than adding a replacement validation protocol.
**Evidence and follow-up:**
[Failed-native-validation tests](../../../internal/framework/pipeline/producer_test.go#L162)
exercise both initial and correction responses and prove they are not interpreted
or reassessed. They assert safe fallback and call counts, not retained diagnostic
detail or the operational/content-category distinction. A future fix should
cover those distinctions with controlled native failures and preserve the
existing no-extra-retry behavior. No new test was added during this audit.
### ERR-002 — Successful Extraction Diagnostics Disappear When The Lane Never Continues
**Relevant code:**
[runExtractJob and ordered finalization](../../../internal/framework/pipeline/runner_concurrent.go#L268),
[handleExtractResult](../../../internal/framework/pipeline/runner_concurrent.go#L235),
[continueLane](../../../internal/framework/pipeline/runner_concurrent.go#L349),
[runLanes](../../../internal/framework/pipeline/runner_concurrent.go#L66), and
[CLI diagnostic reporting](../../../internal/cli/pipeline_run.go#L160).
**Failure condition:** One or more chunks finish successfully and return process
diagnostics, such as cache degradation or a qualified-fallback warning. A later
chunk in that lane fails, or a sibling lane fails before its continuation starts.
This also occurs with one worker: finish chunk A, then fail chunk B before the
lane becomes ready. No unusual concurrent interleaving is required.
**Expected behavior:** Stop the failed work and prevent publication as today,
while retaining diagnostics from operations that already completed. The runner's
failure-output helper explicitly aims to preserve already accepted diagnostics,
and the CLI reports the returned diagnostic collection even on runner error.
Not every failed or canceled operation needs a synthetic warning.
**Actual behavior:** Successful results and their diagnostics remain in
`laneExtractState.results`. They enter the lane's ordered diagnostic slice only
when every extraction finishes successfully. That slice reaches a returned
`RunOutput` through continuation. If failure/cancellation prevents continuation,
the coordinator returns only `completedOutputs`; it never folds the successful
partial-lane diagnostics into that result. `failOutput` cannot recover information
that never reached the run's accumulator.
**Consequences:** Operators can lose genuine earlier cache/fallback context on a
failed run. Diagnostic visibility depends on whether the lane happened to reach
continuation, rather than whether the originating operation completed. Ordinary
pipeline failure still propagates, failed lanes do not publish, and native/debug
operation evidence can remain available when enabled. This is diagnostic loss,
not acceptance of partial lane artifacts.
**Potential remediation:** After draining started work, preserve already completed
operations' diagnostics independently of lane continuation eligibility. Fold them
in canonical lane/chunk order and ensure completed-lane diagnostics are not added
twice. Keep artifact merging, normalization, generated handoffs, and publication
disabled for incomplete lanes.
Successful partial results form a sparse map after failures. Do not call the
current dense `finalizeLaneExtract` loop unchanged: iterating only to `len(results)`
can miss higher chunk indices. Iterate known chunk positions with presence checks
or sort actual result keys. Preserve existing cancellation/error precedence;
do not resurrect output returned after cancellation or invent findings for work
that never completed.
**Evidence and follow-up:** The coordinator's storage/continuation branches
establish the loss. Existing
[reverse-completion tests](../../../internal/framework/pipeline/runner_concurrency_test.go#L317)
check successful diagnostic ordering, and
[ordered-step failure tests](../../../internal/framework/pipeline/runner_concurrency_test.go#L266)
check preservation of completed predecessor outputs and suppression of later work.
Those tests do not combine a completed warning-bearing chunk with a later
same-lane failure. That is the focused regression scenario for a future fix.
### ERR-003 — Failure-Output Finalization Suppresses Aggregation Errors
**Relevant code:**
[failOutput](../../../internal/framework/pipeline/runner.go#L446),
[finalizeDiagnostics](../../../internal/framework/pipeline/diagnostics.go#L78),
[Aggregator.Add](../../../internal/framework/diagnostics/aggregator.go#L30),
and the [success-path finalization call](../../../internal/framework/pipeline/runner.go#L263).
**Failure condition:** Individually valid groups accumulated from multiple
operations exceed a final aggregate constraint, and the runner is returning a
stage/cancellation error. A concrete case is more than 128 distinct warning
groups across a sufficiently large configured pipeline. Checked occurrence-total
overflow is another aggregation failure. Per-producer/group validation does not
prove either aggregate constraint.
**Expected behavior:** Keep the primary failure and make a genuine aggregation
failure inspectable, preserving available bounded diagnostic information where
possible. Existing warning bounds and their failure behavior remain in force;
there is no requirement to publish every warning beyond those bounds.
**Actual behavior:** `failOutput` discards the result of `finalizeDiagnostics`.
Its comment incorrectly assumes that validating each diagnostic makes finalization
infallible. `finalizeDiagnostics` returns on `Aggregator.Add` failure before
assigning the locally collected prefix to `output.Diagnostics`. On an earlier
stage failure, the caller consequently receives only that primary error and
typically an empty diagnostic collection, with no aggregation error.
The nominal success path correctly returns an aggregation error, but its call to
`failOutput` repeats the same failed aggregation and still loses the prefix.
This is separate from ERR-002: it affects groups that did reach the accumulator.
**Potential remediation:** Make failure finalization explicitly return/propagate
its error, joining it with the primary cause rather than replacing that cause.
Consider returning the valid bounded prefix alongside the error, clearly as
incomplete failed-run information. Avoid reaggregating an identical failed set.
A small shared failure-return helper or outer finalization boundary can keep
the many return sites consistent.
Retain stable diagnostic ordering, warning-limit failure, non-warning truncation
metadata, and cause identities. Do not silently raise limits, truncate actionable
warnings into apparent success, or introduce an unbounded fallback collector.
**Evidence and follow-up:**
[Aggregator boundary tests](../../../internal/framework/diagnostics/aggregator_test.go#L43)
already prove that valid individual groups can encounter aggregate failures.
[Pipeline diagnostic tests](../../../internal/framework/pipeline/diagnostics_test.go#L20)
cover successful finalization, not a primary failure combined with overflow.
The defect follows from composing these existing branches. A future correction
should retain both causes and bounded available diagnostics on that combined path.
## Reviewed Behavior That Is Deliberate Or Already Protected
| Area | Assessment |
| --- | --- |
| Configuration and preflight | Native loading/inspection failures retain causes and scoped pipeline/module/profile context. CLI classification distinguishes identifiable invalid selections from operational or mixed joined failures. Preflight intentionally does not prove provider readiness, read execution input, or invent defaults for dynamic selections. |
| Complete assessment | Validators continue after rejection/failure/unavailability; caller cancellation and framework/capture failures interrupt. Missing/invalid correction guidance becomes a failed contract, not invented instructions. Rejection text is distinct from operator errors and internal reason codes. |
| Strict/permissive disposition | Explicit permissive recovery may cover native operational failure or exhausted nonacceptance when a module supports a checked fallback. This is selected policy, not suppressed failure by accident. Fallback construction errors retain the original cause, and fallback is disclosed/reuse-ineligible. |
| Native continuation | Undelivered responses and result-less failures do not recover an earlier candidate. Initial/final usable candidates receive assessment once. Exhausted structural repair is not extended by an outer application retry. ERR-001 concerns classification/details, not this safe control flow. |
| Cancellation and timeouts | Caller cancellation takes precedence, prevents fallback/publication, stops dispatch, and drains started jobs. A native operation timeout does not become caller cancellation while the caller remains active. Stable error selection intentionally returns one scoped terminal failure rather than every sibling cancellation. |
| Cache errors | Read/malformed/unusable entries become diagnostic misses, and store I/O failures warn without failing otherwise successful work. Artifact encoding and capture errors remain fatal. This best-effort split is explicit; it should not be changed to universal failure or silent suppression. Failed refresh preserves prior accepted data. |
| Capture errors | Recording errors are sticky and surfaced at returnable boundaries. Ignoring the immediate `executions.json` write result is safe here because the recorder retains it and `Finalize` joins it with the primary cause. Capture failure cannot become model feedback/fallback or trigger another model call. |
| Native reporter calls | Ignored progress/deferred-diagnostic return values do not erase delivery evidence: the native reporter records it, and finalization returns failure with separate presentation causes. Existing tests cover failed stdout/stderr, partial report writes, quiet mode, and retained publication. `AdaptDiagnostics`'s second result is an explanation, not an ignored error. |
| File writes and partial publication | Individual write/close/chmod/rename failures propagate; unpublished temporary siblings are removed on ordinary error paths. Secondary close/remove errors during cleanup are intentionally best effort while preserving the primary write error. Partial output/new debug directories are retained for inspection, not rolled back or automatically deleted. No all-files transaction, power-loss, or hostile-filesystem guarantee is inferred. |
| Domain helpers and panics | Ignored index-presence booleans follow successful reference validation. Identity-key marshal panics operate on fixed string/integer/reference structures whose current encoding cannot fail normally. No new general panic-recovery requirement is inferred for programming errors or unsupported custom collaborators. Earlier correctness findings retain their own reports. |
## Validation And Limits
Both commands 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 ./...
```
Existing test source was inspected for actual coverage, including producer
structural failures, unavailable judgments, assessment-contract failure,
continuation failures, cancellation/timeouts, cache degradation and recovery,
codec failures, aggregate bounds, capture/primary-cause joins, output collisions/
partial publication, and native report/diagnostic delivery failure. The findings
are supported by current control flow and pinned API definitions; no new composed
fault-injection test was implemented for the uncovered combinations.
No real credentials, live provider calls, or production filesystem fault injection
were used. Passing tests/vet do not prove the absence of every exceptional path.
The earlier [concurrency audit](04-concurrency.md) covers the executable's missing
OS-signal adapter; that issue is not reclassified as a newly discovered context
handling defect here. [Resource](05-resources.md) and
[correctness](01-correctness.md) findings are likewise separate.
The current ownership/fallback architecture should be retained. Address the
specific classification and diagnostic-retention gaps without blanket retries,
new mandatory sidecars, automatic destructive recovery, or broader guarantees.
Local report link targets and the final documentation diff were checked.