From a44134769f820d97328822233d0e7aa514bbe7e5 Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Sat, 5 Dec 2026 17:15:50 +0000 Subject: [PATCH] Index source operations during history construction --- docs/roadmap/remediation.md | 21 +++++++- facade_source_history_tiers_test.go | 66 +++++++++++++++++++++++ internal/engine/history_source.go | 82 +++++++++++++++++++++++------ 3 files changed, 153 insertions(+), 16 deletions(-) create mode 100644 facade_source_history_tiers_test.go diff --git a/docs/roadmap/remediation.md b/docs/roadmap/remediation.md index 7c85cbb..776fa84 100644 --- a/docs/roadmap/remediation.md +++ b/docs/roadmap/remediation.md @@ -198,7 +198,13 @@ restriction on inspecting rejected configuration. ## Finding 4 — Avoid repeated scans of source observations during history construction -**Status:** Open. **Priority:** P2. **Affected stages:** 3, 4 and 6 through +**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 @@ -305,3 +311,16 @@ 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. diff --git a/facade_source_history_tiers_test.go b/facade_source_history_tiers_test.go new file mode 100644 index 0000000..1c5791b --- /dev/null +++ b/facade_source_history_tiers_test.go @@ -0,0 +1,66 @@ +package configkit_test + +import ( + "errors" + "fmt" + "testing" + + ck "go.maximumdirect.net/configkit" +) + +func TestRepeatedTierHistoryKeepsOneEventPerReplacement(t *testing.T) { + values := []int{3, 5, 8, 13, 21, 34, 55, 89} + var tiers []ck.Underlay + for _, value := range values { + tiers = append(tiers, ck.Underlay{Inputs: []ck.Input{{Source: ck.Bytes(fmt.Sprintf("tier-%d", value), []byte(fmt.Sprintf("setting: %d\n", value)))}}}) + } + for _, reject := range []bool{false, true} { + t.Run(fmt.Sprintf("reject=%t", reject), func(t *testing.T) { + definition := ck.Definition[map[string]int]{} + if reject { + definition.Validate = func(_ *map[string]int, v *ck.Validation) { v.Error(ck.Keys("setting"), "rejected") } + } + result, err := ck.LoadLayered(ck.Input{Source: ck.NoSource()}, ck.LayeredOptions[map[string]int]{Underlays: tiers, Definition: definition}) + var provider inspectionProvider + if reject { + var failure *ck.LoadError + if result != nil || !errors.As(err, &failure) { + t.Fatalf("result=%v error=%v", result, err) + } + provider = failure + } else { + if err != nil { + t.Fatal(err) + } + provider = result + } + view, ok := provider.InspectSubtree(ck.Path{}) + if !ok { + t.Fatal("inspection unavailable") + } + path := ck.Keys("setting") + explanation, found := view.Explain(path) + history := view.Metadata().History(path) + if !found || len(history) != len(tiers) || len(explanation.History) != len(tiers) { + t.Fatalf("duplicated or missing history: metadata=%#v explanation=%#v", history, explanation) + } + previous := ck.ValueSnapshot{} + for i, event := range explanation.History { + if event.Before != previous { + t.Fatalf("broken chronology at %d: %#v", i, event) + } + previous = event.After + if len(history[i].Origin.Locations) != 1 { + t.Fatalf("wrong attribution: %#v", history[i]) + } + source, found := view.Source(history[i].Origin.Locations[0].SourceID) + if !found || source.Label != fmt.Sprint("tier-", values[i]) { + t.Fatalf("wrong source at %d: %#v", i, source) + } + } + if previous != explanation.Effective { + t.Fatalf("history does not reach effective value: %#v", explanation) + } + }) + } +} diff --git a/internal/engine/history_source.go b/internal/engine/history_source.go index a0f1ea3..16bd3d5 100644 --- a/internal/engine/history_source.go +++ b/internal/engine/history_source.go @@ -53,6 +53,7 @@ func (builder *historyBuilder) observeSourceEvidence(root *document.Node, origin if len(applications) == 0 && len(records) == 0 { return } + operations := newSourceOperationIndex(builder.model) applicationsBySource := make(map[string]historyPayloadRef) applicationsByLayer := make(map[Layer][]historyPayloadRef) for index := range applications { @@ -88,7 +89,7 @@ func (builder *historyBuilder) observeSourceEvidence(root *document.Node, origin owned.hasApplicationRef = true } for displacedIndex, displaced := range record.displaced { - if sourceOriginRepresentedByOperation(builder.model, displaced.path, displaced.origin) { + if operations.contains(builder.model, displaced.path, displaced.origin) { continue } definitionPayload := payload @@ -110,12 +111,13 @@ func (builder *historyBuilder) observeSourceEvidence(root *document.Node, origin }) } for _, introduced := range record.introduced { - builder.addObservation(historyObservation{ + id := builder.addObservation(historyObservation{ path: introduced.path, phase: historyPhaseSources, payload: payload, reportedPath: record.change.Path, role: historyRoleOperation, afterPresent: true, sensitive: introduced.sensitive, attributionRef: attribution, }) + operations.add(builder.model, id) } } @@ -124,7 +126,7 @@ func (builder *historyBuilder) observeSourceEvidence(root *document.Node, origin } walkDocument(root, Path{}, func(path Path, node *document.Node) { origin, found := origins[path.String()] - if !found || origin.Layer == "" || sourceOriginRepresentedByOperation(builder.model, path, origin) { + if !found || origin.Layer == "" || operations.contains(builder.model, path, origin) { return } payload := builder.addSourceSummary(path, origin) @@ -191,22 +193,72 @@ func sourceApplicationOrigin(application historyApplication, node *document.Node return origin } -func sourceOriginRepresentedByOperation(model *historyModel, path Path, origin Origin) bool { - for _, observationID := range model.observationsByPointer[path.String()] { - observation := model.observations[observationID] - if observation.phase != historyPhaseSources || observation.role != historyRoleOperation { +// sourceOperationIndex is local to source evidence construction. It indexes only +// completed after-operation facts, narrowing attribution checks by source ID. +// General observation lists also contain all contributions at a path and grow +// with every replacement; scanning those lists per replacement is quadratic. +type sourceOperationIndex struct { + byPath map[string][]int + bySource map[sourceOperationSource][]int +} + +type sourceOperationSource struct { + pointer string + sourceID string +} + +func newSourceOperationIndex(model *historyModel) *sourceOperationIndex { + index := &sourceOperationIndex{ + byPath: make(map[string][]int), + bySource: make(map[sourceOperationSource][]int), + } + for id := range model.observations { + index.add(model, id) + } + return index +} + +func (index *sourceOperationIndex) add(model *historyModel, id int) { + if id < 0 { + return + } + observation := model.observations[id] + if observation.phase != historyPhaseSources || observation.role != historyRoleOperation || !observation.afterPresent { + return + } + attribution, ok := model.resolveAttribution(observation.attributionRef) + if !ok { + return + } + pointer := observation.path.String() + index.byPath[pointer] = append(index.byPath[pointer], id) + seen := make(map[string]struct{}, len(attribution.origin.Locations)) + for _, location := range attribution.origin.Locations { + if _, found := seen[location.SourceID]; found { continue } - if !observation.afterPresent || !sameConcreteHistoryPath(path, observation.path) { + seen[location.SourceID] = struct{}{} + key := sourceOperationSource{pointer: pointer, sourceID: location.SourceID} + index.bySource[key] = append(index.bySource[key], id) + } +} + +func (index *sourceOperationIndex) contains(model *historyModel, path Path, origin Origin) bool { + pointer := path.String() + candidates := index.byPath[pointer] + if len(origin.Locations) != 0 { + // Every representing origin must include this source, for both exact and + // ancestor replacements. The full predicate still checks all locations, + // contributor traces, layers, operations and concrete path shapes. + candidates = index.bySource[sourceOperationSource{pointer: pointer, sourceID: origin.Locations[0].SourceID}] + } + for _, id := range candidates { + observation := model.observations[id] + if !sameConcreteHistoryPath(path, observation.path) { continue } - operationOrigin, ok := model.resolveAttribution(observation.attributionRef) - if !ok { - continue - } - if originRepresentedByChange(path, origin, Change{ - Path: observation.reportedPath, Origin: operationOrigin.origin, - }) { + attribution, _ := model.resolveAttribution(observation.attributionRef) + if originRepresentedByChange(path, origin, Change{Path: observation.reportedPath, Origin: attribution.origin}) { return true } }