From 97e9d51db029dbc3db23f9d667864460834b291e Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Thu, 26 Nov 2026 03:00:08 +0000 Subject: [PATCH] Prepare item and enemy event sort keys once --- docs/internal/dnd.md | 4 + docs/roadmap/audit/catalog.md | 10 +-- docs/roadmap/implementation.md | 7 ++ .../modules/dnd/enemyevents/enemyevents.go | 57 ++++++++----- .../dnd/itemoccurrences/itemoccurrences.go | 84 ++++++++++++------- .../dnd/normalize/enemyevents/normalizer.go | 6 +- .../normalize/enemyevents/normalizer_test.go | 22 +++++ .../normalize/itemoccurrences/normalizer.go | 6 +- .../itemoccurrences/normalizer_test.go | 28 +++++++ .../enemyevents/invariants/validator.go | 9 ++ 10 files changed, 176 insertions(+), 57 deletions(-) diff --git a/docs/internal/dnd.md b/docs/internal/dnd.md index bccc4451..fdc0e2fd 100644 --- a/docs/internal/dnd.md +++ b/docs/internal/dnd.md @@ -121,6 +121,10 @@ NPC and location occurrences, combat turns, and spell casts share Each family supplies identity and source-reference eligibility and owns its output and diagnostic mapping. Spells retain the original list when no duplicate is removed; item occurrences keep their bucket-plus-exact-equality check separately. +Occurrence and enemy-event normalizers prepare chronology and other invariant +comparison keys for owned records before sorting. Enemy invariant checks use +canonical evidence only after verifying its order and uniqueness; defensive +comparators remain for unproven inputs and evidence ties remain linear. Guidance describes all currently detectable model-controlled defects using contextual names, response fields, and source ranges. It does not copy operator diff --git a/docs/roadmap/audit/catalog.md b/docs/roadmap/audit/catalog.md index 15a66ebd..3f1b1ab3 100644 --- a/docs/roadmap/audit/catalog.md +++ b/docs/roadmap/audit/catalog.md @@ -453,11 +453,11 @@ or stage interpreter is established by this finding. ### CAT-019 — Sorting Recomputes Invariant Evidence Keys -**Progress:** NPC and location occurrence normalizers prepare earliest valid -positions once per owned record; location kind rank is also prepared once. -Defensive comparators and genuine evidence tie comparisons remain. Literal -long-tie, non-monotonic, invalid-reference, duplicate, and existing validator -tests pass. Item and enemy-event work remains pending. +**Status:** Resolved. NPC, location, item, and enemy-event normalizers prepare +invariant sort keys once per owned record. Enemy invariant checks use canonical +comparisons only after evidence-order validation; defensive comparators and +genuine evidence tie comparisons remain. Literal non-monotonic, tied, invalid, +duplicate, and validator tests pass across the affected families. **Assessment:** Local algorithmic opportunity; original P3. diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index f312fc40..b2b10bb8 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -844,6 +844,13 @@ Comment canonical fast-path premises. ## Stage 31 — Prepare Item And Enemy Sort Keys Once +**Completed.** Item and enemy-event normalizers prepare chronology and scalar +comparison keys once per owned canonical record. Enemy invariant checks use the +canonical path only for evidence that passed order/uniqueness checks; defensive +comparators and item exact-equality buckets remain. Literal tie, invalid evidence, +identity/dedup, and existing nil/empty and kind-order tests pass with the +specified family, normalizer, and validator suites. + **Coverage:** CAT-019 completion. **Prerequisites:** Stage 30. Apply local key preparation to item/enemy records. Remove enemy recanonicalization diff --git a/internal/modules/dnd/enemyevents/enemyevents.go b/internal/modules/dnd/enemyevents/enemyevents.go index ba7f7eb0..e5ffad0d 100644 --- a/internal/modules/dnd/enemyevents/enemyevents.go +++ b/internal/modules/dnd/enemyevents/enemyevents.go @@ -109,33 +109,52 @@ func canonicalSourceRefsEqual(left, right []source.SourceRef) bool { // remain comparable through SourceRefOrder's literal fallback so malformed // candidates can still be sorted for later validation. func Less(order shared.SourceRefOrder, left, right dnd.EnemyEvent) bool { - leftPosition, leftHasEvidence := order.EarliestValid(left.SourceRefs) - rightPosition, rightHasEvidence := order.EarliestValid(right.SourceRefs) - if leftHasEvidence != rightHasEvidence { - return leftHasEvidence + left.SourceRefs = order.Canonicalize(left.SourceRefs) + right.SourceRefs = order.Canonicalize(right.SourceRefs) + return CanonicalLessPrepared(order, left, right, PrepareCanonicalOrder(order, left), PrepareCanonicalOrder(order, right)) +} + +// CanonicalOrderKey holds invariant comparisons for an owned event. +type CanonicalOrderKey struct { + earliest int + hasEvidence bool + nameComparison, nameDisplay string + kindRank int + kindKnown bool +} + +// PrepareCanonicalOrder requires evidence already in canonical order. +func PrepareCanonicalOrder(order shared.SourceRefOrder, event dnd.EnemyEvent) CanonicalOrderKey { + earliest, hasEvidence := order.EarliestValid(event.SourceRefs) + rank, known := KindRank(event.Kind) + return CanonicalOrderKey{earliest: earliest, hasEvidence: hasEvidence, nameComparison: ComparisonKey(event.Name), nameDisplay: NormalizeDisplay(event.Name), kindRank: rank, kindKnown: known} +} + +// CanonicalLessPrepared requires keys prepared from these unchanged canonical +// events. Less is the defensive comparator for unproven evidence order. +func CanonicalLessPrepared(order shared.SourceRefOrder, left, right dnd.EnemyEvent, leftKey, rightKey CanonicalOrderKey) bool { + if leftKey.hasEvidence != rightKey.hasEvidence { + return leftKey.hasEvidence } - if leftHasEvidence && leftPosition != rightPosition { - return leftPosition < rightPosition + if leftKey.hasEvidence && leftKey.earliest != rightKey.earliest { + return leftKey.earliest < rightKey.earliest } - if leftKey, rightKey := ComparisonKey(left.Name), ComparisonKey(right.Name); leftKey != rightKey { - return leftKey < rightKey + if leftKey.nameComparison != rightKey.nameComparison { + return leftKey.nameComparison < rightKey.nameComparison } - if leftName, rightName := NormalizeDisplay(left.Name), NormalizeDisplay(right.Name); leftName != rightName { - return leftName < rightName + if leftKey.nameDisplay != rightKey.nameDisplay { + return leftKey.nameDisplay < rightKey.nameDisplay } - if leftRank, leftKnown := KindRank(left.Kind); leftKnown { - if rightRank, rightKnown := KindRank(right.Kind); rightKnown && leftRank != rightRank { - return leftRank < rightRank - } else if !rightKnown { - return true - } - } else if _, rightKnown := KindRank(right.Kind); rightKnown { - return false + if leftKey.kindKnown != rightKey.kindKnown { + return leftKey.kindKnown + } + if leftKey.kindKnown && leftKey.kindRank != rightKey.kindRank { + return leftKey.kindRank < rightKey.kindRank } if left.Kind != right.Kind { return left.Kind < right.Kind } - return sourceRefsLess(order, order.Canonicalize(left.SourceRefs), order.Canonicalize(right.SourceRefs)) + return sourceRefsLess(order, left.SourceRefs, right.SourceRefs) } func sourceRefsLess(order shared.SourceRefOrder, left, right []source.SourceRef) bool { diff --git a/internal/modules/dnd/itemoccurrences/itemoccurrences.go b/internal/modules/dnd/itemoccurrences/itemoccurrences.go index 342c2082..5f7c33a6 100644 --- a/internal/modules/dnd/itemoccurrences/itemoccurrences.go +++ b/internal/modules/dnd/itemoccurrences/itemoccurrences.go @@ -101,30 +101,57 @@ func Less(order shared.SourceRefOrder, left, right dnd.ItemOccurrence) bool { // CanonicalLess defines the canonical occurrence order without modifying or // canonicalizing source references. Callers must provide canonical evidence. func CanonicalLess(order shared.SourceRefOrder, left, right dnd.ItemOccurrence) bool { - leftPosition, leftHasEvidence := order.EarliestValid(left.SourceRefs) - rightPosition, rightHasEvidence := order.EarliestValid(right.SourceRefs) - if leftHasEvidence != rightHasEvidence { - return leftHasEvidence + return CanonicalLessPrepared(order, left, right, PrepareCanonicalOrder(order, left), PrepareCanonicalOrder(order, right)) +} + +type holderOrderKey struct { + present bool + comparison, display string +} + +// CanonicalOrderKey holds invariant comparisons for an owned occurrence. +type CanonicalOrderKey struct { + earliest int + hasEvidence bool + nameComparison, nameDisplay string + from, to holderOrderKey +} + +// PrepareCanonicalOrder requires source references already in canonical order. +func PrepareCanonicalOrder(order shared.SourceRefOrder, value dnd.ItemOccurrence) CanonicalOrderKey { + earliest, hasEvidence := order.EarliestValid(value.SourceRefs) + holder := func(value string) holderOrderKey { + display := DisplayValue(value) + return holderOrderKey{present: display != "", comparison: ComparisonKey(display), display: display} } - if leftHasEvidence && leftPosition != rightPosition { - return leftPosition < rightPosition + return CanonicalOrderKey{earliest: earliest, hasEvidence: hasEvidence, nameComparison: ComparisonKey(value.Name), nameDisplay: DisplayValue(value.Name), from: holder(value.From), to: holder(value.To)} +} + +// CanonicalLessPrepared compares values with keys prepared from those same +// canonical, unchanged records; arbitrary input should use Less instead. +func CanonicalLessPrepared(order shared.SourceRefOrder, left, right dnd.ItemOccurrence, leftKey, rightKey CanonicalOrderKey) bool { + if leftKey.hasEvidence != rightKey.hasEvidence { + return leftKey.hasEvidence + } + if leftKey.hasEvidence && leftKey.earliest != rightKey.earliest { + return leftKey.earliest < rightKey.earliest } if left.ItemID != right.ItemID { return left.ItemID < right.ItemID } - if leftKey, rightKey := ComparisonKey(left.Name), ComparisonKey(right.Name); leftKey != rightKey { - return leftKey < rightKey + if leftKey.nameComparison != rightKey.nameComparison { + return leftKey.nameComparison < rightKey.nameComparison } - if leftName, rightName := DisplayValue(left.Name), DisplayValue(right.Name); leftName != rightName { - return leftName < rightName + if leftKey.nameDisplay != rightKey.nameDisplay { + return leftKey.nameDisplay < rightKey.nameDisplay } if left.Kind != right.Kind { return left.Kind < right.Kind } - if less, decided := optionalStringLess(left.From, right.From); decided { + if less, decided := holderKeyLess(leftKey.from, rightKey.from); decided { return less } - if less, decided := optionalStringLess(left.To, right.To); decided { + if less, decided := holderKeyLess(leftKey.to, rightKey.to); decided { return less } if less, decided := optionalQuantityLess(left.Quantity, right.Quantity); decided { @@ -133,6 +160,22 @@ func CanonicalLess(order shared.SourceRefOrder, left, right dnd.ItemOccurrence) return sourceRefsLess(order, left.SourceRefs, right.SourceRefs) } +func holderKeyLess(left, right holderOrderKey) (bool, bool) { + if left.present != right.present { + return !left.present, true + } + if !left.present { + return false, false + } + if left.comparison != right.comparison { + return left.comparison < right.comparison, true + } + if left.display != right.display { + return left.display < right.display, true + } + return false, false +} + // ExactEqual reports whether occurrences are exact duplicates after their display // fields and evidence have been canonicalized for the supplied source order. func ExactEqual(order shared.SourceRefOrder, left, right dnd.ItemOccurrence) bool { @@ -197,23 +240,6 @@ func writeKeySourceRefs(builder *strings.Builder, refs []source.SourceRef) { } } -func optionalStringLess(left, right string) (bool, bool) { - leftPresent, rightPresent := HolderPresent(left), HolderPresent(right) - if leftPresent != rightPresent { - return !leftPresent, true - } - if !leftPresent { - return false, false - } - if leftKey, rightKey := ComparisonKey(left), ComparisonKey(right); leftKey != rightKey { - return leftKey < rightKey, true - } - if leftValue, rightValue := DisplayValue(left), DisplayValue(right); leftValue != rightValue { - return leftValue < rightValue, true - } - return false, false -} - func optionalQuantityLess(left, right *int) (bool, bool) { if (left == nil) != (right == nil) { return left == nil, true diff --git a/internal/modules/dnd/normalize/enemyevents/normalizer.go b/internal/modules/dnd/normalize/enemyevents/normalizer.go index febfa9bb..cfcaa3cb 100644 --- a/internal/modules/dnd/normalize/enemyevents/normalizer.go +++ b/internal/modules/dnd/normalize/enemyevents/normalizer.go @@ -93,6 +93,7 @@ type normalizedRecord struct { event dnd.EnemyEvent identity string inputIndex int + orderKey enemyeventmodel.CanonicalOrderKey } type nameCanonicalization struct { @@ -108,7 +109,7 @@ func normalizeList(input dnd.EnemyEventList, order shared.SourceRefOrder, regist findings := make([]diagnostics.Finding, 0) for index, inputEvent := range input.Events { event, nameChange, refsChanged := normalizeEvent(inputEvent, order, registry) - records[index] = normalizedRecord{event: event, identity: enemyeventmodel.CanonicalIdentity(event), inputIndex: index} + records[index] = normalizedRecord{event: event, identity: enemyeventmodel.CanonicalIdentity(event), inputIndex: index, orderKey: enemyeventmodel.PrepareCanonicalOrder(order, event)} if nameChange != nil { findings = append(findings, diagnostics.Finding{ Scope: eventScope(index), @@ -128,7 +129,8 @@ func normalizeList(input dnd.EnemyEventList, order shared.SourceRefOrder, regist } sort.SliceStable(records, func(left, right int) bool { - return enemyeventmodel.Less(order, records[left].event, records[right].event) + l, r := records[left], records[right] + return enemyeventmodel.CanonicalLessPrepared(order, l.event, r.event, l.orderKey, r.orderKey) }) for position, record := range records { if position == record.inputIndex { diff --git a/internal/modules/dnd/normalize/enemyevents/normalizer_test.go b/internal/modules/dnd/normalize/enemyevents/normalizer_test.go index c18ea5bc..f5fa15fc 100644 --- a/internal/modules/dnd/normalize/enemyevents/normalizer_test.go +++ b/internal/modules/dnd/normalize/enemyevents/normalizer_test.go @@ -81,6 +81,28 @@ func TestNormalizeUsesExplicitKindOrderAndPreservesDistinctObservations(t *testi } } +func TestNormalizeOrdersTiedEnemyEvidenceWithoutMergingIt(t *testing.T) { + doc := &source.SourceDocument{ID: "session", Units: []source.SourceUnit{{ID: 50}, {ID: 10}, {ID: 90}}} + ref := func(id int) source.SourceRef { + return source.SourceRef{SourceID: doc.ID, StartUnitID: id, EndUnitID: id} + } + event := func(refs ...source.SourceRef) dnd.EnemyEvent { + return dnd.EnemyEvent{Name: "Ashfang", Kind: dnd.EnemyEventKindEngaged, SourceRefs: refs} + } + earlier, later, invalid := event(ref(50), ref(10)), event(ref(50), ref(90)), event(ref(999)) + input := dnd.EnemyEventList{Events: []dnd.EnemyEvent{later, invalid, earlier, later}} + result, err := runNormalize(newNormalizer(t, npcReferences(t)), context.Background(), normalizeRequest(doc, input, contracts.ReferenceSet{})) + if err != nil { + t.Fatal(err) + } + if want := []dnd.EnemyEvent{earlier, later, invalid}; !reflect.DeepEqual(result.Value.Events, want) { + t.Fatalf("events = %#v, want %#v", result.Value.Events, want) + } + if !hasDiagnostic(result.Diagnostics, ReasonCodeEventsReordered) || !hasDiagnostic(result.Diagnostics, ReasonCodeDuplicateCollapsed) { + t.Fatalf("diagnostics = %#v", result.Diagnostics) + } +} + func TestNormalizePreservesDistinctEvidenceWhenEncodedKeysCoincide(t *testing.T) { invalidSourceID := string([]byte{'s', 0xff}) replacementSourceID := "s\uFFFD" diff --git a/internal/modules/dnd/normalize/itemoccurrences/normalizer.go b/internal/modules/dnd/normalize/itemoccurrences/normalizer.go index 7a713e44..6da972f8 100644 --- a/internal/modules/dnd/normalize/itemoccurrences/normalizer.go +++ b/internal/modules/dnd/normalize/itemoccurrences/normalizer.go @@ -92,6 +92,7 @@ type normalizedRecord struct { occurrence dnd.ItemOccurrence identity string inputIndex int + orderKey itemoccurrencemodel.CanonicalOrderKey } func normalizeList(input dnd.ItemOccurrenceList, index source.DocumentIndex, order shared.SourceRefOrder, registry *itemregistry.Registry) (dnd.ItemOccurrenceList, []diagnostics.Finding) { @@ -103,7 +104,7 @@ func normalizeList(input dnd.ItemOccurrenceList, index source.DocumentIndex, ord findings := make([]diagnostics.Finding, 0) for index, inputOccurrence := range input.Occurrences { occurrence, changedFields, found, refsChanged := normalizeOccurrence(inputOccurrence, order, registry) - records[index] = normalizedRecord{occurrence: occurrence, identity: itemoccurrencemodel.CanonicalExactIdentity(occurrence), inputIndex: index} + records[index] = normalizedRecord{occurrence: occurrence, identity: itemoccurrencemodel.CanonicalExactIdentity(occurrence), inputIndex: index, orderKey: itemoccurrencemodel.PrepareCanonicalOrder(order, occurrence)} if len(changedFields) != 0 { findings = append(findings, diagnostics.Finding{ Scope: occurrenceScope(index), @@ -131,7 +132,8 @@ func normalizeList(input dnd.ItemOccurrenceList, index source.DocumentIndex, ord } sort.SliceStable(records, func(left, right int) bool { - return itemoccurrencemodel.CanonicalLess(order, records[left].occurrence, records[right].occurrence) + l, r := records[left], records[right] + return itemoccurrencemodel.CanonicalLessPrepared(order, l.occurrence, r.occurrence, l.orderKey, r.orderKey) }) for position, record := range records { if position == record.inputIndex { diff --git a/internal/modules/dnd/normalize/itemoccurrences/normalizer_test.go b/internal/modules/dnd/normalize/itemoccurrences/normalizer_test.go index 2005300b..67748409 100644 --- a/internal/modules/dnd/normalize/itemoccurrences/normalizer_test.go +++ b/internal/modules/dnd/normalize/itemoccurrences/normalizer_test.go @@ -2,6 +2,7 @@ package itemoccurrences import ( "context" + "reflect" "testing" "gitea.maximumdirect.net/eric/notarius/internal/core/source" @@ -63,6 +64,33 @@ func TestNormalizeRequiresRegistryAndRegistersSlot(t *testing.T) { } } +func TestNormalizeOrdersTiedItemEvidenceWithoutMergingIt(t *testing.T) { + doc := &source.SourceDocument{ID: "session", Units: []source.SourceUnit{{ID: 50}, {ID: 10}, {ID: 90}}} + ref := func(id int) source.SourceRef { + return source.SourceRef{SourceID: doc.ID, StartUnitID: id, EndUnitID: id} + } + item := func(refs ...source.SourceRef) dnd.ItemOccurrence { + return dnd.ItemOccurrence{ItemID: itemidentity.DeriveID("Torch"), Name: "Torch", Kind: dnd.ItemOccurrenceKindDiscovered, SourceRefs: refs} + } + earlier, later, invalid := item(ref(50), ref(10)), item(ref(50), ref(90)), item(ref(999)) + input := dnd.ItemOccurrenceList{Occurrences: []dnd.ItemOccurrence{later, invalid, earlier, later, invalid}} + references := registryReferences(t) + normalizer, err := New(Options{}, references) + if err != nil { + t.Fatal(err) + } + result, err := runNormalize(normalizer, context.Background(), contracts.NormalizeInput[dnd.ItemOccurrenceList]{Source: doc, References: references, MergeOutput: contracts.MergeArtifact[dnd.ItemOccurrenceList]{Value: input}}) + if err != nil { + t.Fatal(err) + } + if want := []dnd.ItemOccurrence{earlier, later, invalid, invalid}; !reflect.DeepEqual(result.Value.Occurrences, want) { + t.Fatalf("occurrences = %#v, want %#v", result.Value.Occurrences, want) + } + if !hasDiagnostic(result.Diagnostics, ReasonCodeOccurrencesReordered, contracts.DiagnosticDispositionObservation) || !hasDiagnostic(result.Diagnostics, ReasonCodeDuplicateCollapsed, contracts.DiagnosticDispositionObservation) { + t.Fatalf("diagnostics = %#v", result.Diagnostics) + } +} + func hasDiagnostic(diagnostics []contracts.ProducerDiagnostic, reason string, disposition contracts.DiagnosticDisposition) bool { for _, diagnostic := range diagnostics { if diagnostic.ReasonCode == reason && diagnostic.Disposition == disposition { diff --git a/internal/modules/dnd/validate/enemyevents/invariants/validator.go b/internal/modules/dnd/validate/enemyevents/invariants/validator.go index 250719e8..1946bdd1 100644 --- a/internal/modules/dnd/validate/enemyevents/invariants/validator.go +++ b/internal/modules/dnd/validate/enemyevents/invariants/validator.go @@ -90,6 +90,7 @@ func allSourceRefsValid(index source.DocumentIndex, value dnd.EnemyEventList) bo func issuesFor(order shared.SourceRefOrder, value dnd.EnemyEventList, registry *npcregistry.Registry) []string { issues := make([]string, 0) canonicalEvidence := make([]bool, len(value.Events)) + orderKeys := make([]enemyeventmodel.CanonicalOrderKey, len(value.Events)) for eventIndex, event := range value.Events { prefix := fmt.Sprintf("events[%d]", eventIndex) canonicalEvidence[eventIndex] = true @@ -110,8 +111,16 @@ func issuesFor(order shared.SourceRefOrder, value dnd.EnemyEventList, registry * canonicalEvidence[eventIndex] = false } } + if canonicalEvidence[eventIndex] { + orderKeys[eventIndex] = enemyeventmodel.PrepareCanonicalOrder(order, event) + } } if !sort.SliceIsSorted(value.Events, func(left, right int) bool { + // Only use the fast path when both evidence sequences passed the + // canonical-order and duplicate checks above. + if canonicalEvidence[left] && canonicalEvidence[right] { + return enemyeventmodel.CanonicalLessPrepared(order, value.Events[left], value.Events[right], orderKeys[left], orderKeys[right]) + } return enemyeventmodel.Less(order, value.Events[left], value.Events[right]) }) { issues = append(issues, "events are not in canonical order")