Files
narratio/docs/roadmap/remediation.md

92 lines
5.7 KiB
Markdown
Raw Normal View History

# Scriptorium algorithmic audit
Reviewed baseline: `f930ebf337d632afdc449cab86757291e14e5e37`.
Scope: the twelve stages in [implementation.md](implementation.md), focusing on
algorithmic correctness and avoidable time/space costs. This is a static audit;
no real-world performance measurements were gathered. Algorithms explicitly
selected in the plan, including sequential per-target inspection, in-memory
requirements capture, deterministic argument sorting, and existing planner reuse,
are retained as scope decisions.
## Finding 1: Avoid full-file allocation for post-capture size checks
Status: Pending consideration.
Priority: P3 — bounded memory and redundant I/O optimization; no demonstrated
incorrect result or release-blocking defect.
### Evidence and affected stages
Stages 2–3: `internal/adapters/scriptorium/subprocess.go`, particularly
`RunArtifact` at line 118, `RenderArtifact` at lines 205–212, and
`validateNonEmptyOutput` at lines 372–380.
Generation now streams stdout to an output file through the bounded result
writer. After success, `validateNonEmptyOutput` calls `fileops.ReadFileBounded`
and uses only the returned slice's length. That helper uses `io.ReadAll`, so the
adapter rereads and allocates the whole artifact solely for a nonempty/size check.
Prepared preview calls the same helper, then immediately reads the file again
for `json.Valid`. The nonempty helper predates this sprint; the newly implemented
capture/preview paths retain its allocation, and preview adds another full read.
This is an optimization opportunity in the completed feature, not a claim that
the sprint introduced the original helper or a new asymptotic regression.
### Complexity
Let B be result size and A the number of generated artifacts.
- The nonempty/size validation currently costs O(B) time and O(B) extra memory
per artifact, with cumulative additional reads of O(sum B_i) over A artifacts.
Existing limits bound each result at 64 MiB but still permit a substantial
transient allocation. Sequential execution does not retain all A buffers.
- For an already captured regular file, size/nonempty validation can use O(1)
extra memory and metadata work independent of B, plus existing path checks.
If read-through validation is desired, bounded streaming preserves O(B) time
while reducing its buffer space to O(1).
- Preview can combine its nonempty/limit checks with the one bounded read
already needed for its current JSON validation. That removes a redundant read
and allocation; preview's overall time and memory remain O(B).
- Generation and downstream content validation still process O(B) bytes. This
change would improve adapter validation space and unnecessary I/O, not make
the complete generation workflow constant-time or constant-space.
### Recommended refactoring
Separate file-property checks from content parsing. For generation, validate
the closed captured file's required properties using its metadata, preserving
existing path/type handling and the centralized size limit. Retain streaming
capture limits and propagation of write/close failures. Use a bounded streaming
check instead if preserving read-through verification is necessary.
For preview, perform one bounded read, check nonempty content, and validate that
same buffer as JSON. Preserve stage-owned payload validation, checksums, canonical
promotion, and failure behavior. No new caching, configuration setting, or
relaxation of output validation is needed.
Retain focused tests for empty, oversized, nonregular, and failed outputs, and
valid/invalid preview JSON. Review the implementation's buffering directly;
timing thresholds, allocator-count contracts, and benchmark gates are unnecessary.
## Stage-by-stage disposition
| Stage | Algorithmic assessment |
| --- | --- |
| 1 — Result capture | Streaming writes are linear in bytes; bounded accounting and failure signaling add constant work per write. No finding. |
| 2 — Generation | Finding 1 covers the avoidable post-capture whole-file allocation. Sorted argument construction follows the selected deterministic contract. |
| 3 — Preview | Finding 1 also covers the redundant read before JSON validation. |
| 4 — Requirements adapter | Capture/decoding is linear in report bytes, with linear storage for the selected in-memory report. No finding. |
| 5 — Request context | Map conversion/copying and sorted variables preserve existing behavior. No new repeated catalog scan or quadratic construction found. |
| 6 — Planning and closure | Reuses the selected planner, manifest cloning, and existing dependency ordering. Those algorithm choices were expressly retained during planning. No additional finding. |
| 7 — Inspection targets | Builds targets with map lookups and one traversal of selected bindings; storage scales with the materialized target contexts. No finding. |
| 8 — Assessment | Single passes over inputs, variables, and issues use expected constant-time map lookups. Findings/errors append amortized linearly. No finding. |
| 9 — Automatic preflight | Uses the selected projection and checker, without a separate simulation or reinspection loop. No additional finding. |
| 10 — Explicit validation | Uses shared target construction and assessment; report assembly is linear in findings. No finding. |
| 11 — Workflow verification | Test helpers introduce no production algorithm. No additional correctness issue identified. |
| 12 — Documentation | No algorithm implemented. Documentation introduces no additional algorithmic requirement relevant to this audit. |
No newly implemented quadratic-time algorithm or additional correctness defect
was identified within this scope. Finding 1 warrants consideration as a small,
behavior-preserving follow-up.