Files
narratio/docs/roadmap/audit/02-efficiency.md
Eric Rakestraw 3c00167912
All checks were successful
ci/woodpecker/push/verify Pipeline was successful
Record algorithmic efficiency audit findings
2026-11-30 17:50:25 +00:00

11 KiB
Raw Blame History

Algorithmic Efficiency Audit

Reviewed on 2026-11-30 against commit 89ea4ff1556633f217844b4a8c81a4bc2c9ffede.

Scope And Method

The review traced repository-owned loops, lookups, copying, graph traversal, error construction, and their callers across configuration, orchestration, stages, artifact resolution, storage, restore, and subprocess adapters. Complexities below follow from source-level operation counts. Hash-map bounds are expected bounds; path, key, and error-message lengths are treated as bounded unless stated otherwise. No benchmarks or production performance measurements were collected. Production code and tests remain unchanged.

The five findings concern implementation choices without an expressly selected algorithm requiring the current cost. They preserve the existing data and execution contracts.

EF-01 — P2: Local audio copying buffers the complete recording

Status: Open

Code. prepare.go, materializeLocalAudioInputs (line 367) and copyFileIfChanged (lines 635–663).

On the missing or changed destination path, copyFileIfChanged first hashes the source, then calls os.ReadFile(src) and passes the complete byte slice to store.WriteFileAtomic. This path handles prepared local .flac files as well as small configuration inputs.

Complexity. For a recording of B bytes, copying takes Θ(B) time and Θ(B) auxiliary RAM. Sequential processing limits this to the current recording, but a single large speaker file still requires a file-sized allocation. The same copy can take Θ(B) time and O(1) auxiliary RAM relative to B using a fixed-size streaming buffer. This is a space-complexity improvement, not an asymptotic time improvement.

Refactoring opportunity. Retain the existing unchanged-destination check, then use the streaming artifact-copy path. artifacts.Store.CopyInputFor is already available; its local implementation delegates to fileops.CopyFileAtomic. CopyFileAtomicWithChecksum and WriteReaderAtomicWithChecksum also provide the underlying streaming replacement mechanism. Preserve destination naming, workspace modes, atomic visibility, and the recorded checksum. File-sized buffering is not required for any of those behaviors. No new input-size cap is needed.

EF-02 — P3: Analysis rebuilds the same dependency index after each completion

Status: Open

Code. analyze_execution_state.go, acceptArtifact (lines 93–101), and analyze.go, staleUnscheduledAnalyzeDependents / staleAnalyzeDependentClosure (lines 278–319).

Every newly generated artifact, or artifact whose output identity changed, calls the invalidation helper. That helper rebuilds the entire reverse dependency map, renormalizes dependency lists, and sorts reverse adjacency lists before traversing the affected descendants. Configuration is unchanged throughout the execution.

Complexity. Let V be configured artifacts, E dependency edges, and K new/changed completions. Graph construction alone costs at least Ω(K(V+E)), with repeated dependency/adjacency sorting adding up to O(K E log V) work. On an initial execution of V independent artifacts, E=0 and K=V: this setup still costs Θ(V²), although each descendant traversal is empty. It also repeatedly allocates graph maps and edge slices.

Refactoring opportunity. Build the immutable reverse dependency index once for the analysis execution, retaining any required deterministic ordering. Pass it to success and failure invalidation. Setup then costs O(V+E), plus any one-time sorting, followed by O(reached vertices + reached edges) for each affected traversal. For independent artifacts, the invalidation work becomes O(V+K). Preserve the current eligibility rule for evaluated artifacts and the timing of dependent invalidation.

The selected complete-collection checkpoints still have their own cumulative cost. This finding removes redundant graph work; it does not claim that the whole analysis stage becomes linear.

EF-03 — P3: Previous-session metadata is repeatedly searched as a list

Status: Open

