From 7ad6b718a0d1dab2b07a620dfa7d4f540a41ba40 Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Mon, 30 Nov 2026 03:55:56 +0000 Subject: [PATCH] Record algorithmic audit findings --- docs/roadmap/remediation.md | 195 +++++++++++++++++++++++++++++++++++- 1 file changed, 193 insertions(+), 2 deletions(-) diff --git a/docs/roadmap/remediation.md b/docs/roadmap/remediation.md index 3538caa..747537e 100644 --- a/docs/roadmap/remediation.md +++ b/docs/roadmap/remediation.md @@ -3,8 +3,9 @@ Reviewed Narratio commit `2ec43305da6c47709909d5cee167c7be0358b311` against all 23 stages in [implementation.md](implementation.md) and the target in [pipeline.md](pipeline.md). The catalog migration and controlled consumer -boundaries were included. This document records required remediations; it does -not implement them or change the agreed operator contract. +boundaries were included. This document records required remediations and +algorithmic refactoring opportunities for consideration. It does not implement +them or change the agreed operator contract. ## 1. Preserve available producer files after failed extraction @@ -175,6 +176,149 @@ inputs, and publication/restore with that configuration. Manifest product identities remain portable and session-relative; paths outside the permitted product directory remain invalid under the existing placement contract. +## 5. Index committed product paths once per restore plan + +**Priority:** P3 + +**Status:** For consideration + +**Stages:** 19 and 21. + +In [restore_plan.go](../../internal/app/restore_plan.go), +`buildCommittedRestoreActions` calls `restoreProductRelativePath` for each +published product. Each call scans every stage output and every per-artifact +analysis record. With P published products and A manifest output records, this +mapping costs O(P × A), quadratic when P grows with A. This is new cutover code. +Missing evidence also rebuilds the configured artifact catalog on each lookup. + +Build a source-ID-to-paths index once per restore plan, then resolve each selected +source from that index. Mapping becomes expected O(A + P), plus the paths +actually checked. Build the fallback catalog at most once, lazily. Retain both +aggregate and per-artifact evidence and the existing disagreement checks; +last-write-wins indexing would hide conflicts. Validate paths for the requested +sources as today, without adding rejection rules for unrelated records. + +Verification should preserve nested-remote/flat-local mappings, carried locked +objects, duplicate agreeing evidence, conflicting paths, and missing-source +fallbacks. The complexity finding follows directly from the nested call/scan; +no timing or production-size assumption is required. + +## 6. Index prior audio records before S3 materialization + +**Priority:** P3 + +**Status:** For consideration + +**Stage:** 17. + +In [prepare.go](../../internal/stage/prepare.go), `materializeS3AudioInputs` +scans `m.Inputs` for every selected S3 object (lines 436–444). For F objects and +R recorded inputs, prior-record selection is O(F × R), becoming O(F²) when +the manifest contains the same F audio inputs. This loop was introduced with +the simplified single-copy materialization path. It repeatedly cleans the same +recorded paths as well. + +Index audio records by cleaned destination path once, then perform expected +constant-time lookup per object: O(R + F) selection time and O(R) auxiliary +space, treating path length separately. Preserve current first-match behavior +if duplicate records are encountered, and keep all source-identity, checksum, +size, cancellation, and download verification in `MaterializeS3Audio` unchanged. +Audio-byte hashing and transfer costs remain linear in the bytes processed; +this opportunity concerns metadata lookup, not those required checks. + +Verify reuse and replacement with reordered records, unrelated input kinds, +missing records, and changed remote identities. The loop structure establishes +the complexity without a benchmark. + +## 7. Replace repeated roster ambiguity scans with indexed membership + +**Priority:** P3 + +**Status:** For consideration + +**Stage:** 4. + +In [party.go](../../internal/config/party.go), `firstPartyDomainError` and +`partyNameAmbiguous` compare each character name/alias against all earlier names +and copy the accumulated list for each character (lines 150–195 and 212–218). +N distinct names/aliases require N(N−1)/2 string comparisons. Per-character +class validation likewise takes O(K²) comparisons for K classes. String lengths +multiply these comparison costs; cumulative name-list copying can also be +quadratic. This algorithm predates the migration and remains in the newly +adopted shared-roster path; it is not a new regression. Ordinary parties are +small, so practical benefit may be modest. + +Retain sorted character traversal and the selected ambiguity rules, but use +one membership set for names/aliases and one per-character class set. With +appropriate fold keys, membership becomes expected linear in total name bytes, +plus the existing O(C log C) ordering of C character IDs. Preserve exactly +`strings.EqualFold` equivalence, including Unicode simple-fold classes; plain +`strings.ToLower` is not an equivalent key function. A small canonical +simple-fold key helper is one option. Preserve original forwarded strings. + +Verify within/across-character ambiguity, repeated player names, duplicate +classes, and Unicode pairs such as sigma/final-sigma and ASCII K/Kelvin sign. +This changes lookup machinery, not the agreed Narratio roster requirements. + +## 8. Avoid repeatedly sorting the analysis ready queue + +**Priority:** P3 + +**Status:** For consideration + +**Stages:** 16 and 21; inherited analysis scheduling used by the cutover. + +In [analyze_fingerprint.go](../../internal/stage/analyze_fingerprint.go), +`orderConfiguredAnalyzeArtifacts` sorts the entire ready slice whenever a +dependent becomes ready. A root with V−1 independent dependents causes sorts +of queues of lengths 1 through V−1. Even already sorted queues require +quadratic aggregate inspection; a general upper bound is O(V² log V), apart +from edge processing and dependency normalization. The implementation predates +this sprint; character-expanded artifact families increase its input size. +The roadmap selects deterministic dependency ordering, not this queue algorithm. + +Use the standard library's `container/heap` with a lexical min-heap. Each vertex +is inserted and removed once, yielding O(E + V log V) queue/edge work for E +dependency edges, plus any retained dependency-list normalization. It preserves +the same smallest-ready-key choice; a FIFO queue would change that ordering. +Keep unknown-dependency and cycle errors. Verify wide fan-out, chains, shared +prerequisites, and map-insertion independence against the same observable order. + +## 9. Prevent generated audio names from colliding with original names + +**Priority:** P2 + +**Status:** Pending + +**Stage:** 17; retained local-audio acquisition behavior. + +In [prepare.go](../../internal/stage/prepare.go), `localAudioDestinations` +(lines 381–401) disambiguates equal basenames independently of other basename +groups. For `/a/one.flac` and `/b/one.flac`, it generates names containing a +source-path hash. A third recording can already have exactly one of those +generated basenames. The two distinct sources then share a destination. +`materializeLocalAudioInputs` sequentially copies both to that path, so the +later recording replaces the earlier prepared copy. Original recordings remain +untouched, but prepared membership/evidence can no longer represent both. +This is an inherited correctness defect, not a newly introduced naming scheme. + +A temporary offline Go-overlay test constructed the third basename from the +first source's actual digest and confirmed duplicate destinations. No hash +collision, race, real audio, or external service was required. + +Resolve destination ownership across the complete selected audio set. Reserve +unmodified names and check generated candidates against a global occupied-name +set, using deterministic conflict resolution while retaining ordinary existing +names. At minimum, detect an unresolved conflict before copying either source; +do not permit silent replacement or ban ordinary duplicate-basename inputs. +The existing assignment is expected O(F) in F paths; global membership checks +can remain expected O(F), with O(F log F) if deterministic ordering is needed. +No new persistence or compatibility machinery is required. + +Verify a generated-versus-original collision, ordinary duplicate basenames, +unchanged noncolliding names, and materialization of distinct bytes to distinct +destinations. Check destination uniqueness before performing file writes. + ## Review coverage and verification | Implementation stages | Inspected boundaries | @@ -247,3 +391,50 @@ also passed at `016473fd16b15847f3e913670c423faa7c35720b`. Existing tests passed the temporary absolute-path probes exposed finding 4. Findings 1–3 remain pending. No fixes, compatibility shims, new product restrictions, or upstream changes were made. + +### Algorithmic follow-up + +Reviewed commit `4ee706bfb676ba2d0cf24be7aaf8472e778a6696`, in implementation +stage order. Findings 5–8 are optimization candidates for consideration; +finding 9 is a correctness remediation. Prior findings retain their statuses. +Complexities are analytical, with ordinary expected-time Go map operations; +no measured performance improvement is claimed. + +| Stage | Algorithmic review | +| --- | --- | +| 1 | Schema compilation is cached with `sync.Once`; glossary uniqueness uses per-collection sets. | +| 2 | Version checks are constant-time after manifest decoding; shared remote verification remains authoritative. | +| 3 | Canonical path construction scales with path length rather than session file count. | +| 4 | Shared validation/projection was inspected; repeated ambiguity scans are finding 7. | +| 5 | Field defaulting is bounded by the fixed interface; native ConfigKit resolution remains upstream-owned. | +| 6 | Initialization and standalone rendering scale with selected document size; independent native inspections remain intentional. | +| 7 | Catalog checking compiles its schema once and uses collection-ID sets and deterministic index traversal. | +| 8 | Input reconciliation indexes kind/destination pairs; snapshots and checksum passes scale with input bytes. | +| 9 | Four individual envelopes plus one combined projection add fixed-factor serialization/validation work selected by the plan. | +| 10 | Destination collision checks use a destination-owner map after existing deterministic ordering. | +| 11 | Completion decoding is bounded and linear in report size; command/reference construction has no all-pairs scan. | +| 12 | Required-lane mapping uses owner maps and stages one payload at a time; whole-file checks and promotion remain selected behavior. | +| 13 | Audita receives the fixed four prepared files; no new variable-size matching algorithm was introduced. | +| 14 | Required-lane/readiness matching uses sets; native provider checks and ConfigKit internals are outside this audit. | +| 15 | Latest-view operations handle two categories and validate paths; managed-target enumeration is linear in view entries. | +| 16 | Producer routing is path/byte proportional; reused analysis ordering is considered in finding 8. | +| 17 | S3 prior-record lookup is finding 6; retained local destination assignment has the correctness defect in finding 9. | +| 18 | Publication enumerates declared records and indexes source/lock/destination ownership; file verification remains byte-proportional. | +| 19 | Per-product whole-manifest scans and repeated fallback catalogs are finding 5. | +| 20 | Cleanup prefix checks scan a protection set bounded by the fixed stage inventory plus bundle markers; this is not quadratic in run file count. | +| 21 | Analysis fingerprint ordering re-sorts growing ready queues (finding 8); map-backed prepare reconciliation is already linear. | +| 22 | Workflow fixtures and controlled consumer checks protect behavior, without asserting unmeasured scalability. | +| 23 | Documentation/verification adds no runtime algorithm; the recorded opportunities preserve the selected contracts. | + +Explicit planning choices were left intact: native configuration composition, +deterministic ordering, five glossary documents, whole-file content evidence, +per-file staged promotion, and the retained content/lifecycle boundaries. +Nested traversal of distinct entries/classes/lanes is not by itself quadratic; +findings identify repeated traversal of the same growing collections. + +Existing tests passed for configuration, stages, application, artifacts, audio, +shared validation, glossaries, file operations, and previous inputs using Go +1.27.4; documentation checks and `git diff --check` also passed. The separate +temporary audio-name probe failed as expected, reproducing finding 9. No +implementation or upstream files were changed, and no live provider or +real-world performance measurements were used.