Skip to content

fix(storage): retire crawls from killed audits; prune continues past a failing project #941 - #945

Merged
nc9 merged 3 commits into
mainfrom
fix/941-retire-orphan-crawls
Oct 20, 2026
Merged

nc9 merged 3 commits into
mainfrom
fix/941-retire-orphan-crawls

Conversation

@nc9

@nc9 nc9 commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

What

  • Crawls left by audits killed before they finished (kill -9, watchdog, OOM) are "abandoned" once a newer audit of the project has finished: unfinished, not retired, started before the newest finished crawl. [storage] keep_audits and self disk --prune now retire them. They take no window slot.
  • retireCrawls(ids, at, { allowAbandoned }) skips the finished-only guard only for ids that still satisfy the abandoned predicate, re-checked inside the retiring transaction. A newest or live crawl is still refused.
  • self disk --prune: each project is planned and run on its own (a locked or unreadable db is reported, the rest continue); abandoned crawls are listed apart with status and age; unfinished crawls newer than the newest finished audit are listed as skipped with a reason; free disk is checked before VACUUM (retire anyway, skip rebuild, report skipped); final summary; exit 1 only when a project failed.
  • Ctrl-C marks the crawl this process owns (by id) as stopped, so --resume continues it.
  • No schema change; works on v0.0.115 to v0.0.117 databases.

Why

Closes #941. Retention only looked at finished audits, so killed crawls and their bulk rows (sitemap_urls, frontier, rule_results) piled up forever, and prune threw on the first unfinished crawl and aborted every later project.

Liveness (updated)

A crawl is only retired when it also has had no activity (latest page or frontier timestamp) for 30 minutes, so an overlapping live audit is never retired and recently active orphans are listed as skipped with their last activity. Remaining gap: a killed newest crawl stays until the next successful audit, and a crawl killed less than 30 minutes ago is retired by a later audit. stopped and paused crawls (what --resume continues; Ctrl-C leaves one) need 7 days idle instead. failed is unfinished in all three queries: abandoned under the same rule, and when newer than the newest finished audit it is skipped, never holding a --keep slot. A crawl that turns active between listing and write is skipped alone and the rest of the batch retires. Known limit: an overlapping audit silent for 30+ minutes in its analyze phase looks abandoned (test documents it); a pid/heartbeat lease closes that: #946.

Reproducing the issue's kill -9 loop now needs a 30-minute wait (or crawls whose last page is older than that) before an audit or prune retires the killed crawls.

Tests

Real temp SQLite: predicate matrix, retention retiring orphans without window slots, resumed-crawl refusal in the transaction, prune with killed + live + finished crawls, repeated prune keeps the window, a fresh-activity orphan kept vs a 31-minute-idle one retired, one bad project does not stop the rest, exit codes, low-disk skip, signal path. Docs updated (tangly check --strict passes), CHANGELOG entry added.

skills: no change (the squirrelscan skill does not document self disk --prune).

@claude

claude Bot commented Oct 20, 2026

Copy link
Copy Markdown

Review of #945 (retire abandoned crawls, per-project prune). I read the diff only and did not run the tests. The storage-layer changes (listAbandonedCrawls, retireCrawls guard) were not visible in the part of the diff I read, so I could not check them.

  • (high) apps/cli/src/audit/retention.ts (retainRecentAudits): the end of every successful audit now retires every unfinished crawl older than the newest finished one, whatever keep_audits says. Two audits of one project that overlap (parallel CI jobs, or a long audit plus a quick re-run) can therefore delete the still-running crawl's sitemap_urls, frontier and rule_results while it is writing. The PR's "Known limit" section admits this. It is a silent data-loss path on the default retention flow, and the in-transaction recheck cannot catch it because the predicate holds. Suggest gating the automatic path on a minimum age (for example, unfinished and older than N hours) until the heartbeat/lease follow-up lands. Also link that follow-up issue from the PR.
  • (medium) A stopped or paused crawl is exactly what --resume continues, and this PR now makes Ctrl-C produce more of them. Once any later audit finishes, those crawls count as abandoned and get deleted. The new Ctrl-C-to-stopped change then sets up a resume the next audit can erase. Please confirm that is intended and say so in the docs and CHANGELOG, or exclude stopped crawls from retirement for a grace period.
  • (medium) apps/cli/src/audit/stop-interrupted-crawl.ts: stopInterruptedCrawls opens a second SQLite connection inside a signal handler while the process's own connection may hold a write transaction. busy_timeout = 1000 blocks the handler for up to 1s and then silently returns 0, so the crawl stays running. That is acceptable as best effort, but the handler should state it is best-effort. Also, existsSync plus new Database can create an empty db file if the file is removed between the two calls. Opening with { create: false } avoids that.
  • (low) apps/cli/src/self/disk.ts (lowDiskReason): the 1.1×size + 64MB threshold is a heuristic. VACUUM can also need space for the WAL, and statfsSync bavail is only reliable on local filesystems. The "unreadable means proceed" fallback is reasonable, but a note in the code would help.
  • (low) apps/cli/src/cli/commands/self.ts (runPrune): the pre-run summary counts retiringAudits as retiring + abandoned, but the message says "audit(s)... Their reports stop being renderable". Abandoned crawls never had renderable reports, so the wording is slightly off. When plans.length === 0 with planning failures, the output says "0 project(s) pruned", which is fine.
  • (nit) planProjectPrune returns name: dbPath, and the caller overrides it with the directory name. Consider dropping the field or setting it properly.
  • (nit) The tests are thorough (predicate matrix, in-transaction refusal, isolation of one bad project, exit codes). One gap: nothing exercises the overlapping-audit scenario described above, even as a documented-limitation test. Adding one would make the known limit visible in the suite.