Three related lookup paths have straightforward indexing alternatives:

  1. Remote declarations. previouscache.go, Resolve (lines 145–147) calls committedPublishedArtifactBySource (lines 196–209) separately for every requirement. With R requirements and C commit declarations, the lookup work is O(RC), including quadratic cases when both grow together. Build one source-keyed index of validated published_output declarations in O(C), then resolve requirements in O(R). Existing sorting of the returned plan remains unchanged. The index must remain bound to the single pointer-selected commit.

  2. Local input records. artifact_resolver.go, ResolvePreviousSessionArtifactWithCatalog (lines 271–288), scans every manifest.Inputs entry for each previous-artifact binding. The prepared stable-input resolver in prepared_input.go, ResolvePreparedInput, also searches that collection on each call. Analysis invokes these through input-identity resolution across configured artifacts. For U lookups and I input records, record selection costs O(UI) before content verification. A phase-local kind/source index reduces selection to O(I+U), plus candidate validation. Retain candidate multiplicity and existing ambiguity/path checks; a last-write-wins map would change behavior. Continue verifying the selected files' content.

  3. Optional-absence reporting. session_state_command.go, inspectSessionState (lines 227–232), calls previousRequirementSkipped for each requirement. It linearly searches the skipped-name list. With R requirements and S skipped names, membership costs O(RS); when all are optional and absent, it performs a triangular Θ(R²) number of comparisons. Build a skipped-name set once for O(R+S) total work. Binary search is also viable while the existing sorted-result property is retained, giving O(R log S) membership work.

These indexes can remain private to each phase. They need not become a generic manifest framework or cache file contents across executions. Required/optional policy, checksum validation, and selected-commit authority remain intact.

EF-04 — P3: Restore reporting performs a full search after each install

Status: Open

Code. restore_execute.go, executeRestorePlan (lines 81–93), and restore_report.go, markDownloaded, markFailed, and findAction (lines 102–153).

The report is built from the complete restore plan. Each downloaded file then calls markDownloaded, which searches the report from the first action to find the matching local-path/remote-key pair. Failure marking uses the same search.

Complexity. For A report actions and D downloads, successful reporting costs O(DA). When every action downloads, the searches perform 1+2+...+A = Θ(A²) comparisons, even though each report entry changes once. Moving the manifest install last does not change that sum.

Refactoring opportunity. Build a private composite-key-to-report-index map when constructing the report: O(A) setup and space, then expected O(1) per update, for O(A+D) total bookkeeping. Alternatively, carry the original report index alongside each execution action, including when moving the manifest action last. Preserve public report order, serialized fields, and install ordering. Downloading, verification, and report serialization are separate costs and are not removed by this change.

EF-05 — P3: Publication-inspection errors form a quadratic-formatting tree

Status: Open

Code. session_state_command.go, inspectPublishedOutputs (lines 300–303).

For every failed publication lookup, the loop assigns resultErr = errors.Join(resultErr, err). Multiple failures, such as object metadata requests failing during a storage outage, produce a left-nested error tree. The returned error is subsequently rendered by command reporting.

Complexity. Creating each join is constant work, so aggregation itself is linear in F failures. Formatting is different: Go 1.27.4's errors.joinError.Error recursively formats the previous join and copies its growing message into the parent result. For bounded-size leaf messages, one final formatting pass takes Θ(F²) time and cumulative allocation, with Θ(F) tree depth, even though the final text is only Θ(F) bytes.

Refactoring opportunity. Append failures to []error and call errors.Join(failures...) once after the loop. Formatting then takes O(F+T), where T is the total rendered leaf-message size, with a flat aggregate. Retain per-output error details, error order, partial results, and errors.Is/errors.As visibility. The existing preflight collectors already use this approach.

Deliberately Retained Designs And Review Results

The following were treated as selected behavior rather than optimization findings:

  • the fixed canonical stage sequence, separate invalidation relation, and pure planning projection;
  • deterministic topological artifact ordering and required dependency closure;
  • complete-collection manifest checkpoints after each accepted speaker or artifact, including the detached-copy boundary;
  • manifest-authoritative checksum/content validation, publication commit ordering, and restore's manifest-last installation;
  • native ConfigKit configuration resolution and upstream-owned processing algorithms.

Nested loops over independent collections were not classified as quadratic without tracing the relevant input dimensions. Fixed-stage and fixed-glossary loops are bounded by the application model. Existing map-based publication mapping and prepared-record matching, heap-based artifact ordering, streaming WhisperX upload, and streaming remote downloads already avoid the corresponding simple scaling pitfalls.

No additional ordinary functional defect was established in this pass. The previously recorded findings remain in 01-correctness.md; they were not duplicated here.

Validation: GOTOOLCHAIN=go1.27.4 go test ./... passed. This is behavioral baseline evidence, not a performance measurement or proof that the identified costs are operational bottlenecks. The findings identify available asymptotic improvements; their practical priority remains a maintainer decision.