Skip to content

test(db): cover pruneExpiredRecords' two defensive ?? 0 fallback arms#8532

Merged
loopover-orb[bot] merged 1 commit into
JSONbored:mainfrom
RealDiligent:fix/critical-issue-retention-cov-8370
Jul 24, 2026
Merged

test(db): cover pruneExpiredRecords' two defensive ?? 0 fallback arms#8532
loopover-orb[bot] merged 1 commit into
JSONbored:mainfrom
RealDiligent:fix/critical-issue-retention-cov-8370

Conversation

@RealDiligent

Copy link
Copy Markdown
Contributor

Summary

src/db/retention.ts's pruneExpiredRecords guards two D1 driver anomalies with ?? 0 — the dry-run count row (line 75) and the delete-loop meta.changes (line 85) — and neither had direct coverage, even though the identical pattern on the sibling dedupeSignalSnapshots already has dedicated tests (lines 236-264). This mirrors that precedent exactly rather than inventing a new mocking style.

Three cases added:

Case Arm Assertion
count query returns no row row?.n ?? 0 deleted === 0, not NaN
row present but n: null row?.n ?? 0 deleted === 0
delete run() result lacks meta result.meta?.changes ?? 0 deleted === 0, not NaN

Worth flagging: the line-85 guard prevents an infinite loop, not just a NaN

While revert-proofing I removed each ?? 0 to confirm the tests actually detect its absence. Removing the line-75 guard fails the test cleanly, as expected. Removing the line-85 guard does something more serious: changes becomes NaN, and since every NaN comparison is false, the loop's exit condition

if (changes < batchSize || deleted >= maxPerTable) break;

never fires — the batched delete loop spins forever. My local run had to be killed on timeout.

So that ?? 0 is load-bearing beyond producing a tidy number, and the new test's failure mode for that arm is a hang rather than an assertion error. I'm noting this rather than quietly leaving it: a hang is a worse CI signal than a failure, and a maintainer may decide the loop deserves its own Number.isFinite guard. I have not changed the loop — the issue is scoped to test coverage only, and adding a production guard here is a behavior decision that needs a maintainer's read.

Closes #8370