@nc9
nc9 force-pushed the fix/941-retire-orphan-crawls branch from fcff05a to 9ad48be Compare October 20, 2026 02:40
nc9 added 2 commits October 20, 2026 13:40
…a failing project #941

Abandoned crawls (unfinished, older than the newest finished audit) are retired by keep_audits and self disk --prune, take no window slot, and are re-checked inside the retiring transaction. Prune isolates each project, checks free disk before VACUUM, prints a summary and exits 1 only on failure. Ctrl-C marks the owned crawl stopped.

Signed-off-by: Nik Cubrilovic <[email protected]>
…941

Latest page or frontier timestamp must be older than 30 minutes, so an overlapping live audit is never retired. Recently active orphans are skipped with their last activity.

Signed-off-by: Nik Cubrilovic <[email protected]>
@nc9
nc9 force-pushed the fix/941-retire-orphan-crawls branch from 9ad48be to c0aeb47 Compare October 20, 2026 02:40
@claude

claude Bot commented Oct 20, 2026

Copy link
Copy Markdown

Reviewed the diff (retention, stop-interrupted-crawl, self disk --prune, sqlite.ts abandoned-crawl predicate, tests, docs). I read the code but did not run the tests. The design is sound: one shared predicate for listing and for the in-transaction re-check, the signal-handler write is best-effort, and prune now isolates per-project failures. Findings:

  • (medium) packages/crawler/src/storage/sqlite.ts (retireCrawls with allowAbandoned): refuseUnfinished throws for the whole batch if any one id stops qualifying between listing and the write. Examples are a crawl resumed by another process, or a newer activity timestamp. In retainRecentAudits that makes the entire retention pass fail, including the ordinary windowed retirements. Consider skipping the non-qualifying abandoned ids and retiring the rest. Alternatively, catch that error and retry the windowed set alone.
  • (medium) The abandoned predicate is project-wide, not per base URL. A crawl is retired once it started before the newest finished audit and has shown no page or frontier write for 30 minutes. Two audits overlapping in one project (different sites, or a slow analyze/rules phase that writes no pages) can have the older, still-live run retired when the newer one finishes. The code comments acknowledge the overlap case, but 30 minutes of idle time is only a heuristic. A long analyze phase writes no pages or frontier rows. Consider also counting recent rule_results writes, or a heartbeat column, as activity. At minimum, document the limit.
  • (low) stop-interrupted-crawl.ts: the ownedCrawlId module-level singleton is fine for one audit per process. It is silently overwritten if runAudit is called twice in the same process, so a comment saying so would help. The handler opens a second SQLite connection while the audit's connection may hold a write lock, and the 1s busy_timeout means the stopped mark can be lost. That is acceptable for best-effort, and the failure is silent.
  • (low) self.ts: when every project fails planning, the summary line goes to console.log while the failures go to console.error. The FAILED lines also appear on stderr in the plan phase but on stdout in the run phase. Pick one stream.
  • (nit) The comment on LAST_ACTIVITY_SQL and the ABANDONED_IDLE_MS constant sit below abandonedSql, which uses them. This works because they are static members, but declaring them first reads better. The 30-minute figure is also repeated as literal text in the prune output and docs. Derive it from the constant.
  • (nit) Interpolating cutoff into the SQL string is safe, since it is a computed number. Binding it as a parameter would still match the surrounding style better and avoid any doubt.

Test coverage looks good: the new tests cover the predicate, the retention integration, the signal-path write and the prune plan. One gap is a test for the batch-refusal race in the first finding.

@claude

claude Bot commented Oct 20, 2026

Copy link
Copy Markdown

Review of #945

Well-structured overall: the abandoned predicate is shared between the listing and the in-transaction re-check, and test coverage is strong. A few things to consider.

  • (medium) apps/cli/src/audit/retention.ts and retireCrawls in packages/crawler/src/storage/sqlite.ts: windowed and abandoned ids go into one retireCrawls call, and refuseUnfinished() throws for the whole batch. If one abandoned crawl is resumed or becomes active between the listing and the transaction, the whole retention pass (including the normal keep_audits window) is rolled back, and the caller swallows the error. Consider skipping the offending ids when allowAbandoned is set instead of throwing.
  • (medium) apps/cli/src/audit/stop-interrupted-crawl.ts: the signal handler marks the crawl stopped over a second connection while the main process may still be writing. With busy_timeout = 1000 the update can fail silently (returns 0), leaving the crawl running. Fine as best-effort, but please confirm nothing later overwrites stopped with running and that the Ctrl-C message does not claim it was recorded.
  • (low) sqlite.ts abandonedSql: its status filter includes failed, while listPossiblyLiveCrawls and the refuse query exclude failed separately. A failed crawl newer than the newest finished audit is in neither unfinished set in planProjectPrune, so it still takes a --keep slot. Please check this matches the docs.
  • (low) LAST_ACTIVITY_SQL runs two correlated MAX() subqueries per crawl row. I could not confirm an index on frontier(crawl_id, fetched_at) or pages(crawl_id, fetched_at), and this runs at the end of every audit and on prune. Probably fine, but worth checking on a large db.
  • (low) lowDiskReason in apps/cli/src/self/disk.ts: the 1.1x + 64 MiB heuristic ignores the WAL and a temp dir on another volume (VACUUM uses the temp store). Reasonable as an approximation.
  • (low) self.ts: --dry-run with plan failures exits 1. Confirm that is the intended contract and that it is in docs/cli/self.mdx.
  • (nit) self.ts: plans.filter((p) => planIsActionable(p.plan)).length is computed twice; hoist it.

No security concerns: SQL interpolates only a computed integer cutoff and static strings, and ids are bound parameters.

…s; longer grace for stopped/paused #941

retireCrawlsDetailed skips ids that stopped qualifying inside the transaction and retires the rest. stopped/paused need 7 days idle. failed is unfinished in all three queries. Signal mark opens with create:false.

Signed-off-by: Nik Cubrilovic <[email protected]>
@claude

claude Bot commented Oct 20, 2026

Copy link
Copy Markdown

Reviewed the diff (retention, prune, storage, Ctrl-C handling, tests). The design is careful: the abandoned predicate is shared between the listing and the in-transaction re-check, per-project failures are isolated, and test coverage is good. Findings:

  • (medium) packages/crawler/src/storage/sqlite.ts (retireCrawlsDetailed): failed was removed from the finished-only guard. Any caller that passes a failed crawl id without allowAbandoned now throws, where it used to retire the crawl. I found no other non-test callers in the repo, but retireCrawls is a public storage API, so call out the behaviour change in the changelog or docs.
  • (medium) apps/cli/src/audit/stop-interrupted-crawl.ts: the Ctrl-C handler opens a second sqlite connection and runs a synchronous UPDATE with a 1s busy_timeout. The audit's own connection may still hold the write lock when the signal arrives. If so, the UPDATE silently fails and the crawl stays running, so it is treated as killed. That is an acceptable fallback, but a log line on failure would make it diagnosable. The module-level ownedCrawlId is also global mutable state. That is fine for a CLI, but it is not safe if runAudit is ever invoked more than once per process (for example by the MCP server).
  • (low) apps/cli/src/cli/commands/self.ts: process.exit(1) sits inside the planFailures loop, and the "0 project(s) pruned" summary prints there too. As written it looks like a plan failure aborts the whole prune, which contradicts the PR description ("the rest continue"). Please confirm the intent, and move the check outside the loop.
  • (low) retention.ts: all ids are passed with allowAbandoned: true. Any id that fails the re-check is skipped silently, and the only trace is a lower retired count. Consider logging skipped ids.
  • (low) sqlite.ts: the correlated subqueries in LAST_ACTIVITY_SQL scan pages and frontier per unfinished crawl. Confirm there are indexes on (crawl_id, fetched_at). Prune is infrequent, so the impact is low.
  • (nit) lowDiskReason: give the 1.1x and 64MB constants names.
  • (nit) formatAge: the parameter is called startedAt but is also used for last-activity times. Rename it to timestamp.

No critical or high-severity problems found.

@nc9
nc9 merged commit 0290290 into main Oct 20, 2026
15 checks passed
@nc9
nc9 deleted the fix/941-retire-orphan-crawls branch October 20, 2026 03:12
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.

keep_audits never retires crawls from killed audits, project.db grows without bound

1 participant