Remove completed failed-load inspection plans

This commit is contained in:
2026-12-05 18:58:21 +00:00
parent a44134769f
commit 9037fdb74e
4 changed files with 0 additions and 890 deletions

View File

@@ -1,178 +0,0 @@
# Inspect configuration independently of validation outcome
Status: implemented and validated. The [configuration contract](../config.md)
owns current behavior.
Baseline: commit `4a7ae66`, following the typed-value and inspection-view work.
## Purpose and user intent
Operators need to inspect invalid configurations at least as easily as valid
ones. A failed load must report its error; failure is not a reason to withhold
configuration evidence that ConfigKit has already produced.
Narratio's motivating workflow is `config validate`, followed by `config show`
or `config explain` for the same selected inputs. For example, an unsupported
`storage.backend` value should be inspectable together with the import, overlay,
or override that contributed it. The application's CommandKit/ckconfig adapter
should use ConfigKit's native reporting interface rather than reload the input
with validation disabled or reconstruct provenance itself.
Success or failure describes the outcome of processing and validation.
Inspection describes the available configuration evidence. These are separate
facts; access to a report does not imply that configuration passed validation.
## Current baseline
[LoadError](../../diagnostic.go) exposes diagnostics and sanitized source records.
Both loading entry points currently return a nil Result on error. A successful
[Result](../../lifecycle.go) provides current typed values and a separately frozen
[Inspection](../../inspection_view.go) view with effective rendering, history,
explanations, metadata, source contexts, and comparison.
Internally, history and the resolved document are retained before secret lookup
and final validation. However, sensitivity, source records, resource contexts,
and secret-reference reporting are finalized on the success path in
[load_result.go](../../internal/engine/load_result.go). Error construction drops
that inspection state. Simply attaching the unfinished state to LoadError would
not provide existing redaction and reporting behavior.
The final validator is expected to be read-only. Its existing mutation audit can
reject value, sensitivity, or resolved-secret changes. A retained snapshot from
before that callback remains useful even if the callback violates its contract.
## Target end state
### One inspection experience
An invalid resolved configuration supports the same reporting operations and
public Inspection type as a valid one:
- Whole-configuration and selected-subtree effective output with existing redaction.
- Native-path explanations, rendered explanations, effective presence/origins,
chronological history, and historical-path enumeration.
- Original source IDs, source catalogs, locations, and passive resource contexts.
- Existing structural comparison and paired redaction at matching scopes,
including comparisons between accepted and rejected configuration snapshots.
Preserve canonical reporting scopes, explicit query path intent, absent/null
behavior, ancestor evidence, sequence-atomic differences, and ordinary writer
failure behavior. Scoping remains a reporting focus. The error's sources and the
view's sources should refer consistently to the same load and evidence, using
the existing sanitization rules.
Add an optional inspection accessor on LoadError, mirroring Result's scope
selection:
```go
func (e *LoadError) InspectSubtree(path Path) (Inspection, bool)
```
The root Path requests whole-configuration inspection; other scopes follow the
existing rules. Reporting adapters can accept Result and LoadError through the
same inspection-acquisition interface. The Boolean concerns snapshot availability
and path validity, not validation success or presence of the selected scope.
A valid absent scope behaves as it does today.
Ordinary semantic rejection must not leave consumers with a reduced reporting
interface. Callers handle the non-nil error and retrieve inspection through their
normal reporting adapter. Preserve existing load signatures and nil Result
returns on error as a compatibility choice, not a rule that rejected
configurations must be inaccessible.
This addition concerns reporting data. It does not require typed execution access
through an error, and does not establish a general prohibition on such access.
### Evidence from the failing invocation
A view is backed by retained evidence from that invocation. Reading it does not
reload sources, rerun callbacks, repeat secret lookup, or consult changed inputs.
The evidence is frozen independently of caller-owned objects and subsequent
loads. Existing detached-record and passive resource-context ownership applies;
resource contents themselves are still read only when the application requests
access, under the existing resource contract.
When source assembly, typed decoding, overrides, and recorded resolution have
produced the resolved snapshot, preserve it on later reported failure. This
includes semantic validation errors, final registered-identity failures, and
secret lookup failures when the retained snapshot is available. Secret references
can still be reported by name without retaining credential contents. Validation
success is not an admission condition for inspection.
Use the candidate presented to the final validator as the inspection snapshot
for errors reported during that callback, including mutation errors.
Identify it as the pre-validation candidate; do not silently replace it with
unrecorded callback mutations or invent origins for those mutations. The existing
mutation diagnostic remains available alongside the snapshot. A callback failure
must not automatically erase previously retained evidence.
When processing stops earlier, keep diagnostics and available source evidence,
and expose the latest coherent checkpoint already produced by the pipeline whose
values, history, and sensitivity can be reported faithfully. Identify its
processing stage and limitations using lightweight snapshot-stage information
alongside the acquired Inspection. This can include an earlier decoded candidate
when a later CLI assignment fails, or a resolver's entry candidate when resolution
fails. Availability follows the actual processing completed in that invocation.
The [implementation plan](implementation.md) specifies the checkpoint inventory,
public stage representation, failure-exit selection and execution order. Earlier
acquisition and parsing failures may have diagnostics/source evidence alone. This approach reuses existing checkpoints;
it does not require snapshots after every phase or a new partial-decoding or
recovery framework. Do not label an earlier or incomplete snapshot as fully
resolved, or fabricate omitted values and history. Absence of an inspection view
means there is no supported configuration snapshot for that failure, not that an
invalid configuration is categorically uninspectable.
Snapshot stage identifies completed processing, not a second success flag or a
new validation policy. Where a view is available, the same reporting semantics
apply to the evidence it actually contains. A failed load remains an error;
inspection does not turn it into a successful load or continue startup for the
application.
### Existing safety and lifecycle behavior
Reuse current sensitivity classification and historical/paired redaction for
both successful and failed loads. Credential contents remain outside inspection,
and application-authored messages retain their existing responsibility boundary.
No additional confidentiality or isolation guarantee is introduced.
Keep the existing processing order, callback contracts, error classifications,
composition rules, and resource cleanup. Error inspection does not require a
second validation pass or a special load mode. A snapshot unavailable because of
an existing history/resource limit does not authorize bypassing that limit.
Snapshot retention should reuse already produced evidence where possible rather
than duplicate complete trees or introduce a global cache.
## Changes needed from the baseline
The engine needs a shared inspection-finalization boundary used by success and
eligible error returns. It must complete classification and source/context
reporting before exposing a view, preserve the candidate represented by its
history, and carry that evidence through engine and root LoadError wrappers.
The ordinary result-publication path should reuse that owner.
The public facade needs error inspection acquisition, scope selection, and a
clear account of snapshot availability/stage. Existing consumers of LoadError
and Result should continue to work. Downstream adapters can then share reporting
logic across outcomes; Narratio and ckconfig integration changes remain owned by
those projects rather than implemented inside ConfigKit.
Current architecture and configuration documentation must distinguish error
status from inspectability. Revise wording about failure and inspection where it
currently assumes only successful loads have reports, including comparison
eligibility. Record the architectural decision in an ADR, with references to the
existing lifecycle and inspection decisions. Keep implemented-behavior claims
unchanged until implementation lands; this pass creates no ADR or policy changes.
Behavioral coverage should establish same-invocation values and provenance after
semantic rejection, defaults/layers/CLI/resolution agreement, earlier-failure
availability, validator-mutation snapshot identity, and sensitive current and
historical output. Include typed secrets, final identity failure, accepted versus
rejected snapshot comparison, scoped reports, and independent loads. A maintained
consumer example should demonstrate rendering and explanation after an error
without a second load. Reuse existing mechanisms and tests where they already
protect unchanged behavior; avoid private-call-count or performance thresholds.
Completion means a consumer can investigate rejected resolved settings through
the ordinary inspection interface, see the stage and limits of any earlier
snapshot, and continue to receive the original failure diagnostics. The
[implementation plan](implementation.md) owns sequencing and verification.

