Files
notarius/docs/roadmap/remediation.md

364 lines
24 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Pipeline Preflight Review Remediation
## Scope And Overall Assessment
Reviewed implementation commit `c08e5ab` against all eleven stages of
[Implementation Plan](implementation.md) and the accepted
[Preflight Feature Roadmap](preflight.md).
A follow-up integration audit at `ab44543` reviewed those stages against the
existing run, configuration, source, reference, cache, capture, and reporting
paths. Findings 1 and 2 remain open; Finding 3 records the additional result.
An algorithmic audit at `3df1a53` adds Findings 4 and 5. It preserves algorithms
explicitly selected during planning and uses source-level complexity analysis,
not production measurements or latency estimates.
The intended architecture is in place. Run and explicit preflight share local
selection and construction; prepared adapters own source parsing; domain owners
validate references; `internal/preflight` discovers selected targets and
interprets native smoke evidence. The CLI owns destination probes, requested
capture, and native readiness reporting. Offline pipeline validation remains
offline. Preflight neither executes the substantive pipeline nor initializes
an accepted-result cache store.
Five follow-ups are warranted: consistent error propagation at the smoke observer
boundary, narrow documentation corrections, consistent handling of marked
sensitive runtime parameters in invocation capture, linear target association
building, and avoiding disabled-capture work. No unintended strengthening of
permissions policy, provider capability requirements, retry budgets, or readiness
guarantees was found. Keep the accepted scope unchanged while remediating.
## Finding 1: Preserve Smoke Observer Errors Independently Of Readiness
**Status: Complete.** Observer and diagnostic errors are joined consistently;
readiness now follows completed native checks independently of recording failure.
Focused smoke/preflight tests pass, including final/combined failures and stopping
before an unchecked profile.
**Priority:** P2 — error handling and separation of responsibilities.
**Affected owners:**
[smoke orchestration](../../internal/preflight/smoke.go), particularly
`RunSmokeChecksObserved` lines 43–48, and the assessment/finalization handoff in
[the preflight command](../../internal/cli/pipeline_preflight.go).
Related plan stages: 4, 6, and 7.
The observer's error is returned only when the diagnostic itself succeeded and
another diagnostic remains. Consequently:
- A failing observer on the final successful diagnostic is silently discarded:
the helper returns a nil error.
- If a diagnostic and its observer both fail, the helper returns only the
diagnostic error, losing the observer error at this boundary.
An offline review test with one successful structured smoke request and an
observer returning a sentinel error reproduced the first case: one observation
was returned with `err == nil`. A final observer returning cancellation has the
same error-loss problem.
The current CLI's sticky recorder normally recovers capture failures during
`Finalize`; the existing capture tests confirm that those failures still yield
an unsuccessful command. This is not a claim that current CLI capture failures
silently succeed. The problem is that the generic smoke helper depends on a
particular caller's recorder behavior and discards an explicit callback error to
influence the caller's readiness calculation. That makes the error contract
surprising and couples orchestration to presentation/disposition.
### Required Change
- Retain errors returned by the observer consistently, including on the final
check and alongside a diagnostic failure. Ordinary wrapping or `errors.Join`
is sufficient; preserve `errors.Is`/`errors.As` identity.
- Keep the native diagnostic verdict on its observation distinct from errors
recording that observation. Retain the collected observations when returning
an error, and stop additional diagnostics when recording fails.
- Let the CLI determine assessment completion from performed diagnostic results
and whether required checks remain, separately from capture/command failure.
A completed positive assessment may still report `ready: true` with nonzero
command status when capture fails, as already agreed. An interrupted sequence
with required checks remaining must not claim readiness.
- Remove the need to suppress callback errors based on their position in the
sequence. No new retry loop, error hierarchy, persisted state, or public report
variant is needed.
### Verification
Add focused tests for a final observer failure and simultaneous diagnostic and
observer failures, checking original error identities. Retain the existing
early-capture-stop, cancellation/capture, and positive-assessment/failed-capture
tests. Verify that additional paid checks do not start after an observer
failure and that report delivery/finalization are not repeated.
## Finding 2: Correct Two Remaining Documentation Boundaries
**Status: Complete.** Capture ownership now names both commands, and substantive
acceptance/fallback guidance is again a subsection of the run lifecycle.
Heading hierarchy and affected link targets were reviewed; whitespace checks pass.
**Priority:** P3 — documentation accuracy and clarity.
Related plan stages: 9 and 10.
1. [Run State Internals](../internal/state.md), lines 131–133, still says that
the run path alone calls `debug.Start`. Explicit preflight now calls the same
allocation lifecycle through `startRunDebug`, as the preceding paragraph
correctly states. Describe both invocation owners and keep shared loaders
storage-free.
2. [Operations](../operations.md), lines 147–187, inserts the new top-level
`Preflight Lifecycle` section before the existing `Acceptance And Fallback`
subsection. This makes substantive run acceptance, semantic continuation, and
permissive artifact fallback appear to be part of preflight. Move the
preflight section after that run subsection, or otherwise restore the run
subsection's correct parent. Preserve the explicit distinction that producer
fallback does not change preflight's smoke verdict.
### Verification
Review the resulting heading hierarchy and capture-owner wording against the
implemented command. Check affected links and `git diff --check`; no prose
snapshot tests or additional upstream-library documentation are needed.
## Finding 3: Apply Existing Sensitive-Parameter Handling To Invocation Context
**Status: Complete.** Both commands use shared early context capture that omits
raw provider-parameter maps. Raw operation-request evidence uses the same
projection; target-aware native evidence still retains masked effective values.
Regression tests scan both commands' captures on success and early failure,
verify actual provider values are unchanged, and retain ordinary settings.
**Priority:** P2 — integration with the established capture contract.
Related plan stages: 1, 4, and 7.
**Affected owners:** Early context writing in
[the preflight command](../../internal/cli/pipeline_preflight.go), line 108,
and [the run command](../../internal/cli/pipeline_run.go), line 67, plus the shared
[capture helpers](../../internal/cli/run_capture.go).
Preflight copies the run path's direct serialization of
`input.Overrides.Execution` into `context.json`. This includes raw
`--llm-extra-params` values. That bypasses both ConfigKit's secret-aware effective
configuration writer and the selected-target masking used for native evidence.
A temporary offline regression test selected a profile with an `extra_params.token`
field marked sensitive by the existing definition, then supplied a different
synthetic value for that same field through `--llm-extra-params`. The provider
fixture confirmed that the intended runtime override was used. Capture contained:
| Capture surface | Result |
| --- | --- |
| Effective application configuration | Sensitive field redacted. |
| Native preflight smoke report | Sensitive runtime value redacted. |
| Preflight invocation context | Sensitive runtime value present verbatim. |
| Ordinary run invocation context | Same sensitive runtime value present verbatim. |
The assertion that the marked value is absent from retained context failed for
both commands. Thus this is a pre-existing run pattern propagated into the new
feature, rather than a defect in native smoke-report redaction. It affects
explicitly enabled debug capture, not the public readiness report.
The existing [architecture policy](../policy/architecture.md#state-output-and-safety)
already requires preserving marked-secret handling and native credential
omissions. This finding requests consistency with that contract, not a new
threat model or a claim that debug bundles sanitize arbitrary application data.
### Required Change
- Reuse a small common context-capture helper for run and preflight, so the two
invocation owners do not independently serialize raw runtime parameter maps.
- Keep early capture available before pipeline/target selection. Omit raw
`ExtraParams` values from that early record and retain supplied-state metadata
when useful. Detailed effective parameters can remain in the existing native
evidence, where selected-profile/backend marks are already applied.
- Preserve the existing native evidence path's redaction of marked parameters
and retention of ordinary non-sensitive settings. Do not mutate the values
passed to PromptKit or add provider calls/configuration loads to capture them.
- Use established sensitivity metadata; do not add heuristic scanning of source,
references, prompts, responses, arbitrary strings, or provider parameter names.
No new configuration restrictions, permission rules, or logging subsystem is
needed.
### Verification
Add a shared capture-boundary regression for both commands using synthetic
marked runtime parameters. Assert that the provider receives the intended
value while the retained context does not contain it; verify marked native
settings remain redacted and ordinary settings are still retained. Exercise an
early preparation failure as well as successful execution, since early capture
must not depend on later native evidence becoming available. Prefer content and
immutability assertions over full snapshots of the private capture layout.
## Finding 4: Build Target Associations With Ordered Sets
**Priority:** P2 — scalability; plan Stage 3.
**Owner:** [Target discovery](../../internal/preflight/targets.go), especially
`DiscoverTargets` and `appendScope`.
Let `A` be the number of selected role/initial-prompt associations visited by
discovery, `P` the distinct selected profiles, and `K` the distinct access scopes.
The outer profile/backend lookup maps are appropriate, but `appendScope` scans
the complete accumulated binding slice on every insertion. For `B` distinct
bindings sharing one profile and backend, each slice performs
`0 + 1 + ... + (B-1)` comparisons. The two slices together perform `B(B-1)`
comparisons: **Theta(B²)** even though there are only Theta(B) associations to
return. The same backend-list problem exists when many distinct profiles share
one backend.
Discovery also calls native `InspectProfile` before consulting its existing
profile map, so a shared profile is inspected once per association rather than
once per profile. Repeated initial prompts without an explicit profile likewise
repeat `InspectPrompt`. These return detached resource views; that repeated
inspection/copy work is unnecessary for the invocation's fixed captured engine.
### Refactoring Opportunity
- Retain ordered result slices and companion membership sets keyed by the
comparable `BindingScope` value for each profile/access target. Insert into
the slice only when absent from its set. This gives expected **O(A)**
association-building time and **O(A + P + K)** bookkeeping space, preserving
exact deduplication and first-use ordering.
- Reuse successful profile selection/backend association data once each profile
is inspected. Memoize an initial prompt's default-profile lookup within this
discovery call where it repeats. Native inspection calls can then be bounded
by distinct selected resources rather than associations. Keep the small needed
identities/indexes, not an application-owned replacement resource registry.
- Preserve per-binding cancellation checks, error scope, endpoint-only behavior,
and the native provider-check schedule. Do not introduce process-global caches,
target fingerprints, altered profile equivalence, or different paid probes.
The roadmap specifies deduplicated targets and retained associations, not linear
slice scans as the required implementation. This optimization preserves the
accepted algorithmic policy. Native inspection's own cost is additional to the
association bound above; no upstream cost or real-world speedup is assumed here.
### Verification
Use independent expected ordered associations for shared-profile,
shared-backend/different-profile, and duplicate-binding/multiple-prompt cases.
Retain the existing target and native probe-deduplication tests. Verify the
complexity improvement by reviewing the map-based insertion path; wall-clock
thresholds and production benchmarks are unnecessary.
## Finding 5: Skip Evidence Preparation When Capture Is Disabled
**Priority:** P3 — avoidable work; plan Stage 7.
**Owner:** [Preflight command](../../internal/cli/pipeline_preflight.go), lines
180–190, and [evidence writer construction](../../internal/cli/run_capture.go).
`executePreflight` constructs `newRunEvidenceRecorder(capture, loaded.result)`
and supplies its observation callback unconditionally. With capture disabled,
the underlying recorder ultimately discards writes, but the work before that
no-op boundary still happens:
- Construction enumerates all `H` historical configuration paths and all `R`
configured profiles/backends, including unselected resources, to build masks.
This entails at least **Omega(H + R)** capture-specific traversal work and
temporary indexing, in addition to the native metadata API's own costs.
- Every smoke report still passes through target masking, which can copy
parameter maps for marked fields, even though none will be written. For `S`
reports with `M` matching top-level marks over `E` parameter entries, that
existing per-mark shallow-copy path can perform **O(S * M * E)** extra work.
The ordinary run path already avoids constructing this writer when capture is
disabled. The new preflight call site bypasses that guard.
### Refactoring Opportunity And Verification
Construct the evidence writer and install its callback only when capture is
enabled; otherwise pass a nil observer to `RunSmokeChecksObserved`. Its native
observations still return normally for readiness interpretation. This reduces
disabled-capture evidence preparation to **O(1)**, excluding required smoke
execution, report construction, and the earlier configuration load.
Keep active capture's masks, failure propagation, and native usage separation
unchanged, including Findings 1 and 3's required behavior. Do not change the
shared helper merely to forbid existing standalone/test uses of a nil recorder.
Use existing enabled/disabled preflight tests to verify identical readiness and
provider-call behavior with no debug files when disabled. No performance threshold
or new instrumentation framework is needed. This finding does not require
redesigning the pre-existing active-capture masking algorithm.
## Stage-By-Stage Review Evidence
| Plan stage | Review result |
| --- | --- |
| 1 — Shared invocation preparation | Both commands use the same flags, loading, reference selection, resolution, materialization, construction, input reads, and session selection. Run retains its execution/publication owner. Existing selection/regression tests pass. |
| 2 — Source and reference checks | `PreparedPipeline.ParseSource` is shared with the runner; document validation and cancellation remain adapter/framework-owned. The runner builds its index once. Constructors retain domain reference checks; a full configured D&D preflight accepts generated dependencies without fabricated artifacts. |
| 3 — Target discovery | Explicit initial-prompt declarations separate independently selected requests from correction dependencies. Native inspection selects profiles; exact identities deduplicate profile/backend scopes, retaining bindings. Endpoint-only profiles and selected validators are covered. |
| 4 — Native smoke orchestration | Access checks and structured generation are deduplicated, native overrides/retries are forwarded, and actual facts determine verdicts. Unsupported/inapplicable capabilities add no failed check or warning. Finding 1 concerns observer error propagation. |
| 5 — Destination probes | Standard-library temporary probes are cleaned up; output failure and cache warnings have different dispositions. Auto/refresh leave accepted entries unchanged; bypass/deterministic work avoids cache access. No permission convergence was added. |
| 6 — Command and report | Both native command spellings work. Text/JSON/YAML and unsuccessful assessments use CommandKit reporting; quiet/verbose and presentation failures retain native behavior. Assessment disposition needs the narrow adjustment described in Finding 1. |
| 7 — Capture and causes | Requested capture starts before selection/engine work, updates `latest`, and finalizes before reporting. Existing tests retain cancellation and sticky capture causes, including a positive assessment with failed capture. Finding 1 removes the lower helper's reliance on that sticky mechanism. Finding 3 addresses raw invocation context bypassing the existing sensitive-parameter treatment. |
| 8 — Assembled verification | Existing real-kit/local-provider tests pass. An additional temporary offline test exercised the unabridged maintained D&D pipeline, its ordinary transcript/reference inputs, generated handoffs, and selected target discovery; it passed with one shared-profile model call and no substantive execution. |
| 9 — Public documentation | Command/report and subprocess workflows are documented, including fixture scope and process-status handling. Finding 2 corrects the Operations hierarchy. |
| 10 — Internals and architecture | Native ownership, shared parsing, online versus offline boundaries, and smoke usage separation are documented. Finding 2 corrects the stale run-only capture sentence. No unrelated architecture restriction was introduced. |
| 11 — Final verification | Tests, vet, build, both help routes, and offline validation succeed. Correctness/documentation findings and the additional algorithmic opportunities above remain recorded for remediation. |
## Algorithmic Audit Coverage
| Plan stage | Algorithmic assessment |
| --- | --- |
| 1 — Shared preparation | The extraction preserves the prior configuration/selection/materialization algorithms; no additional nested scan was introduced by the shared handoff itself. These deliberately reused algorithms were not redesigned. |
| 2 — Parsing | Parsing/document validation is shared without a duplicate run parse; source-index construction remains once per run. No new algorithmic defect identified. |
| 3 — Discovery | Finding 4 identifies quadratic binding accumulation and repeated resource inspections; hash-indexed target lookup itself is appropriate. |
| 4 — Smoke checks | Sequential iteration is O(P + K) orchestration, excluding native calls and returned evidence. The agreed once-per-access/once-per-profile schedule and native retries are retained, not reconsidered. Finding 1 already covers the callback error issue. |
| 5 — Destinations | Cache-use detection is linear in selected lanes and temporary-file probes are bounded per destination. Repeated constant-count scans do not make this quadratic. The filesystem policy is unchanged. |
| 6 — Readiness report | Check accumulation and rendering use linear passes; serializing associated bindings is proportional to emitted data. No additional asymptotic issue identified. |
| 7 — Capture | Finding 5 removes work for disabled capture. Findings 1 and 3 retain the previously established correctness fixes; no new capture algorithm or security policy is proposed. |
| 8 — Tests | Existing tests express native verdicts, scopes, and probe counts. Future verification should protect these behaviors without timing assertions. |
| 9 — Public docs | No runtime algorithm introduced; the earlier documentation finding remains unchanged. |
| 10 — Internal docs/policy | No runtime algorithm introduced and no reconsideration of accepted native ownership or capability policy. |
| 11 — Verification | Source-level complexity analysis and focused tests suffice for these opportunities; no live-provider or real-world performance collection was needed. |
## Follow-Up Integration Audit Evidence
- Stages 1–2: Compared extracted loading/selection/preparation and parsing against
the original run path. Existing source-relative path, selector specificity,
unbinding, generated-reference, session/profile override, construction-order,
and source-index regression tests pass without cached test results.
- Stages 3–4: Checked initial/correction/validator target selection against actual
request builders and native override handling. Existing native smoke facts,
deduplication, endpoint-only profile, and typed-cause tests pass. No additional
target-resolution or provider-ownership conflict was found.
- Stage 5: An additional real-cache round trip ran a pipeline, performed both
auto and refresh preflight, and ran the pipeline again with auto reuse. Both
preflights left accepted cache bytes unchanged, each performed a smoke call,
and the subsequent run reused the original acceptance without new producer
calls. Output and cache file-placement helpers introduce no conflicting root
or permission treatment in these paths.
- Stages 6–7: Compared native outcome/delivery evidence and capture ownership
with ordinary run. Findings 1 and 3 identify the remaining error-propagation
and parameter-capture inconsistencies; no duplicate execution, publication,
or ordinary usage accounting was introduced.
- Stage 8: Ran the additional round-trip and marked-parameter reproduction tests
through a temporary Go overlay using real application configuration/registries
and a fake model client. Only the new sensitive-context assertion failed.
- Stages 9–11: Checked the new consumer/report guidance against the existing
subprocess protocol, configuration ownership, debug policy, and offline command
boundary. Finding 2 remains the narrow documentation correction; no additional
contract conflict was identified. The normal full test suite and vet pass.
## Checks Run During Review
- `go test ./...`
- `go test -count=1 ./internal/cli ./internal/preflight ./internal/framework/pipeline`
- `go test -race ./internal/preflight ./internal/cli -run 'TestPreflight|TestSmoke' -count=1`
- `go vet ./...`
- Built `./cmd/notarius` to a temporary path outside the repository.
- Exercised `help pipeline preflight`, `preflight --help`, and offline
`pipeline validate dnd-session --config examples/dnd-complete/config.yml`.
- Temporary Go-overlay tests exercised the full D&D preflight and the terminal
observer-error case without modifying application or permanent test files.
- The follow-up audit reran uncached tests for CLI, preflight, configuration,
pipeline, file I/O, debug allocation, and accepted-result cache packages, plus
`go test ./...` and `go vet ./...`.
- Additional temporary integration tests passed the run/preflight/cache round
trip and reproduced Finding 3 with a failing marked-context assertion in both
command paths. They used synthetic placeholders, not actual credentials.
- The algorithmic audit reran `go test ./internal/preflight ./internal/cli`
successfully. Findings 4 and 5 follow from source-level operation counts and
control flow; no benchmark or live-provider measurements were collected.
No live provider calls or real credentials were used. Artifacts and accepted cache
entries exercised by the round-trip tests were synthetic temporary fixtures;
no production state, application code, or permanent test files were modified.