Skip to content

feat(trackers,node): StorageTracker for node/bun/deno (TR8, part 2) - #88

Merged
krassx merged 2 commits into
mainfrom
feat/node-storage-tracker
Oct 20, 2026
Merged

krassx merged 2 commits into
mainfrom
feat/node-storage-tracker

Conversation

@krassx

@krassx krassx commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

Summary

  • New per-process `StorageTracker` in `@bugsee/trackers/node` (`storageTrackerFor(env, onError?)`, `resetStorageTracker`) owning the statfs read of the opt-in `disk_mem_free`/`disk_mem_total` traces (design §15.2, TR8 part 2). One stage, `disk` `{freeBytes, totalBytes}`.
  • Polls on its own unref'd 5 s timer only while it has a listener; failures reported once per failure streak; unreadable/unsane readings omitted, never zeroed; stale in-flight reads guarded by generation; no overlapping reads.
  • Data dir is a per-launch seam via `rebind` (latest launch wins, merge-not-drop, `statfs: null` is a defined seam); a changed seam while listening re-reads immediately and does not leak the old path's reading/streak.
  • Retention rule (stated + tested): only merged seams survive the last unsubscribe; the last reading does not.
  • `@bugsee/node`'s `disk-space-producer.ts` is now composition only (subscribes to the tracker stage, converts to integer MB, `hold:false`); the old polling code and tests are deleted/rewritten. Trace names, wire shapes and the opt-in behaviour are unchanged. `@bugsee/node` re-exports `storageTrackerFor`/`resetStorageTracker`/`StorageTracker` (bun/deno re-export it).
  • Docs: PROGRESS.md TR8 part 2 entry, trackers README + package description, changeset (minor: node, bun, deno, trackers).

Test plan

  • Tracker unit tests (37) with per-entity mutator loop (34 mutants, all killed or shown equivalent), trackers package coverage gate
  • Producer tests rewritten over the tracker + mutation checks
  • Launch-level test wraps `storageTrackerFor`: opt-in on goes through it (mutating to `new StorageTracker` fails); no tracker requested when off / no data dir
  • `pnpm ci:local` passes (lint, typecheck incl. portable, cycles, coverage gates, harness)

🤖 Generated with Claude Code

Absorbs the statfs polling of @bugsee/node's disk-space producer into a per-process
StorageTracker in @bugsee/trackers/node. The producer is now composition only.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
@claude

claude Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Claude finished @krassx's task in 43s —— View job


Review of PR #88: StorageTracker for node/bun/deno (TR8, part 2)

I found no real bugs. I did not post any inline comments.

I read storage-tracker.ts in full, along with disk-space-producer.ts, the launch.ts call site, InterceptorBase, the tracker registry, and the launch-level test diff. I did not run the tests or the type checker, because dependencies aren't installed in this job. Treat the points below as code reading only.

What I checked, and why I think it holds

  • Stale reads and timers. #gen is bumped in both #end() and #begin(). The timer callback and both .then branches check it, so a read from an older run can't emit, report or flip #inFlight. A timer whose clearInterval threw also can't read.
  • Overlapping reads. #inFlight is cleared on teardown. A new run can read immediately even if the old promise never settles, and the old promise is ignored when it does.
  • Rebind while listening. #end() runs against the old seams and #begin() against the merged ones. The clear goes to the scheduler that armed the timer, not the new one. #last and #failing are reset, so the old path's reading and failure streak don't carry over. An unchanged relaunch restarts nothing.
  • Omit, never zero. bavail of 0 passes (a full disk reports a real 0). A non-positive bsize or blocks, a non-finite value, or an overflowing product emits nothing and clears #last.
  • Throwing code. A synchronous throw from statfs becomes a rejection. A throwing onError is swallowed on both paths. setInterval throwing leaves the tracker inert and reports the error. Emitter listener errors are caught at emitter.ts:103, so emit inside the .then can't produce an unhandled rejection.
  • Producer behaviour. hold:false means a failing statfs doesn't leave a stale value being re-recorded. Trace names and the integer-MB conversion are unchanged. The launch only builds the producer when the opt-in is on and a data dir exists, and the new launch tests cover both branches.
  • Portability. The import * as fsp namespace import with a statfs lookup degrades gracefully on Node < 18.15. The default scheduler unrefs its timer.

Non-blocking observations (not findings)

  • Hung statfs: while a statfs call never settles (for example a dead NFS mount), #inFlight stays true, so there are no further reads and no onError. The disk traces just go quiet until the call settles. This is the "no overlapping reads" rule working as designed, and the hold:false choice means no stale numbers get recorded. A read timeout that reports once could be a later improvement.
  • Merge-not-drop seams: a later launch that omits scheduler or statfs keeps the earlier launch's value. That is documented and tested. It does mean a launch-1 test scheduler persists into launch 2 unless resetStorageTracker() is called, which the launch.test.ts afterEach already does.

Overall risk: Low

Merge recommendation: Approve once CI is green (pnpm ci:local is claimed in the PR body; I didn't verify it).

Most important issues to fix: None.

Positives

  • The retention rule is written down and tested.
  • The generation guarding is applied consistently.
  • The producer shrinks to composition only, which removes duplicated polling code.
  • The launch-level test wraps the real accessor with a pass-through spy, so it proves the wiring without replacing behaviour.
    · branch feat/node-storage-tracker

@coderabbitai

coderabbitai Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: eab9310c-e222-4288-b811-1d4e2507371c
📥 Commits

Reviewing files that changed from the base of the PR and between 54becb2 and 6827d85.

📒 Files selected for processing: 8
  • .changeset/node-storage-tracker.md
  • docs/PROGRESS.md
  • packages/node/src/disk-space-producer.test.ts
  • packages/node/src/launch.test.ts
  • packages/node/src/launch.ts
  • packages/trackers/README.md
  • packages/trackers/src/node/storage-tracker.test.ts
  • packages/trackers/src/node/storage-tracker.ts
🚧 Files skipped from review as they are similar to previous changes: 2
  • packages/trackers/README.md
  • .changeset/node-storage-tracker.md

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.

📝 Summary

Summary by CodeRabbit

  • New Features

    • Added opt-in storage tracking for Node, Bun, and Deno, reporting disk free and total space.
    • Monitoring supports immediate and periodic polling, shared tracking per data directory, failure handling, and cleanup.
    • Exposed storage tracker APIs through the Node and shared tracker entry points.
    • Added support for updated data-directory and error-handling settings.
    • Disk monitoring is skipped when a custom system metrics sampler is configured.
  • Documentation

    • Documented storage tracking behavior, lifecycle, outputs, and configuration.

The change adds StorageTracker to the Node trackers package. It samples filesystem statistics while listeners exist and a data directory is configured. Trackers are shared by resolved data directory. The Node disk-space producer subscribes to the tracker and maps readings to free and total disk-space values. Node launch handling skips disk capture when a custom system metrics sampler is provided. The tracker APIs are exported through the trackers and Node entry points.

Sequence Diagram(s)

sequenceDiagram
  participant NodeLaunch
  participant DiskSpaceProducer
  participant StorageTracker
  participant fs.promises.statfs
  NodeLaunch->>StorageTracker: Obtain tracker for data directory
  NodeLaunch->>DiskSpaceProducer: Create disk-space producer
  DiskSpaceProducer->>StorageTracker: Subscribe to disk stage
  StorageTracker->>fs.promises.statfs: Read data directory
  fs.promises.statfs-->>StorageTracker: Return filesystem statistics
  StorageTracker-->>DiskSpaceProducer: Emit disk reading in bytes
  DiskSpaceProducer-->>NodeLaunch: Emit free and total values in binary MB
Loading

Priority: ⬇️ Low

Change: Feature

Merge Risk: ⚪ Minimal · up to 6827d

Disk-space monitoring in the Node SDK now uses a shared storage tracker for each data directory instead of polling separately in each producer. Trace names, value shapes, and the opt-in behavior are unchanged. No concrete defects were found in the polling lifecycle, error reporting, or launch wiring, so the change looks ready to merge after normal checks.

Security architecture risk: 🔵 Low · up to 6827d

The normal launch path preserves opt-in, read-only disk sampling and existing metric outputs. One cleanup exception remains: explicitly starting the public tracker can leave it polling after reset, outside the shared registry’s ownership. No new security attack path was established in the inspected integration.

Retained concerns

  • Low · reliability · observed: Reset does not fully release an explicitly started tracker. After storageTrackerFor(...).start(), resetStorageTracker(dir) evicts the instance but only removes its listeners. The inherited started flag keeps it active, so its timer and reads can survive and a later lookup can create a second polling instance for the same directory. This breaks teardown ownership and failure containment. It requires explicit public start() use; the normal disk producer’s subscribe/unsubscribe path does not exhibit it.
Security review details

Security Blast Radius

  • observed — The shared mutable scope is one registry instance per resolved directory, unless a caller supplies an explicit object key. Ordinary lookups for different directories obtain separate trackers; callers using the same directory share mutable seams and error routing. Directory identity is the sharing key, not an authorization or tenant-isolation control.

Security Findings and Attack Paths

  • inferred — No introduced attacker-to-sensitive-sink path was established in the inspected disk flow. The traced configuration comes from launch options, and the operation remains a capacity read followed by existing metric emission. The specifically routed test range contains fixtures and assertions, not a request-facing entrypoint. External use of the new public controls was not established by this review.

Trust Boundaries and Controls

  • observed — The public tracker accepts caller-provided paths, read functions, schedulers and error handlers without adding a sandbox boundary. In the integrated launch path, default-root verification still precedes use, while explicit directories remain the caller’s security decision. Tracker generations reject stale completions, invalid readings are omitted, and error-handler exceptions are contained.

Resilience and Maintainability Implications

  • observed — The explicit-start reset exception is an ownership and cleanup defect, not a demonstrated privilege escalation or data disclosure. Normal producer stop removes its subscription, and the inspected reset test verifies listener-driven teardown without invoking the tracker’s inherited start() mode.
Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 10 functions across 10 files. (3 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly identifies the addition of StorageTracker support for Node, Bun, and Deno, which is the main change.
Description check Passed The description accurately summarizes the StorageTracker behavior, producer integration, exports, tests, and documentation changes.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 10 functions across 10 files. (3 skipped: 3 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

✨ Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

…producer; close test gaps

Review of #88: a process-keyed singleton let a later launch redirect a running
launch's data dir and onError. The tracker is now one per resolved data dir.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
@claude

claude Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Claude finished @krassx's task in 35s —— View job


Review of PR #88: StorageTracker for node/bun/deno (TR8, part 2)

I found no new real bugs, so I posted no inline comments. This is a re-review on push and agrees with the earlier review.

This is code reading only. I did not run the tests, the type checker or pnpm ci:local.

What I read

  • storage-tracker.ts in full.
  • disk-space-producer.ts.
  • The launch.ts and index.ts diffs.
  • TraceProducerBase in packages/capture/src/trace-producer.ts.

What I checked

  • Producer lifecycle. TraceProducerBase.start() returns early if already started, and stop() is idempotent. onStart therefore can't add a second tracker.on('disk') listener, and onStop always releases the one it added.
  • launch.ts guard. options.systemMetricsSampler === undefined matches the code below it, where { sample } replaces { producers }. A producer built under the legacy sampler would never be started, so skipping it is accurate. It also avoids needlessly rebinding the shared per-volume tracker.
  • Generation guarding. #gen is bumped in both #begin() and #end(). The timer callback and both .then branches check it. A stale read can't emit, report or flip #inFlight, and a timer whose clearInterval threw can't read.
  • Rebind while listening. Seams are merged, and #end() runs on the old seams (the old scheduler clears the old timer) before #begin() runs on the merged ones. A relaunch whose seams are unchanged restarts nothing, because dataDir is normalised with resolve().
  • Omit, never zero.
    • A bavail of 0 passes as a real full disk.
    • A non-positive bsize or blocks emits nothing.
    • A non-finite value emits nothing.
    • An overflowing product emits nothing.
    • Any of these clears #last.
  • Error paths. A synchronous statfs throw becomes a rejection, and a throwing onError is swallowed on both reporting paths. A failing setInterval leaves the tracker inert and reports once.
  • Registry keying. One tracker per resolved data dir, with interned key objects. resetStorageTracker handles the object, string and no-argument forms. The dirKeys map grows by one small object per distinct dir, which is bounded and documented.

Non-blocking observations (not findings)

  • Late subscriber waits up to 5 s. If a tracker is already active for a dir (a second launch on the same data dir, or another listener), a new subscriber gets no immediate emission. onActivate only fires on the first listener, so the producer's first disk trace for that subscriber arrives on the next poll, up to 5 s later. The old per-producer code read immediately on every start. This is harmless for a 5 s-cadence opt-in trace, but the producer's "no baseline to emit here" comment is only true for the first subscriber.
  • Hung statfs. A call that never settles (such as a dead NFS mount) keeps #inFlight true. The disk traces go quiet with no onError. This follows from the no-overlapping-reads rule, and hold:false means no stale value is recorded. A one-shot "read timed out" report would be a possible follow-up.
  • Persistent scheduler seam. A scheduler or statfs injected by one launch persists into later launches on the same dir, because seams merge and never drop. This is documented and tested, and launch.test.ts resets in afterEach.

Overall risk: Low

Merge recommendation: Approve once CI is green. I did not verify the pnpm ci:local result from the PR body.

Most important issues to fix: None.

Positives

  • The retention rule and the seam-merge semantics are written down and tested.
  • Generation guarding is applied consistently across the timer and both promise branches.
  • The producer is now composition only, which removes the duplicated polling and failure-streak code.
  • The systemMetricsSampler guard in launch.ts fixes a side effect the old code also had.
    · branch feat/node-storage-tracker

@krassx
krassx merged commit ed8d179 into main Oct 20, 2026
krassx added a commit that referenced this pull request Oct 20, 2026
…o and Electron trackers merged)

Update §14.5/§15.5 to origin/main 9b05e36: TR8 (#87, #88) and TR9 (#90, #91) as built, owner decision on private-mode opt-out, captureUserIdle opt-in pending confirmation, unverified-Electron list, and the remaining plan.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
krassx added a commit that referenced this pull request Oct 29, 2026
…o and Electron trackers merged)

Update §14.5/§15.5 to origin/main 9b05e36: TR8 (#87, #88) and TR9 (#90, #91) as built, owner decision on private-mode opt-out, captureUserIdle opt-in pending confirmation, unverified-Electron list, and the remaining plan.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
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