View File

@@ -1,348 +0,0 @@
# Implementation plan: inspect failed configuration loads
Status: complete; all stages implemented and validated.
Baseline: `5e0f406`, with runtime behavior at `4a7ae66`.
## Scope and execution
Implement [failed-load-inspection.md](failed-load-inspection.md). Invalid
configuration has the same inspection interface as valid configuration; the
error remains authoritative about processing/validation outcome. Implement stages
in order as one end-to-end sprint for a Luna coding agent. Intermediate stages
need not compile. No temporary compatibility framework is needed.
Read [development guidance](../development.md), [agents](../policy/agents.md),
[architecture](../policy/architecture.md), [testing](../policy/testing.md), and
[documentation](../policy/documentation.md). Follow current contracts for
[inspection](../config.md#layered-metadata), [failures](../config.md#results-and-failures),
and [ownership](../config.md#completion-and-resource-lifetime).
The original Narratio request is background; the roadmap incorporates the user's
subsequent decisions. This plan does not change composition, callback contracts,
source-version policy, the public load signatures, or nil Result returns on error.
Keep exported types root-owned. Share engine history, classification, rendering,
comparison and source conversion mechanisms. No new dependencies, global caches,
background work, load mode, reload, callback retry, permissive decoding, or
publication gate is needed. Existing error messages/codes and diagnostic ordering
continue to apply. Inspection is reporting access; this addition does not expose
typed Config through errors or establish a general prohibition on doing so.
## Selected API and checkpoint semantics
Add these root declarations (engine equivalents remain private to consumers):
```go
func (e *LoadError) InspectSubtree(path Path) (Inspection, bool)
type InspectionStage string
func (i Inspection) Stage() InspectionStage
```
Use named constants `InspectionStageMain`, `InspectionStageComposed`,
`InspectionStageInherited`, `InspectionStageDecoded`, `InspectionStageOverridden`,
`InspectionStageResolved`, and `InspectionStageValidated`, with string values
`"main"`, `"composed"`, `"inherited"`, `"decoded"`, `"overridden"`, `"resolved"`,
and `"validated"`. The zero stage is `""` for an unavailable/zero view. Stage
identifies the represented checkpoint, not the error location or a substitute
for handling the load error. All scopes of one snapshot have the same stage.
Successful Result views report Validated. A resolved snapshot does not assert
successful secret lookup, final identity checking or validation.
InspectSubtree mirrors the existing Result method: nil/zero errors, unavailable
snapshot or invalid Path return false; a valid absent scope succeeds. Preserve
canonical scope equivalence and all existing explicit-query behavior. Use the
existing Inspection methods for output, history, sources, SourceContext and Diff.
Comparison operates on represented frozen values at matching scopes regardless
of stage or load outcome; it does not compare diagnostic status. Preserve atomic
sequence/ancestor differences, paired redaction and cross-root-type support.
Implement the following checkpoint selection for both Load and LoadLayered:
| Failure or return point | Snapshot represented |
| --- | --- |
| Options, source acquisition/parsing, unsupported schema, or main strict-composition failure before a coherent main tier and schema exist | No configuration view; retain ordinary diagnostics/source evidence. |
| Main-only version rejection after successful main composition | Main. |
| Later underlay/tier/selected-overlay assembly failure | Last completed main tier (Main); do not present partially assembled peers as a completed tier. |
| Resource-context completion or sibling-inheritance failure after full tier composition | Composed. Context queries expose only contexts actually established. |
| Override preflight or typed-default/decode failure after successful inheritance | Inherited. No partial typed decode is presented. |
| CLI type/decode/assignment failure after a successful typed decode | Decoded; the original pre-CLI candidate, not a partially applied override batch. |
| Resolver error, unrecorded mutation, projection or auditing failure after successful CLI application | Overridden; the resolver-entry candidate, without failed callback edits. |
| Successful resolution followed by detachment, secret lookup, final identity, final validator or publication-detachment failure | Resolved, with completed recorded resolution evidence. |
| Successful load | Validated; existing successful snapshot behavior. |
Advance to the next checkpoint on successful completion of that phase, even when
it has no selected work (for example, no inheritance or resolver). Main/Composed/
Inherited describe source trees before typed defaults. Decoded and later describe
typed projections. With NoSource and no contributed document there is no raw-tree
checkpoint; successful defaults/decoding can still produce a typed snapshot,
including a null root. Preserve absence rather than invent an empty source tree.
Only existing coherent candidates are eligible. A failed phase's partial state is
not substituted for its input checkpoint. The earlier source candidates above
require the established schema bindings for classification; this plan does not
add a second permissive schema parser for unsupported schemas. All errors retain
whatever source/diagnostic evidence the current API already returns.
For every error during final Validate, including value, sensitivity and Secret
mutation, show the candidate supplied to that validator. Do not project mutated
callback data into the error view, invent its origins, or withhold the existing
snapshot merely because mutation was reported. Callback panics keep their current
behavior; this feature does not introduce panic recovery.
Retained-history admission and existing source/projection limits still apply.
Count all roots retained by a returned inspection using the existing counter.
If a newer candidate cannot be retained, use an available earlier admissible
checkpoint where possible, with its actual stage; otherwise return no view.
Keep the original failure diagnostics, including any existing limit error. A
failure to prepare optional error inspection must not replace those diagnostics
or cause another load. No new numeric budgets or benchmark thresholds are added.
## Stage 1 — Record the inspection-on-failure decision
**Complete.**
Write ADR 0025 (use the next unused number if another ADR has landed) recording
inspection independent of validation outcome, the error accessor, reuse of the
existing Inspection interface, and identified existing checkpoints. Record the
already approved decisions as Accepted. Keep discussion focused on ConfigKit;
alternatives belong in Alternatives Considered. Reference ADRs 0003, 0005, 0008,
0010 and 0024 as relevant. The comparison addition extends successful-load-only
eligibility without changing equality or redaction. Do not rewrite accepted ADR
decision text; the new record explains the extension.
Acceptance: the decision describes selected behavior and rationale without
requiring approval again, execution sequencing, or unrelated safety guarantees.
## Stage 2 — Add checkpoint state and share inspection finalization
**Complete.**
Read `internal/engine/load.go`, `load_result.go`, `diagnostic.go`, `secret.go`,
`inspection_view.go`, and the retained-node counter in `history.go`.
Add engine checkpoint stage/state and optional frozen inspection ownership on
engine LoadError. Keep checkpoint acquisition separate from diagnostic collection
so ordinary early errors remain cheap. Add Stage to engine views; preserve the
existing root facade conversion boundary for Stage until stage 7 exposes it.
Extract the non-generic inspection finishing work from publishLoadResult:
classification, source records, passive contexts, diagnostics and known
secret-reference reporting. Reuse it for successful and failed candidates.
Success must still detach validated typed data as today. Failure needs no typed
execution result and must not discard a frozen candidate if final detachment
fails. Classification must finish before any view becomes observable.
Preserve existing conservative source-version sanitization on error catalogs.
Use the same error source catalog for LoadError.Sources/Source and its inspection
view; do not let incomplete candidate coverage unmask evidence from other acquired
sources. Preserve all source IDs, including sources whose data is not in the
selected checkpoint. Effective origins/history describe only the checkpoint.
Include only passive contexts actually acquired and established.
Acceptance: shared finalization can produce a fully classified immutable engine
inspection independently of successful result publication. Nil/zero error and
view behavior stays safe. No raw credential values are retained.
## Stage 3 — Support source-tree inspection history
**Complete.**
Read `load_input.go`, `history_model.go`, `history_source.go`,
`history_inheritance.go`, `load_metadata.go`, `metadata.go` and `explain.go`.
Extract the source/inheritance prefix construction currently embedded in
preparePostDecodeOverrideContext into reusable helpers.
Build Main, Composed and Inherited error views from their actual document,
source applications, origins, overlay/sequence contribution evidence and, only
when completed, inheritance operations. Reuse existing producers and replay.
Set effective metadata from the represented tree, its real explicit contributions
and origins. The source-stage baseline is absent: do not run Defaults or invent
default-origin values. Source-version evidence follows existing consumption and
sanitization rules, not new configuration values inserted into the tree.
Generalize history sealing so these prefixes can freeze without fabricating
pre/post-CLI or resolution checkpoints. Keep successful-load history ordering
unchanged. An unexpanded extends declaration can appear in a source-stage report;
its stage explains that inheritance is unfinished. Do not interpret controls
again while querying or rendering it.
Ensure the shared classification sees represented paths, retained historical
shapes, tag-based sensitivity from the valid schema, the application predicate,
source-version evidence and completed inheritance dependencies. Final document
lookup indexes and historical path inventories must cover the represented tree.
Use the existing retained-node budget for these error histories too.
Add focused engine tests for a source-stage view after inheritance/decode failure,
including raw input type mismatch, historical overlay displacement and tagged
container sensitivity. Verify no invented defaults, inheritance or decoding.
## Stage 4 — Support decoded and resolver-entry history prefixes
**Complete.**
Refactor preparePostDecodeOverrideContext so a successful decoded candidate can
be inspected even when a later override batch fails. Reuse metadataFromDecoded,
source/inheritance prefix observation and the pre-CLI checkpoint. Do not add CLI
applications from a batch that failed assignment, even if some earlier loop
iterations assigned working values. Sources/diagnostics may still describe the
attempted flags under their current contracts.
The completed post-CLI prefix is the Overridden checkpoint. Resolver errors use
its frozen entry evidence, not the partially modified typed object. Avoid
freezing or sharing a builder that successful resolution continues to mutate:
seal on the error path, or create a properly owned prefix using existing retained
payloads. The callback's own fixed entry metadata remains independent as today.
Add engine tests for invalid CLI assignment after valid decoding, a resolver that
mutates then returns an error, and a resolver that fails the recorded-change audit.
Assert represented values, stage, CLI/source origins, history and absence of failed
callback edits. Keep successful resolution correspondence/history tests passing.
## Stage 5 — Retain resolved candidates on final failures
**Complete.**
Wire the already prepared resolved history into error handling after resolution.
Complete classification through the Stage 2 owner before returning it on secret
lookup errors, final registered-identity failures, semantic rejection and
validator-mutation errors. Retain known successful SecretReferenceInfo only for
references actually resolved in this invocation, under existing semantics;
unresolved reference names remain configuration input, not resolved credentials.
Validator errors, including invalid diagnostic paths and mutations to values,
dynamic classification or secret state, retain the pre-validator candidate. Do
not rerun the validator or use its mutated object to rebuild the snapshot. A
successful load retains its existing detached Config and Validated inspection.
Add representative engine tests for each final-failure boundary and the successful
counterpart. Check existing diagnostic codes and nil Loaded return. Include
mutation combined with an ordinary semantic error to prove neither suppresses the
report. Reuse the normal success/error source handling rather than cloning it.
## Stage 6 — Wire the earlier failure exits and enforce ownership/admission
**Complete.**
Walk executeLoadRequest and its ordinary/layered helpers against the table above.
Carry small checkpoint descriptors referencing existing candidate documents and
evidence. Preserve the last completed main tier across later tier/overlay errors,
and the composed tree across inheritance failure. Helpers returning an empty or
partially updated assembledInput must not overwrite the last coherent candidate.
Materialize an error view only when returning the failure. Successful loads need
not build and retain full historical models for every earlier phase. Retain only
necessary existing candidate evidence; do not add a full tree copy per checkpoint
or a generic tracing/event framework. If a helper mutates a borrowed candidate,
provide the ownership separation needed to preserve that candidate before the
mutation; do not assume an input passed by value owns its node pointers.
Keep classification/payloads consistent with the selected checkpoint. Existing
budget exhaustion can prevent a view or cause fallback to an earlier admitted
candidate; original diagnostics survive. Before returning, release library-owned
handles normally, drop working typed values and mutable builders from LoadError,
and retain only frozen reporting state and passive contexts.
Add a table-driven engine lifecycle test covering the matrix's distinct boundaries
for ordinary and layered loads, including malformed early input with no view,
main-version rejection, layer failure, absent NoSource input, and budget failure.
Use existing narrow limit seams for deterministic admission cases. Preserve the
prior history-limit boundary before secret lookup and validation on success;
optional failure inspection must not execute hooks skipped by the original error.
## Stage 7 — Expose the shared public inspection interface
**Complete.**
Add LoadError.InspectSubtree and the root InspectionStage declarations/Stage method
specified above. Convert stage values explicitly across the private boundary.
Reuse engine.NewInspectionView and existing root conversions; do not embed an
engine type publicly or construct a fake Result with no typed configuration.
Document nil/zero errors, absent scopes and stage meanings beside declarations.
Result.InspectSubtree and LoadError.InspectSubtree must satisfy the same small
consumer-owned interface. Metadata, Sources, Source, SourceContext, Explain,
WriteExplanation, WriteEffective, HistoricalPaths and Diff retain their existing
view behavior. No separate reduced failure-view type or comparison mode is added.
Add public tests for root/nested/absent/numeric scopes, nil/zero/no-snapshot errors,
Stage on successful and failed views, native queries outside a focus, and zero
view behavior. Verify errors.As still discovers LoadError with unchanged
Error/Diagnostics behavior and every failed load still returns a nil Result.
## Stage 8 — Verify redaction and evidence parity across outcomes
**Complete.**
Use focused public fixtures to verify rendered values, metadata and history agree
for the same candidate accepted versus rejected by final validation. Exercise
representative underlay/import/overlay, inheritance, CLI and recorded-resolution
contributions without duplicating every existing combination test.
Cover tagged and predicate-sensitive values, dynamic struct tags after resolution,
secret lookup failures and successful references, removed historical values and
source-version evidence. Use disposable canaries to prove no credential or
classified value appears in effective/historical/explanation/diff reports. Include
a sensitive pre-validator candidate whose validator removes classification or
changes secret state; inspection must retain the original classification.
Compare accepted/rejected snapshots at equal scopes, including different root Go
types and different stages; structural values govern differences, not validation
status. Preserve existing paired sensitivity and ancestor/sequence behavior.
Mutate returned query records and callback-retained objects after return; reports
must stay detached/frozen. Check independent loads and passive source contexts
through failure, without keeping loading handles open or re-reading inputs.
Run focused tests plus `go test -race ./...` when the ownership changes are complete.
Do not add timing, allocation thresholds, snapshots of incidental messages or
new security policy under the guise of tests.
## Stage 9 — Demonstrate one-invocation diagnostic reporting
**Complete.**
Add a maintained example under examples/consumers and a small behavioral test.
Let an application validator reject an unsupported backend from an imported or
overlaid source. The example handles the error, obtains root/focused inspection,
and forwards show/explain through one reporting helper also accepting Result.
It displays the checkpoint stage and retains the diagnostics and failure status.
The test verifies the rejected value and original source are inspectable, no
second load is needed, and later source/environment changes do not change the
saved report. Include an earlier-failure example showing the stage of the retained
candidate, or explaining absent inspection with the existing diagnostics. Keep
CommandKit/ckconfig and Narratio changes outside this repository and add no
consumer dependencies or copied downstream CLI infrastructure.
## Stage 10 — Update owning documents and complete validation
**Complete.**
Update declaration comments and docs/config.md for failure inspection,
checkpoint availability/stages, source evidence and comparison eligibility.
Replace the architecture policy's categorical failure/no-usable-result wording
with the selected distinction between error status and inspectable evidence.
Preserve the synchronous cleanup and successful-result contracts. Link ADR 0025
from development guidance and relevant architecture/inspection documents without
rewriting accepted ADR decisions. Update docs/internal/overview.md to describe
actual shared finalization and prefix ownership; link the maintained example
from docs/consumers/README.md and add a short README orientation link if useful.
Remove stale successful-load-only descriptions where they contradict this
feature, including Inspection and Difference documentation; keep generic Diff[T]
restricted to successful Results with its existing signature. The new view Diff
compares snapshots independent of outcome/stage. Leave prior immutable release
notes unchanged. Mark the roadmap and this plan complete only after validation.
Do not publish a release or add new release gates during this sprint.
Run `./scripts/check.sh` and reuse the successful full race run for unchanged
code, rerunning affected validation after subsequent production changes. Confirm
consumer examples and public/dependency boundaries pass. Review changed Markdown
links, stage descriptions, the checkpoint table and all nil-result error paths.
Audit the full diff for extra contracts, duplicate processing, unbounded retained
state, skipped redaction and hidden reloads. Commit validated nonempty units with
plain-English messages and report the final workspace state.
## Open Questions
None required for this scope. The public Stage representation and checkpoint
matrix above resolve the mechanical details left to implementation planning.
Private helper names and file boundaries remain implementation choices.

View File

@@ -1,38 +0,0 @@
# Feature request from Narratio for inspection after failed validation
## Consumer rationale
When `narratio config validate` reports a problem, operators use `config show`
and `config explain` to see the resolved value and where it came from. For
example, a validator can report that `storage.backend` must be `local` or `s3`,
while the operator still needs to see the rejected value and find the import or
overlay that supplied it. Today, a semantic validation failure exposes
diagnostics and source records, but the inspection commands have no resolved
view to display. [ConfigKit results and failures](../config.md#results-and-failures)
Narratio uses CommandKit’s `ckconfig` integration for configuration inspection.
Access to the failed load’s native inspection evidence would let that integration
answer these questions using the same values, provenance, and redaction rules
that apply to successful loads. Operators could investigate the exact selection
that failed in a single invocation.
## Requested public API and behavior
Preserve the failed-load contract. When an application’s `Definition.Validate`
rejects resolved settings, the load still returns a nil result and a
`*configkit.LoadError` with its diagnostics and source evidence. Make a
read-only inspection view of the resolved settings available alongside that
evidence. An optional accessor on `LoadError` would give consumers a way to
retrieve the view and distinguish its absence.
- The view describes the configuration evaluated by the validator in that same
load, including applicable defaults, imports, overlays, overrides, and
recorded resolution. Reading the view is passive and requires no reload.
- Consumers can render the whole resolved document and inspect individual paths
with their values, origins, and available history. Use the existing inspection
path and presence semantics and apply the same redaction to current and
historical values. The view carries reporting data only.
[ConfigKit inspection and metadata](../config.md#layered-metadata)
- When loading stops before a safe resolved view is available, the accessor
reports its absence. Diagnostics and any source evidence remain available
through the existing error API.

View File

@@ -1,326 +0,0 @@
# Failed-load inspection review
Reviewed commit `729724debab789ffb0e91147a134283bb2e236fa` against the
[implementation plan](implementation.md), the
[feature roadmap](failed-load-inspection.md), and
[ADR 0025](../adr/0025-inspect-failed-configuration-loads.md).
The follow-up integration audit reviewed `36a54ec788e9c912f335652ecfe244a30e90e8a3`,
whose production code is unchanged, and adds Findings 2 and 3 below.
## Finding 1 — Preserve the actual layered main checkpoint and its collection policy
**Status:** Complete. Retained the policy-aware main checkpoint, protected it
from overlay mutation, and covered overlay/underlay/version failures and invalid
main identities. Focused tests and `./scripts/check.sh` passed.
**Priority:** P2. **Affected stages:** 3 and 6; regression
coverage belongs with the stage 8 integration cases.
### Relevant code
- [executeLoadRequest](../../internal/engine/load.go) captures `mainCandidate`
before the layered loader composes the main tier, and supplies that descriptor
to failure handling after layered assembly fails.
- [assembleLayeredInput](../../internal/engine/load_request.go) composes the main
tier using the completed underlays' collection policies. Its local
`mainComposition` is not retained in the returned input on a later error.
- [sourceFailure](../../internal/engine/load_result.go), particularly its call to
`compositionForInputWithPolicy`, reconstructs the main candidate without the
lower collection policy used by the actual load.
### Circumstances and observed behavior
An underlay can declare an identity for a collection that the main tier's imports
then use during strict composition. This is established collection-policy
behavior; applications need not duplicate the declaration in the main document
or register it in Go.
The following fixture reproduces the issue through the public API:
```yaml
# Underlay supplied through LayeredOptions.Underlays
config:
sequences:
- destination: [items]
key: id
items: [{id: lower, value: base}]
---
# main.yml (loaded with Input.Imports: true)
config:
imports:
- path: a.yml
- path: b.yml
---
# a.yml
items: [{id: a, value: first}]
---
# b.yml
items: [{id: b, value: second}]
```
`LoadLayered` succeeds with these inputs and no selected overlay. With an
explicit overlay filesystem and a nonexistent selected overlay, it correctly
returns a load error. However, `LoadError.InspectSubtree(Path{})` returns false,
instead of exposing the completed main tier with its `a` and `b` records at
`InspectionStageMain`. This occurs under the normal history limits.
The load already composed that main tier successfully using the underlay's
identity rule. Failure handling instead recomposes the two imported lists with
no identity rule, encounters an ordinary overlapping-list conflict, and discards
the available checkpoint.
The same policy mismatch can manufacture a misleading checkpoint in the other
direction. With the same underlay, a single main document containing
`items: [{id: a}, {id: a}]` fails main composition with `compose.conflict`.
A document containing `items: [{other: a}]` fails with `compose.invalid`.
In both cases the fallback nevertheless returns a `main` view: reconstruction
without the identity rule succeeds even though the main composition required by
this invocation did not. The plan distinguishes completed main composition from
failures before such a checkpoint exists.
### Remediation and verification
Retain the actual completed main-tier document and its source/history/policy
evidence when layered assembly produces it, preserving ownership across later
tier and overlay operations. Pass that checkpoint to failure inspection rather
than reconstructing it under different collection rules. Where lazy main
materialization remains necessary, use the applicable policy context and report
only the processing actually completed. Keep the original diagnostics and the
existing checkpoint availability rules.
Add a focused layered-load regression covering an underlay-only YAML identity,
strict main imports, and a later overlay failure. Verify the main values, stage,
origins and history, without including underlay values as main-tier values.
Also verify that main composition rejected by the applicable identity rule does
not become a completed checkpoint merely by retrying without that rule. No new
consumer registration requirement, callback retry, source reread, or history
limit is needed.
## Finding 2 — Record consumption of descendants inside an inheritance selector
**Status:** Complete. The control producer now records every consumed selector
descendant. Public regression coverage verifies explanations, metadata history and
historical paths after decode failure, validation failure and success. Focused
inheritance tests and `./scripts/check.sh` passed.
**Priority:** P2. **Affected stages:** 3 and 8, integrating
the shared inheritance-history producer with failed-load inspection.
### Relevant code
- [observeSourcePrefix](../../internal/engine/override_context.go) reuses
`observeInheritanceEvidence` for source-stage failure snapshots.
- [observeInheritanceControl](../../internal/engine/history_inheritance.go)
records consumption only at the control's root path, then removes its complete
subtree from the scratch document.
- [selectHistory](../../internal/engine/history_select.go) selects exact and
descendant observations for a query. Its producer contract requires facts for
every affected path; it does not infer consumption of an unobserved descendant
from an ancestor control observation.
- [Explain](../../internal/engine/explain.go) and
[appendInheritanceExplanation](../../internal/engine/inheritance_explain.go)
consequently omit the consumption event for that descendant.
### Circumstances and observed behavior
Consider a typed configuration with `Count int` and
`Items []map[string]any`, loaded from:
```yaml
config:
sequences: [{destination: [items], key: id}]
count: invalid
items:
- {id: parent, width: 5}
- {id: child, extends: {id: parent}, width: 20}
```
Inheritance completes and decoding rejects `count`, so the error exposes an
`inherited` inspection. `/items/1/extends/id` remains a valid historical query.
Its explanation correctly reports `Effective.Present == false`, but its history
contains only the source contribution with `After.Present == true` and YAML
`parent`. Its metadata history likewise contains no inheritance consumption.
Querying `/items/1/extends` does include the removal event.
Expected behavior is that the nested query also includes the containing
control's consumption, with the control path as its reported operation path,
and an absent after-value. This follows the existing descendant-history and
consumed-control behavior in the
[configuration contract](../config.md#layered-metadata); it requires no new
inheritance or configuration semantics.
The same omission was reproduced with `count: 0` both on successful loading and
on semantic validation rejection. This is an existing shared-history defect,
not a newly introduced composition regression. Reusing that producer makes the
new failure views inherit it, and outcome-parity tests alone cannot detect it.
Effective configuration values are correct; the missing operation makes their
history incomplete and inconsistent between parent and descendant queries.
### Remediation and verification
Have the inheritance producer register consumption for the concrete descendant
shapes present in a mapping-valued control before removing it, reusing the
existing operation payload, attribution and reported control path. Keep query
selection and ordinary scalar-control behavior consistent; do not substitute a
synthetic decoding event for the inheritance operation.
Add focused coverage through the shared inspection interface for a consumed
selector field. Verify effective absence, the inheritance event and its
before/after presence in explanation, metadata history, and retained historical
paths. Exercise the source-stage failure case and a successful counterpart so
both use the same corrected evidence.
## Finding 3 — Clarify the diagnostic-only statement about load errors
**Status:** Complete. Clarified the distinction between ordinary diagnostic/error
reporting and explicit snapshot inspection in `docs/config.md`. Reviewed against
the public error and inspection methods and checked whitespace.
**Priority:** P3. **Affected stage:** 10.
[docs/config.md](../config.md#classification-and-output-details), around line
925, still states that metadata records, diagnostics and load errors contain
no configuration values. The earlier results-and-failures section and the new
[LoadError.InspectSubtree](../../inspection_view.go) explicitly permit error
inspection to expose non-secret configuration values and historical snapshots.
The unconditional statement leaves the owning contract inconsistent about the
boundary between diagnostic reporting and explicit configuration inspection.
Qualify the existing statement to cover diagnostic records and ordinary
`LoadError.Error()` reporting. State that explicitly requested inspection
snapshots can expose non-secret values under the existing redaction rules,
regardless of load outcome. Preserve the implemented error accessor and
inspection behavior; this calls for documentation clarification, not another
restriction on inspecting rejected configuration.
## Finding 4 — Avoid repeated scans of source observations during history construction
**Status:** Complete. Added a construction-local operation index narrowed by
path and source identity, retaining the existing complete attribution predicate.
Repeated-tier coverage verifies chronological, deduplicated history across load
outcomes. Focused history tests, `./scripts/check.sh` and `go test -race ./...`
passed.
**Priority:** P2. **Affected stages:** 3, 4 and 6 through
their shared source-history construction.
### Relevant code and complexity
[observeSourcePrefix](../../internal/engine/override_context.go) calls
[observeSourceEvidence](../../internal/engine/history_source.go). That producer
first records every source application's contributions, then processes overlay
records. For each displaced definition it calls
`sourceOriginRepresentedByOperation` in the same file (around line 194).
The helper scans every observation at the path, filtering out contributions,
definitions and operations that cannot represent the requested origin.
Let `K` source applications contribute the same scalar path and let `R` overlay
records displace that path. Every helper call must scan past the initial `K`
contribution observations before reaching any eligible operation. The displaced
definition loop alone therefore requires at least `K * R` observation visits.
With `K` ordered underlay tiers repeatedly replacing `setting`, `R = K - 1`,
giving quadratic work even though this path's retained contributions and
replacement evidence have linear size. Later operation observations also
accumulate and are rescanned. Final-tree summary construction performs further
calls to the same helper.
This is an existing shared-helper inefficiency, now also used to construct
earlier failure views. It can increase the cost of reporting a decode or
resolver failure after many tier replacements. The selected design explicitly
reuses the producer; it does not prescribe this internal lookup algorithm.
The finding does not challenge chronological history, ownership copies,
checkpoint fallback, or the expressly selected whole-snapshot diff.
### Refactoring opportunity
Maintain an incremental index of eligible after-operation evidence by concrete
path and attribution rather than searching the general observation list for
each query. Narrow candidates using layer, operation and source/location
identity, retaining `originRepresentedByChange` semantics for composite origins
and ancestor replacements. Singleton-origin scalar replacements can then use
expected constant-time indexed lookups, making the repeated-scalar fixture
linear in its history size. A separate list containing only operations would
remove irrelevant contribution scans but would still leave repeated scans of
earlier operations; address both costs.
Preserve semantic key/index shapes, subset attribution, deduplication and
chronological output. Composite-origin matching may require additional work
proportional to attribution size; no general public performance guarantee is
proposed. Existing source/history cases should verify behavior after refactoring,
with a focused repeated-tier fixture covering the affected deduplication.
No timing thresholds or benchmarks are required to establish this static finding.
## Review coverage and validation
The review followed all ten implementation stages in order:
| Stages | Reviewed outcome |
| --- | --- |
| 1 | Accepted decision separates failure status from inspection and extends existing view comparison. |
| 2 | Shared finalization classifies snapshots and attaches conservative source catalogs, passive contexts and known references. |
| 3 | Source prefixes reuse source/inheritance evidence without inventing typed defaults. Findings 1 and 2 affect main selection and inherited control history. |
| 4 | CLI and resolver failures retain their frozen entry candidates without failed partial edits. |
| 5 | Late failures retain resolved evidence, including pre-validator values and known secret references. |
| 6 | Ownership and budget fallback are implemented; Finding 1 affects preservation of the actual layered main checkpoint. |
| 7 | Root-owned API and stage conversions reuse the existing inspection view, including nil/zero and absent scopes. |
| 8 | Evidence, redaction, comparison and detachment tests protect many parity cases. Integration probes expose the shared-history omission in Finding 2; the policy-dependent fallback in Finding 1 is also missing. |
| 9 | Maintained consumer example reports failed loads from one invocation and preserves the error. |
| 10 | Public/configuration/architecture/internal documentation describes checkpoint inspection and retains existing lifecycle boundaries. Finding 3 identifies an unrevised diagnostic-boundary statement. |
`./scripts/check.sh` and `go test -race ./...` passed using Go 1.27.4 with
dependency downloads disabled, including during the follow-up integration
audit. An uncached focused run also passed for failure inspection, history,
source versions, destinations, resource contexts, resolution and the consumer
reporting example.
Disposable public-API probes outside the repository confirmed Finding 1 and
the missing selector-consumption history in Finding 2. Additional probes checked
source-stage replay for strict imports, lower-tier upsert, mapping and identified
sequence inheritance, mounted mapping inputs, and imported sequence-item inputs.
Those cases agreed on effective and historical values apart from Finding 2.
The stage-by-stage follow-up also traced error-source sanitization, frozen
resolver-entry metadata, late secret/validation failures, scoped comparison,
passive contexts, nil/zero facade behavior and the one-invocation example.
No production code or permanent tests were changed during either review. No
further actionable integration gaps were identified.
## Algorithmic follow-up audit
Reviewed `a675d3ab50b9c6c2659e22bb4b8210a6004c5dc4`, with the same production
baseline as the prior audits. Finding 4 is additional; Findings 1–3 remain open.
The analysis followed the implementation stages in order:
| Stage | Algorithmic review |
| --- | --- |
| 1 | ADR 0025 establishes checkpoint semantics, without an additional executable algorithm to assess. |
| 2 | Shared finalization retains classification and source handling; extracting it adds no input-sized nested loop. Existing selected sensitivity/comparison mechanisms were preserved. |
| 3 | Source-tree traversal and origin copying scale with visited paths and attribution payloads. Finding 4 identifies avoidable repeated history scans in the shared producer. |
| 4 | Prefix construction reuses that producer, so Finding 4 also applies here. CLI application lists and source-ID deduplication otherwise use sequential walks and maps. |
| 5 | Late failures reuse the already-frozen resolved history rather than rebuilding it. No additional suboptimal algorithm was identified. |
| 6 | The number of checkpoint candidates is fixed by the lifecycle. Retrying a fixed number of prefixes does not itself make traversal quadratic in configuration size. Retained-node counting and document lookup construction memoize node identity. Ownership cloning remains as selected in the plan. |
| 7 | Stage conversion is constant-time and scope normalization scales with path length. Whole-snapshot comparison followed by scope filtering is expressly selected and was not reconsidered. |
| 8 | Reviewed the exercised construction/query paths without introducing performance assertions or changing selected comparison and redaction algorithms. |
| 9 | The maintained example acquires views from the same retained inspection and does not reload inputs. |
| 10 | Documentation and validation add no production algorithm; prior correctness/documentation findings were preserved rather than duplicated. |
Finding 4 follows directly from loop ordering and lookup contents; no empirical
performance data was collected. Production code and tests remain unchanged.
The prior successful checks apply to the unchanged runtime; this pass validates
the report's links and whitespace. No further algorithmic findings were identified
within the reviewed feature scope.
## Remediation completion
All four findings have been addressed in separate commits with their completion
markers above. Main-tier fallback preserves the applicable composition policy;
consumed selector descendants retain their inheritance event; the owning
configuration documentation distinguishes diagnostic formatting from inspection;
and source-operation lookup no longer rescans all contributions and preceding
operations for distinct-source scalar replacements. Existing attribution,
redaction, history limits and public API signatures remain in place.
Validation includes the focused regressions, the everyday check and the full
race suite. No timing thresholds or public performance guarantees were added.