Scope

  • The PR title follows type(scope): short summary Conventional Commit format, for example fix(api): restore profile access checks.
  • This PR is focused and does not mix unrelated backend, UI, MCP, docs, dependency, and deploy changes.
  • This follows CONTRIBUTING.md and does not reintroduce GitHub Pages, VitePress, site/, or CNAME.
  • I linked a currently open issue this PR resolves (e.g. Closes #123) — a linked open issue is required for every contributor PR.

Validation

  • git diff --check
  • npm run actionlint
  • npm run typecheck
  • npm run test:coverage locally; codecov/patch requires ≥99% coverage of the lines AND branches you changed (aim for 100% on your diff so CI variance does not fail near the threshold). Global coverage is a non-blocking trend with a loose 90% backstop, not the gate.
  • npm run test:workers
  • npm run build:mcp
  • npm run test:mcp-pack
  • npm run ui:openapi:check
  • npm run ui:lint
  • npm run ui:typecheck
  • npm run ui:build
  • npm audit --audit-level=moderate
  • New or changed behavior has unit/integration tests for new branches, fallback paths, and sanitizer boundaries

If any required check was skipped, explain why:

  • Test-only diff (one file, +50 lines): no workflow, MCP, UI, worker, or dependency surface is touched. Root tsc --noEmit is clean and git diff --check passes. codecov/patch has no changed production lines to score; the scoped run emits a non-empty coverage/lcov.info containing src/db/retention.ts (the suite imports it directly), satisfying the "Verify coverage report exists" step.
  • Pre-existing unrelated failures: test/unit/retention.test.ts's "dry-run reports eligible rows per table without deleting anything" and "deletes rows older than the window and keeps recent ones" fail on my local checkout. I verified they fail identically with my changes stashed, so they are environmental and untouched by this PR; my three new cases pass, and src/db/retention.ts is byte-unmodified (git diff --stat empty).

Safety

  • No secrets, wallet details, hotkeys, coldkeys, user PATs, private keys, raw trust scores, private rankings, or private maintainer evidence are exposed.
  • Public GitHub text stays sanitized, low-noise, and does not imply compensation guarantees or optimization tactics.
  • Auth, cookie, CORS, GitHub App, Cloudflare, or session changes include negative-path tests.
  • API/OpenAPI/MCP behavior is updated and tested where needed.
  • UI changes use live API data or real empty/error/loading states, not production mock/demo fallbacks.
  • Visible UI changes include a UI Evidence section below with JPG/JPEG or PNG screenshots arranged as organized, captioned, clickable thumbnails. SVG screenshots are not used as review evidence. Review-only screenshots or recordings are not committed to the repository.
  • Public docs/changelogs are updated where needed; changelogs are only edited for release-prep PRs.

UI Evidence

Not applicable — unit-test additions; no visible UI, frontend, docs, or extension change.

@RealDiligent
RealDiligent requested a review from JSONbored as a code owner July 24, 2026 18:56
@superagent-security

Copy link
Copy Markdown
Contributor

Superagent didn't find any vulnerabilities or security issues in this PR.

pruneExpiredRecords guards two D1 driver anomalies with ?? 0 -- the dry-run
count row and the delete-loop meta.changes -- and neither had direct coverage,
while the identical pattern on the sibling dedupeSignalSnapshots already has
dedicated tests.

Adds three cases mirroring that precedent: a dry-run count query returning no
row, one returning a null n, and a delete run() result lacking meta. Each
asserts the fallback yields 0 rather than NaN. No production change.

Closes JSONbored#8370
@loopover-orb loopover-orb Bot added the gittensor:bug Gittensor-scored bug fix — scores a 0.05x multiplier. label Jul 24, 2026
@loopover-orb

loopover-orb Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Tip

✅ LoopOver review result - approve/merge recommended

Review updated: 2026-07-24 19:07:03 UTC

1 file · 1 AI reviewer · no blockers · readiness 100/100 · CI green · clean

✅ Suggested Action - Approve/Merge

  • safe to merge

Review summary
This PR adds three unit tests mirroring the existing dedupeSignalSnapshots pattern to cover the two `?? 0` defensive fallback arms in pruneExpiredRecords (count-row-missing and meta-missing on the delete loop), closing #8370. The tests are well-targeted, mock env.DB directly to exercise the exact conditions that trigger each fallback, and the PR description transparently documents that the author verified via revert-testing that removing the line-85 guard causes an infinite loop rather than just a NaN, which is a valuable finding left for a maintainer decision rather than silently patched. The diff is test-only, closes a linked issue, and follows the sibling test's established mocking convention exactly.

Nits — 4 non-blocking
  • The PR correctly scopes itself to test coverage only, but per its own finding that the line-85 guard prevents an infinite hang (not just a cosmetic NaN), consider filing or linking a follow-up issue for a `Number.isFinite`/explicit guard so this load-bearing behavior isn't left solely dependent on the `?? 0` never being touched by a future refactor.
  • test/unit/retention.test.ts: the three new tests duplicate the mock-env boilerplate already established for dedupeSignalSnapshots almost verbatim — consider extracting a shared `mockD1({first, run})` helper if this pattern gets a fourth use, though at three call sites this is optional.
  • File or reference a maintainer-facing issue for the `Number.isFinite`-style hardening on the line-85 `changes` value, as the PR description itself recommends, so the finding isn't lost after merge.
  • Consider a small comment or follow-up test asserting `deleted` stays finite across repeated loop iterations if the guard is ever hardened, to lock in the hang-prevention behavior explicitly rather than only implicitly via the `?? 0`.

Decision drivers

  • ✅ Code review — No blockers (1 reviewer)
  • ✅ Gate result — Passing (No configured blocker found.)
Context & advisory signals — never blocks the verdict
Signal Result Evidence
Linked issue ✅ Linked #8370
Related work ✅ No active overlap found No same-issue or scoped active PR overlap found.
Change scope ✅ 20/20 Low review scope from cached public metadata (1 linked issue).
Validation posture ✅ 25/25 PR body includes validation/test evidence.
Contributor workload ✅ 10/10 Author activity: 366 registered-repo PR(s), 146 merged, 37 issue(s).
Contributor context ✅ Confirmed Gittensor contributor RealDiligent; Gittensor profile; 366 PR(s), 37 issue(s).
Improvement ℹ️ Insufficient signal risk: clean · value: insufficient-signal · LLM: minor
Linked issue satisfaction

Addressed
The PR adds three tests directly mocking env.DB to trigger both the dry-run row?.n ?? 0 fallback (line 75) and the delete-loop meta?.changes ?? 0 fallback (line 85), asserting deleted === 0 rather than NaN, mirroring the sibling test pattern as requested with no production code changes.

Review context
  • Author: RealDiligent
  • Role context: outside_contributor
  • Public audience mode: oss maintainer
  • Lane context: Repository is configured for direct PR review.
  • Public profile languages: not available
  • Official Gittensor activity: 366 PR(s), 37 issue(s).
  • PR-specific overlap: none found.
Contributor next steps
  • Keep the PR focused and include validation evidence before maintainer review.
Signal definitions
  • Related work = same linked issue, overlapping active PRs, or title/path similarity.
  • Change scope = cached public metadata such as size labels, draft state, and review-burden hints.
  • Validation posture = whether the PR provides enough public validation/test evidence for maintainer review.
  • Contributor workload = public contributor activity and cleanup pressure, not a repo-wide quality failure.
  • Contributor context = public GitHub/Gittensor identity context; non-Gittensor status is not a blocker.
🧪 Chat with LoopOver

Ask LoopOver a question about this PR directly in a comment — grounded only in the same cached, public-safe facts shown above, never a new claim.

  • @loopover ask &lt;question&gt; answers contribution-quality Q&A with source citations and freshness.
  • @loopover chat &lt;question&gt; answers in natural prose from cached decision-pack facts via local inference (maintainer/collaborator; read-only).
  • A plain-language @loopover mention with a real question is routed to the closest matching read-only command automatically — no exact syntax required.

Full command reference: https://loopover.ai/docs/loopover-commands

🧪 Experimental — new and may change.

🟩 Safe / merged · 🟦 Advisory · 🟨 Held for review · 🟥 Blocked / closed


💰 Earn for open-source contributions like this. Gittensor lets GitHub contributors earn for the work they already do — register to start earning →.

Checked by LoopOver, a quiet PR intelligence layer for OSS maintainers.

  • Re-run LoopOver review

@loopover-orb loopover-orb Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LoopOver approves — the gate is satisfied and CI is green.

@loopover-orb
loopover-orb Bot merged commit 61f6ec6 into JSONbored:main Jul 24, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gittensor:bug Gittensor-scored bug fix — scores a 0.05x multiplier.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

pruneExpiredRecords's defensive ?? 0 arms have zero test coverage, unlike its sibling function

1 participant