diff --git a/docs/roadmap/audit/02-efficiency.md b/docs/roadmap/audit/02-efficiency.md new file mode 100644 index 00000000..2236999f --- /dev/null +++ b/docs/roadmap/audit/02-efficiency.md @@ -0,0 +1,277 @@ +# Algorithmic Correctness, Efficiency, And Scalability Audit + +## Baseline And Scope + +Reviewed revision `e42031f2f6b9e8f29562a02a792dcbc59064bd7e` on 2026-11-24. +Its production code is unchanged from `3887d89b763b7040efc866d4a57eb910d8778730`; +the intervening commit records the [functional correctness audit](01-correctness.md). +This pass changed only this report. + +The review used code-graph discovery, current source and call-site inspection, +existing tests, and algorithmic cost analysis. It did not gather production +performance data, benchmark model calls, or audit the implementations of upstream +libraries. Findings describe opportunities for consideration, not approved new +contracts or an implementation plan. + +Expressly selected algorithms and boundaries were left intact: ordered step +barriers and the bounded ready-job pool; complete assessment of each candidate; +detached validator inputs; native continuation/history; typed codec handoffs; +bounded single-request semantic reconciliation; stable domain ordering and exact +identity rules; and the accepted-artifact cache policy. In particular, expensive +work required to emit or independently own the selected data is not itself a +finding. The findings below concern avoidable repeated work within those choices. + +## Architecture And Review Coverage + +Notarius remains a typed, modular Go pipeline: + +```text +input -> chunk -> ordered steps [extract per chunk -> merge -> normalize] -> output +``` + +ConfigKit owns configuration mechanics; CommandKit and its integrations own the +standard CLI surfaces; one native PromptKit engine owns model execution, +continuation, structural repair, and admission. The framework owns preparation, +assessment, ready-job coordination, generated-reference barriers, accepted-result +reuse, and output assembly. Domain modules own interpretation, normalization, +identity, validation, and contextual reference projections. Embedded assets remain +a content-only dependency. ReleaseKit owns native release mechanics. + +| Area inspected | Algorithmic assessment | +| --- | --- | +| Configuration, reference selection, resolution, and preflight | Predominantly linear walks, map lookups, and sorting for deterministic presentation. Nested loops over steps, lanes, slots, and kinds generally traverse different input dimensions, not repeated scans of one growing collection. No additional finding confirmed. | +| Source parsing and chunk planning/materialization | Document validation builds a position map; plan materialization retains resolved endpoints. Chunk copying is proportional to emitted material, including deliberately overlapping chunks. The numerical defects already in the correctness audit remain separate. | +| Pipeline scheduling, typed execution, and handoffs | Lazy ready-job dispatch avoids a goroutine per job. Generated outputs are indexed at the selected handoff boundary. Full assessment and detached ownership are deliberate costs, not optimization targets in this audit. | +| D&D extraction and citation validation | Whole-source index construction repeats per chunk; cited-text resolution scans uncited units for every record. Findings EFF-001 and EFF-002. | +| Domain normalization and identity | Exact duplicate grouping uses indexed identities. Some comparators repeatedly derive keys or recanonicalize evidence. Finding EFF-003. | +| Source-relatedness matching | Token-sequence matching uses a restart-at-each-position search. Finding EFF-004. | +| Semantic reconciliation and evidence output | Candidate/proposal membership uses maps; source windows and the evidence artifact use sorted/coalesced intervals. Request limits and fresh application to fixed originals are selected behavior and were not reconsidered. | +| Cache, diagnostics, file publication, and debug | Accepted results use direct keyed lookup; diagnostic identities are indexed and retained samples/groups are bounded. Incremental capture and atomic publication do not introduce another unbounded growing replay ledger. No additional algorithmic finding confirmed in these paths. | + +The review is risk-directed, not a proof of every possible composition. Four +efficiency opportunities and one collateral documentation inconsistency warrant +consideration. No additional executable correctness defect was confirmed; the +three findings in [01-correctness.md](01-correctness.md) still stand independently. + +## Findings + +### EFF-001 — Reuse The Full-Source Position Index Across Extraction Jobs + +**Priority:** P2 — transcript-size work is multiplied by chunk/lane count. + +**Evidence:** +[NewDocumentIndex](../../../internal/core/source/validation.go#L17) allocates and +fills a map by visiting every source unit. All ten D&D extractors construct this +full-source index per extraction invocation, directly or through +[NewSourceRefOrder](../../../internal/modules/dnd/shared/source_ref_order.go#L17). +Examples are [spells](../../../internal/modules/dnd/extract/spells/extractor.go#L119), +[item registry](../../../internal/modules/dnd/extract/itemregistry/extractor.go#L67), +and [scene descriptions](../../../internal/modules/dnd/extract/scenedescriptions/extractor.go#L81). +The construction precedes `RunProducer`, so an accepted-result cache hit does not +avoid it. Combat-gated extractors that return before construction are not counted. + +[runExtractJob](../../../internal/framework/pipeline/runner_concurrent.go#L268) +supplies the same source document to the jobs. The runner already has a run-local +lazy index for [cache decoding](../../../internal/framework/pipeline/runner_cache.go#L16), +but the extraction request does not expose that reusable snapshot. + +**Complexity:** Let `D` be the number of source units and `J` the number of +extraction invocations that build an index. Index construction alone takes +`Theta(J * D)` time and cumulative map storage allocation. With `L` applicable +lanes and `C` fixed-size chunks, `J = Theta(L * C)` and `C = Theta(D)`, giving +`Theta(L * D^2)` preprocessing despite linear total chunk content per lane. +Several concurrent jobs can also retain several identical `Theta(D)` maps. + +**Potential refactoring:** Prepare one immutable document-position snapshot per +run/source and make it available to extraction operations. Reuse it when forming +`SourceRefOrder`, retaining local construction for standalone callers that do not +receive one. `DocumentIndex` already hides its map and exposes read-only methods. +This reduces this preprocessing component to `O(D + J)`, with one shared `O(D)` +index rather than a full map per invocation. + +Preserve whole-document endpoint resolution, non-monotonic numeric IDs, +current-source cache checks, and standalone behavior. A chunk-only index would +not be an equivalent replacement. Do not remove assessment, source validation, +or required ownership copies, introduce a process-global document cache, or change +accepted-result identity to implement this improvement. + +**Follow-up verification:** Existing source-order, extractor endpoint-swap, +concurrent extraction, and current-source cache-hit tests should remain valid. +Check multiple source documents/runs and concurrent readers so an index cannot +leak across source identities. Validate the construction path by inspection or a +focused operation-count diagnostic; wall-clock production measurements are not +necessary to establish the improvement. + +### EFF-002 — Build Cited Text From Coalesced Ranges, Not A Document-Wide Bitmap + +**Priority:** P2 — sparse evidence still causes a full transcript scan per record. + +**Evidence:** +[CitationResolver.CitedText](../../../internal/modules/dnd/shared/citations.go#L26) +allocates a boolean slice of document length, marks every position of every +reference, allocates a parts slice with document-length capacity, and scans all +document units to select the marked text. Overlapping references mark the same +positions repeatedly. Even no references or a single-unit reference pay for the +full-document allocation and scan. + +The source-relatedness validators call this method for every artifact record; +see [item registry](../../../internal/modules/dnd/validate/itemregistry/source_relatedness/validator.go#L33) +and [spells](../../../internal/modules/dnd/validate/spells/source_relatedness/validator.go#L32). +This is separate from constructing the resolver's position index once per +validator invocation. + +**Complexity:** For one call, let `R` be the number of references, `S` the sum of +their inclusive span lengths counting overlap, and `B` the returned text size. +Current work is `O(D + R + S + B)`, with `Omega(D)` temporary allocation even for +sparse citations. For `A` records with one bounded citation each, resolution alone +is `Theta(A * D)`; `A = Theta(D)` makes this quadratic. Within one record, +`R` heavily overlapping document-wide ranges also cause `Theta(R * D)` marking +although the output includes each unit once. + +**Potential refactoring:** Validate and resolve endpoints through the existing +index, sort intervals by document position, coalesce their overlap/adjacency, +then join only the selected source-unit slices. After the resolver's one-time +index setup, this costs `O(R log R + U + B)` per record, where `U` is the number +of distinct cited units, and uses range/output-proportional temporary storage. +The [evidence-context builder](../../../internal/framework/evidencecontext/build.go#L17) +already demonstrates this approach. Share only a small pure interval operation +if useful; the text resolver need not construct a full evidence artifact. + +Preserve error handling, source-document order, one copy of each cited unit, +newline joining, and non-mutating inputs. Do not truncate citations, broaden the +cited context, or skip source-relatedness validation as an optimization. + +**Follow-up verification:** Retain +[citation resolver cases](../../../internal/modules/dnd/shared/citations_test.go) +for empty, invalid, disjoint, adjacent, overlapping, duplicate, and out-of-order +ranges. Add a sparse citation near the end of a large synthetic document and +non-monotonic unit IDs. Source-relatedness results should remain unchanged. + +### EFF-003 — Derive Invariant Sort Keys Once Per Normalized Record + +**Priority:** P3 — repeated citation scans and allocations inside comparators. + +**Evidence:** +[NPC occurrence ordering](../../../internal/modules/dnd/npcoccurrences/canonical.go#L29), +[location occurrence ordering](../../../internal/modules/dnd/normalize/locationoccurrences/normalizer.go#L245), +[item occurrence ordering](../../../internal/modules/dnd/itemoccurrences/itemoccurrences.go#L103), +and [enemy-event ordering](../../../internal/modules/dnd/enemyevents/enemyevents.go#L111) +call `EarliestValid` on both records for each comparison. That method scans every +reference. Their normalizers call these comparators while sorting the full merged +collection, even though a record's evidence does not change during the sort. + +Enemy events add another avoidable step: `normalizeEvent` canonicalizes evidence +once, but `Less` canonicalizes both slices again at its final tie-breaker. Thus +equal-chronology/name/kind comparisons allocate and sort already-canonical +evidence. The +[enemy invariant validator](../../../internal/modules/dnd/validate/enemyevents/invariants/validator.go#L90) +also uses that comparator after checking evidence order. The item occurrence +family already has canonical-input helpers from the previous audit; that completed +change is not being reopened here. Its remaining earliest-position scan can use +the same key preparation without changing those helpers' canonical-input premise. + +**Complexity:** For `N` records with `R` references each, deriving earliest +positions inside `O(N log N)` comparisons takes `O(N * R * log N)` work. That +factor is avoidable even when different earliest positions decide every +comparison. Enemy tie-breakers additionally repeat evidence canonicalization +and `Omega(R)` allocation per comparison; general canonicalization includes a +reference sort. Name normalization is likewise repeated when preceding keys tie. + +**Potential refactoring:** Decorate owned normalized records once with +`hasEvidence`, earliest position, and any needed normalized scalar name/kind +keys, then compare those keys. Use already-canonical evidence directly for the +remaining exact tie-breaker. The +[combat-turn normalizer](../../../internal/modules/dnd/normalize/combatturns/normalizer.go#L104) +already caches earliest positions in `normalizedRecord`. + +The earliest-key component becomes `O(N * R + N log N)` rather than +`O(N * R * log N)`, apart from the existing one-time evidence canonicalization. +Genuine lexicographic citation tie comparisons can still cost `O(R)`; this +recommendation does not claim every worst-case comparison becomes constant-time. +Keep defensive general-purpose comparison for arbitrary evidence where needed, +and use a canonical fast path only when the caller has established its premise. + +Preserve stable tie behavior, literal fallback ordering for invalid references, +nil/empty distinctions, kind order, exact deduplication, input-index diagnostics, +and all existing domain policies. This changes key preparation, not the expressly +selected canonical ordering algorithm or identity semantics. + +**Follow-up verification:** Compare normalization and invariant results on +permuted, tied, duplicate, and malformed evidence. Include many records with long +evidence lists and differing earliest positions, plus enemy records with equal +scalar keys but different evidence. Existing normalizer/model/invariant suites +are the primary behavioral protection. + +### EFF-004 — Avoid Restarting Token-Sequence Matching At Every Position + +**Priority:** P3 — low practical priority for ordinary short entity names. + +**Evidence:** +[ContainsTokenSequence](../../../internal/modules/dnd/shared/matching.go#L22) +normalizes/tokenizes both strings, then tests the entire query from each possible +start position. Most D&D source-relatedness validators use it to find contextual +names or actors in cited text. Those name fields do not impose a small fixed +token-count limit. + +**Complexity:** With `V` source tokens and `Q` query tokens, matching takes +`O(V * Q)` token comparisons in the worst case, in addition to normalization. +For example, a source consisting of repeated `a` tokens and a query containing +`Q - 1` copies of `a` followed by `b` forces a long failed match at every start. +Taking `Q` around `V / 2` makes this quadratic. Short fixed-length names +make the current matcher effectively linear, so this is a worst-case opportunity, +not evidence of a common production bottleneck. + +**Potential refactoring:** Keep `NormalizedTokens` and the chosen exact, +consecutive-token semantics. A prefix-function/KMP search over token strings +performs `O(V + Q)` token comparisons using `O(Q)` extra state. A small local +matcher is sufficient; fuzzy matching, an external search dependency, and a new +name-length restriction are unnecessary. Evaluate its small maintenance cost +after the higher-impact full-source repeated work is addressed. + +**Follow-up verification:** Retain Unicode normalization, punctuation, empty +query, exact token-boundary, and nonconsecutive-word tests. Include repeated +prefixes and near-matches; compare any replacement to a simple reference matcher +over a representative set of token sequences. + +## Collateral Documentation Correctness Finding + +### DOC-001 — Distribution Architecture Still Describes The Retired Source-Only Workflow + +**Priority:** P3 — contradictory current architecture guidance. + +[Architecture Policy / Platform And Distribution](../../policy/architecture.md#platform-and-distribution) +says that Notarius publishes no executable binaries or checksums. The adopted +[release policy](../../policy/release.md#release-model-and-completion), +[maintainer runbook](../../release.md), and +[ReleaseKit profile](../../../releasekit.json) instead select Linux/amd64 binary +and checksum delivery. This is stale wording, not an open distribution decision. + +Align the architecture summary with the implemented ReleaseKit-native release +model and link to the release policy for the publication/delivery contract. +Retain the existing Linux support and best-effort macOS development scope; +no additional targets, release gates, or distribution promises are needed. +No policy was edited during this code-audit pass. + +## Verification And Suggested Priority + +The default offline suite passed at the reviewed revision: + +```sh +GOWORK=off GOTOOLCHAIN=go1.27.0 GOPROXY=off go test -mod=readonly ./... +``` + +Most package results reused Go's cache for unchanged code. Existing tests establish +current behavioral expectations; they do not prove the complexity bounds. Those +bounds come from the inspected loops, allocations, comparator call sites, and +scaling examples above. No new tests or production implementation were added. + +A fresh `-count=1` run also passed for D&D shared helpers/resolvers; enemy, NPC, +and location occurrence normalizers; the enemy validator packages; and spell/item +registry source-relatedness validators. Report link targets were checked locally; +the staged diff passed `git diff --check`. + +Address EFF-002 and EFF-001 first if this work is selected: they remove a full +transcript dimension from repeated operations. EFF-003 is a localized follow-up; +EFF-004 is lower priority because typical queries are short. DOC-001 is an +independent small documentation correction. The separately recorded numerical +correctness defects should not be treated as fixed by any of these optimizations.