Skip to content

harden(stream): bounded streaming pipeline, deadlock + OOM safe, telemetry local-only (#100 G3) - #108

Merged
thehoff merged 4 commits into
developfrom
harden/g3-audit-100
May 20, 2026
Merged

thehoff merged 4 commits into
developfrom
harden/g3-audit-100

Conversation

@thehoff

@thehoff thehoff commented May 20, 2026

Copy link
Copy Markdown
Owner

Summary

Fixes the G3 (core streaming + telemetry) findings from audit #100. Codex-reviewed across 5 passes — final review: OOM closed, deadlock closed, clean thread join.

Findings fixed

Sev Fix
IMPORTANT Streaming back-pressure deadlock. The consumer used to drain the child channel and write to stdout/stderr inline — a wedged terminal stalled the consumer, filled the channel, back-pressured the child. Now a dedicated sink-writer thread decouples terminal I/O from the child drain.
IMPORTANT The deadlock fix's first cut used an unbounded sink channel — a wedged sink could then grow it without limit (OOM). Now a bounded sync_channel(8192) + try_send drop-on-overflow: the child drain never stalls, memory is hard-capped, and dropped bytes are accounted.
IMPORTANT Silent output truncation at FILTERED_CAP (10 MiB) — now emits [contextcrawler: output truncated at N bytes].
IMPORTANT Sink-stall drops now emit [contextcrawler: N bytes dropped — output sink stalled]; both end-of-stream markers always reach the user, never suppressed by the accumulator cap.
IMPORTANT for_each_line reads bytes with lossy-UTF8 decode (non-UTF-8 child output no longer panics/mangles).
— Telemetry: network phone-home disabled. maybe_ping() is now an unconditional no-op — no outbound telemetry. Local SQLite usage tracking is unaffected and keeps working.
NICE go/gradle ANSI escape stripping.

Review history

5 Codex passes: base review found the deadlock + silent truncation; pass 2 review caught that the unbounded sink channel traded the deadlock for an OOM; pass 3 review verified the bounded channel; pass 4 caught the drop-marker being suppressed by a full accumulator; pass 5 (this) emits it unconditionally. Final verdict: OOM closed, deadlock closed, thread join clean.

Test plan

  • cargo test --workspace — 2305 pass, 0 fail; stream module 61 pass
  • test_wedged_sink_bounds_memory_and_drops_with_marker — a condvar-gated sink proves bounded memory + no deadlock
  • test_dropped_marker_survives_full_filtered_accumulator
  • cargo build --release clean
  • Codex review ×5 — final: closed, mergeable

Part of the #100 audit.

🤖 Generated with Claude Code

thehoff and others added 4 commits May 20, 2026 18:42
Addresses the G3 group of the full-codebase audit (#100).

## toml_filter.rs — match_output after replace (finding 1)
Snapshot raw (post-ansi-strip) output before the `replace` stage and
evaluate `match_output`/`unless` guards against the snapshot. Previously
a `replace` rule that scrubbed error markers let an `unless` guard see
clean text and short-circuit a genuine failure to "ok".

## arithmetic hardening (finding 2)
- toml_filter.rs: `head_lines + tail_lines` now uses `saturating_add`.
- toml_filter.rs: reject `max_lines = 0` at config compile time.
- filter.rs: `smart_truncate` clamps `max_lines` to >= 1 to avoid the
  `max_lines - 1` underflow on a 0 CLI/config value.

## tracking.rs — DB path confinement + perms (finding 3)
Config-supplied `tracking.database_path` is canonicalised and confined
to `$HOME` (paths escaping home are rejected). `RTK_DB_PATH` stays as
the explicit test/override escape hatch. DB file (and WAL/SHM sidecars)
set to 0600 on Unix after open.

## tracking.rs — VACUUM after prune (finding 9)
`cleanup_old` runs `VACUUM` when rows were actually deleted so the DB
file does not grow unbounded.

## stream.rs — bounded channel + output cap (finding 4)
`run_streaming` now uses a bounded `sync_channel` (4096 lines) for
backpressure and caps the in-memory `filtered` accumulator at RAW_CAP.

## stream.rs — byte-line lossy read (finding 5)
New `for_each_line` reads child output as raw bytes with lossy UTF-8
conversion, replacing `BufReader::lines().map_while(Result::ok)` which
silently truncated output at the first non-UTF-8 byte. Applied to all
streaming and buffered reader paths.

## stream.rs — ANSI strip before filter match (finding 6, G6)
The streaming consumer strips ANSI from each line before `feed_line()`,
so coloured go/gradle failure markers no longer evade compaction. Raw
lines are still preserved verbatim in raw_stdout/raw_stderr.

## tee.rs — tee dir confinement + restricted write (finding 7)
`RTK_TEE_DIR`/config tee directory confined to `$HOME`. Tee files
written via `OpenOptions` with mode 0600 and `O_NOFOLLOW` (symlink-safe)
instead of `fs::write`. Size cap already present, retained.

## display_helpers.rs — slice guard (finding 8)
`week_start`/`week_end` now use `.get(5..)` with a fallback instead of
unchecked `[5..]`, which panicked on short or non-char-boundary dates.

## disable network telemetry (user decision)
`maybe_ping()` now returns unconditionally before any consent check,
marker write, or send-thread spawn — it never opens a network socket.
The function body and `main.rs` call site are kept (with `#[allow]`) so
the change is small and trivially reversible. Local SQLite tracking
(`history.db`) is unaffected and remains fully functional. The
`telemetry_cmd` erasure/opt-out path is only reachable via the explicit
`telemetry` subcommand, not a normal command invocation.

Tests added: match_output-before-replace snapshot, max_lines=0
rejection, week-stats malformed-date slice guard, maybe_ping no-op
(marker untouched), for_each_line non-UTF-8 line preservation.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ecoupling + truncation marker

IMPORTANT 1: the streaming consumer loop drained the bounded child
channel AND wrote to stdout/stderr inline. A slow/blocked terminal
stalled the consumer, filled the sync_channel(4096), and back-pressured
the reader threads and the child itself. Decouple sink writes onto a
dedicated writer thread fed by an unbounded channel: the consumer always
makes progress draining the child, terminal back-pressure is absorbed in
memory off the drain path.

IMPORTANT 2: the `filtered` accumulator hit FILTERED_CAP silently. Add
`StreamResult.truncated_filtered`; when the cap trips, set the flag and
emit a visible `[contextcrawler: output truncated at N bytes]` marker to
the sink and into `filtered` so the agent/user knows output is partial.

Tests: a slow/flooding-sink drain test (50k lines >> channel cap, must
not deadlock, child fully drains) and a FILTERED_CAP test asserting the
flag is set and the marker present.
…w) so the deadlock fix can't OOM.

The streaming deadlock fix (6f963e7) decoupled the child drain from sink
writes via a dedicated writer thread fed by an *unbounded* mpsc channel.
That removed the deadlock but introduced an OOM: if the sink wedges while
the child floods output, the unbounded channel grows without limit.

Bound the sink channel with SINK_CHANNEL_CAP (8192) and have the consumer
use try_send: a full channel drops the chunk and accounts the bytes rather
than blocking. The child drain never stalls on a wedged sink (deadlock-safe)
and memory is capped at ~SINK_CHANNEL_CAP buffered chunks (OOM-safe). When
the run finishes with dropped_bytes > 0, one summary marker is emitted to
the filtered accumulator, mirroring the truncated_filtered marker pattern.

Adds a genuinely-wedged-sink test (WedgedSink blocks on a condvar gate) that
proves: child drain completes, the writer accepts at most one chunk while
wedged (bounded memory), and the dropped-output marker is emitted.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ways emitted, never suppressed by the accumulator cap.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@thehoff
thehoff merged commit 6b738a5 into develop May 20, 2026
4 checks passed
@thehoff
thehoff deleted the harden/g3-audit-100 branch May 20, 2026 09:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant