You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
maintenance: a timed-out purge is detached, not stopped, so purges accumulate #1103
Found by the static review of the 026-nwc-req-before-event branch, run after its round 1: the finding is in a file that branch does not touch, and it is pre-existing on rewrite/main at 4adaa42.
The mechanism
crates/nostream-services/src/workers/maintenance.rs:104-144 spawns the retention purge and bounds it with a timeout:
let purge = tokio::spawn(asyncmove{ purge_tasks.clear_old_events().await});
...
let purge_timed_out = match tokio::time::timeout(self.purge_timeout, purge).await{Err(_) => { tracing::error!(...);true}
...
};PassOutcome{ purge_timed_out }
A JoinHandle dropped by timeout is detached, not aborted: the purge keeps running against the stores while run_pass returns. The loop at :160-176 then does self.run_pass().await; self.running.store(false, ...) and never reads the outcome, so the single-run guard is cleared while the detached purge is still working. Every later tick starts another purge, so a store whose cleanup is slower than the interval accumulates detached purges and competing database work, with only a log line per timeout.
purge_timed_out is read only by tests/maintenance.rs:251 and :270 — the field is produced for the tests and dropped in production.
What a fix needs
The runner should hold the outstanding purge and refuse to start a pass while one is still in flight; a timeout should either abort() the task (accepting cancellation, with the loop acting on the outcome) or be treated as "still running" rather than as a completed pass. Either way the loop has to consume PassOutcome, because today a timeout is logged and then forgotten. A test can drive two ticks with a purge that outlives the interval and assert the second pass does not spawn a second purge.
A timed-out purge is kept, and the next pass waits on it instead of starting another (9 passes now share 1 purge instead of starting 9); the loop logs each outcome
Trade-off: a purge that never returns holds retention until restart, logged with passes_waited each pass, rather than aborting a store write midway. Happy to abort after N passes if you'd prefer that
2 new tests that fail on the old detach; all five CLAUDE.md checks pass (1819 tests)
Reviewed c75a92ce (fix/1103-purge-in-flight, based on dcf0259e, which is the current rewrite/main). The mechanism is right and the tests discriminate. Nothing here blocks merge; the first three are worth a line before it, the rest are your call.
What I verified rather than read
The defect is real on the base, proven by running it. On a clean checkout of dcf0259e I added an adapted copy of the new first test — two passes over a Semaphore(0)-blocked purge with a 20 ms cap — asserting starts == 2, and it passes there (cargo test -p nostream-services --test purge-accumulation-1103: 1 passed). So the base really does start a second purge while the first one still runs. Your test asserts starts == 1 for the same scenario; that is the assertion the fix changes, and it is the right one.
The new tests pass, and not once.cargo test -p nostream-services --test maintenance: 9 passed, 0 failed — then the same target 20 more times back to back, 0 failures. No flake surfaced.
The five CLAUDE.md checks, run in the same worktree on this commit: cargo fmt --all --check, both clippy passes (--all-targets and the strict --lib --bins one), cargo test --workspace --all-features, cargo build --workspace --all-features --release — all green. CI is still the authority; nothing local contradicts it.
Nothing odd in the diff: no hidden characters in the three changed files (U+200B-200F, U+202A-202E, U+2066-2069, U+FEFF, U+E0000-E007F), no workflow, dependency or install-time edits.
The changeset is the shape rewrite/main asks for: empty frontmatter, like the existing ones, so Changeset Required passes and no published package is touched. Header is 84 characters, conventional form.
The design, once measured
tokio::time::timeout(self.purge_timeout, &mut purge) is the correct idiom, and it is the whole fix: JoinHandle is Unpin and &mut F is a Future when F is, so a timeout leaves the handle intact instead of consuming and detaching it. Everything else is bookkeeping that should stay as small as it is here.
Waiting instead of starting a second purge is the right call. Aborting a store write midway leaves the store in a state nothing in this loop can reason about, and the behaviour being replaced — duplicated work against one database — is worse than the one being accepted. The cost is stated honestly in both the module doc and the changeset: a purge that never returns holds retention until restart. I would take the same trade.
Findings
1. store_outstanding_purge overwrites the slot without looking.run_pass is pub. If two passes ever overlap, the second take_outstanding_purge() finds None, starts its own purge, and its timeout stores over the first handle — dropping it, which detaches a purge that is still working, silently: the bug this commit exists to remove. run() cannot overlap today (the select! never wraps run_pass), so this is about the next caller rather than this one. A debug_assert!(slot.is_none()) in the store closes it for the cost of a branch, and would have caught a future caller in tests; returning the displaced handle so it can be logged or aborted is the other shape.
2. The late-purge arm has no test. In run_pass, Some(previous) with previous.handle.is_finished() takes the arm that reads the finished purge's counts through log_late_purge and then starts a new one. No case reaches it: the first test's third pass adds the permit and calls run_pass with no await in between, so the purge has not been polled and is_finished() is still false — the pass takes the wait arm. A four-line case covers it: release the gate, tokio::task::yield_now().await so the purge finishes, then run a pass and assert purge_started and purge_starts == 2. Without it, the branch that exists so a result is not lost is the one branch nobody watches.
3. ADR 0019 D1's cost paragraph is now inaccurate. It says the loop discards the outcome — "one Option the loop still discards — run_pass's outcome is dropped at the tick" — and describes PassOutcome as gaining one field. After this commit the loop logs the outcome at debug! and the struct has three fields, the third of which (purge_started) exists only so a test can tell a wait from a start. One paragraph; either amend it or state in the ADR why the log line does not count as consuming the value.
4. A pass dropped between the take and the store detaches the handle again. Narrower than (1) and the same class: the handle lives only in a local across the pass's awaits, so cancelling run_pass mid-flight loses it and the purge runs untracked. The doc comment says passes are "not meant to be … cancelled midway"; naming what happens when one is would make the constraint actionable for the next caller.
5. purge_started is derived from passes_waited == 0. True today, because the wait arm is only reachable with a stored count of at least one, but it states one fact twice and will drift if the counter ever gains a meaning (a purge that completes inside a waiting pass and resets it, say). Setting an explicit flag at the two arms costs two lines and cannot drift.
6. The third-pass assertion depends on the single-threaded test runtime, as its comment says. The property worth pinning — four passes over one blocked purge start exactly one purge, and the pass that sees it finish reports its counts — does not depend on the runtime, so asserting purge_starts == 1 across the sequence plus counts.is_some() on the third would survive a move to flavor = "multi_thread" without weakening anything.
7. Log volume on a hung purge. Each pass emits the timeout error! and the still-running warn!, so a purge that never returns writes two lines a minute indefinitely. The counter is already there; warning on the first wait and then every tenth would keep the signal out of an operator's log. Optional.
The fix is sound and the tests are honest about what they measure. Items 1-3 are small and local.
Hey @cameri, thanks for the review. Items 1-3 are fixed in 6269d9e, on top of c75a92c, on the same branch:
The store no longer overwrites a held purge (debug_assert! on overlap, and an error log in release); a new test covers the late-purge arm
ADR 0019 D1/D3 no longer say the loop discards the outcome, and D1 records the two new fields. I also did 4, 5 and 7 (cancel doc, explicit purge_started, warning on the 1st and every 10th wait)
I left 6 as is: on a multi-thread runtime the purge can finish first and take the late arm, so those assertions would change too. All five checks pass (1820 tests), and the maintenance suite passed 20 more runs
6269d9e closes 1, 2 and 3, and also takes 4, 5 and 7. I re-ran the checks on the commit rather than reading the diff alone — everything below is measured, not inferred.
cargo test -p nostream-services --test maintenance — 10 passed (the 9 before plus the late-arm case), then the same target 10 more times back to back with 0 failures
cargo test --workspace --all-features — 1820 passed, 0 failed (5 min 5 s) — the same count you quote
0 hidden characters (tag range, bidi controls, BOM) across the four changed files
store_outstanding_purge gains the debug_assert!, the error log and the early return. Keeping the older handle and dropping the incoming one is the right side to keep — the newer purge is the one nothing has waited on yet — and the log names exactly what stopped being tracked.
The new test walks the arm end to end: take a finished purge, log_late_purge it, start a fresh one, and report that one's counts. One note on what it is: coverage, not discrimination — the arm is unchanged from c75a92c, so the test passes there too. That is the right shape for a branch that existed untested; it just is not a regression test, and I would not describe it as one.
Both ADR passages are amended and the new wording matches the code: the loop does tracing::debug!(?outcome, "maintenance pass finished"), and D1 records the two extra fields.
The run_pass doc now names the window: between the take and the store the handle lives only in that pass, so a dropped pass detaches the purge again and an overlapping one finds nothing.
purge_started is set at the two arms instead of derived from the counter.
Cadence is warnings at passes_waited 1, 10, 20, … — nine passes between the first and the second, ten after that. That matches "the first wait and every tenth after it".
On 6, you are right and I was wrong
I claimed the property "four passes over one blocked purge start exactly one purge, and the pass that sees it finish reports its counts" was runtime-independent. It is not: after gate.add_permits(1) the purge can complete before the third pass checks is_finished(), that pass then legitimately starts a second purge, and both halves of my proposed assertion flip. The runtime-independent slice is narrow — purge_starts == 1 and !purge_startedafter the second pass, before any permit is added — and the test already asserts exactly those two, before the comment. Leaving item 6 as it is the honest resolution; removing the dependency would need the purge held by something other than a permit, which is a bigger change than the test is worth.
Two notes, neither blocking
debug_assert! makes an overlap fatal in a dev build: the panic kills the loop task, and maintenance stops until restart. That is louder than the error log, which is the trade you chose deliberately — worth knowing it is a stop, not just a message.
The changeset still describes the first commit only; the overlap guard and the log cadence are not in it. Fine if a changeset is for operators rather than reviewers.
Landing
rewrite/main accepts merge commits only — squash and rebase are disabled — so a PR merge is head-preserving by construction: both commits keep your authorship. Since your fork cannot open the PR, I have opened #1247 from a branch at 6269d9e inside this repo. Your fork is untouched, and the branch is disposable whether or not it lands.
Landed path for 6269d9e: PR #1247, from the branch contrib/1103-purge-in-flight in this repo (your fork untouched, both of your commits keep their authorship — the repository allows merge commits only).
One commit on top, mine: cd0bfd86. Greptile was right that the late-result test could not fail — deleting log_late_purge(previous.handle.await) left every assertion passing — so the test now captures the log line and asserts its counts, and the target reports 9 passed / 1 failed with that call removed. Worth lifting into your fork if you keep one, since the branch here is disposable.
Activity
AgrimTawani commentedon Nov 23, 2026
Hey @cameri, can I pick this up if nobody's on it yet?
PassOutcome, so a timeout counts as "still running" instead of being forgottencameri commentedon Nov 23, 2026
@AgrimTawani Assigned to you.
AgrimTawani commentedon Nov 24, 2026
Hey @cameri, the fix for this is ready on my fork; I can't open the PR myself: rewrite/main...AgrimTawani:nostream:fix/1103-purge-in-flight
passes_waitedeach pass, rather than aborting a store write midway. Happy to abort after N passes if you'd prefer thatCLAUDE.mdchecks pass (1819 tests)chappie-daemon commentedon Nov 24, 2026
Reviewed
c75a92ce(fix/1103-purge-in-flight, based ondcf0259e, which is the currentrewrite/main). The mechanism is right and the tests discriminate. Nothing here blocks merge; the first three are worth a line before it, the rest are your call.What I verified rather than read
dcf0259eI added an adapted copy of the new first test — two passes over aSemaphore(0)-blocked purge with a 20 ms cap — assertingstarts == 2, and it passes there (cargo test -p nostream-services --test purge-accumulation-1103:1 passed). So the base really does start a second purge while the first one still runs. Your test assertsstarts == 1for the same scenario; that is the assertion the fix changes, and it is the right one.cargo test -p nostream-services --test maintenance: 9 passed, 0 failed — then the same target 20 more times back to back, 0 failures. No flake surfaced.CLAUDE.mdchecks, run in the same worktree on this commit:cargo fmt --all --check, both clippy passes (--all-targetsand the strict--lib --binsone),cargo test --workspace --all-features,cargo build --workspace --all-features --release— all green. CI is still the authority; nothing local contradicts it.rewrite/mainasks for: empty frontmatter, like the existing ones, soChangeset Requiredpasses and no published package is touched. Header is 84 characters, conventional form.The design, once measured
tokio::time::timeout(self.purge_timeout, &mut purge)is the correct idiom, and it is the whole fix:JoinHandleisUnpinand&mut Fis aFuturewhenFis, so a timeout leaves the handle intact instead of consuming and detaching it. Everything else is bookkeeping that should stay as small as it is here.Waiting instead of starting a second purge is the right call. Aborting a store write midway leaves the store in a state nothing in this loop can reason about, and the behaviour being replaced — duplicated work against one database — is worse than the one being accepted. The cost is stated honestly in both the module doc and the changeset: a purge that never returns holds retention until restart. I would take the same trade.
Findings
1.
store_outstanding_purgeoverwrites the slot without looking.run_passispub. If two passes ever overlap, the secondtake_outstanding_purge()findsNone, starts its own purge, and its timeout stores over the first handle — dropping it, which detaches a purge that is still working, silently: the bug this commit exists to remove.run()cannot overlap today (theselect!never wrapsrun_pass), so this is about the next caller rather than this one. Adebug_assert!(slot.is_none())in the store closes it for the cost of a branch, and would have caught a future caller in tests; returning the displaced handle so it can be logged or aborted is the other shape.2. The late-purge arm has no test. In
run_pass,Some(previous)withprevious.handle.is_finished()takes the arm that reads the finished purge's counts throughlog_late_purgeand then starts a new one. No case reaches it: the first test's third pass adds the permit and callsrun_passwith no await in between, so the purge has not been polled andis_finished()is still false — the pass takes the wait arm. A four-line case covers it: release the gate,tokio::task::yield_now().awaitso the purge finishes, then run a pass and assertpurge_startedandpurge_starts == 2. Without it, the branch that exists so a result is not lost is the one branch nobody watches.3. ADR 0019 D1's cost paragraph is now inaccurate. It says the loop discards the outcome — "one
Optionthe loop still discards —run_pass's outcome is dropped at the tick" — and describesPassOutcomeas gaining one field. After this commit the loop logs the outcome atdebug!and the struct has three fields, the third of which (purge_started) exists only so a test can tell a wait from a start. One paragraph; either amend it or state in the ADR why the log line does not count as consuming the value.4. A pass dropped between the take and the store detaches the handle again. Narrower than (1) and the same class: the handle lives only in a local across the pass's awaits, so cancelling
run_passmid-flight loses it and the purge runs untracked. The doc comment says passes are "not meant to be … cancelled midway"; naming what happens when one is would make the constraint actionable for the next caller.5.
purge_startedis derived frompasses_waited == 0. True today, because the wait arm is only reachable with a stored count of at least one, but it states one fact twice and will drift if the counter ever gains a meaning (a purge that completes inside a waiting pass and resets it, say). Setting an explicit flag at the two arms costs two lines and cannot drift.6. The third-pass assertion depends on the single-threaded test runtime, as its comment says. The property worth pinning — four passes over one blocked purge start exactly one purge, and the pass that sees it finish reports its counts — does not depend on the runtime, so asserting
purge_starts == 1across the sequence pluscounts.is_some()on the third would survive a move toflavor = "multi_thread"without weakening anything.7. Log volume on a hung purge. Each pass emits the timeout
error!and the still-runningwarn!, so a purge that never returns writes two lines a minute indefinitely. The counter is already there; warning on the first wait and then every tenth would keep the signal out of an operator's log. Optional.The fix is sound and the tests are honest about what they measure. Items 1-3 are small and local.
fix(maintenance): keep an overlapping pass from dropping a held purge…
AgrimTawani commentedon Nov 25, 2026
Hey @cameri, thanks for the review. Items 1-3 are fixed in
6269d9e, on top ofc75a92c, on the same branch:debug_assert!on overlap, and an error log in release); a new test covers the late-purge armpurge_started, warning on the 1st and every 10th wait)chappie-daemon commentedon Nov 26, 2026
6269d9ecloses 1, 2 and 3, and also takes 4, 5 and 7. I re-ran the checks on the commit rather than reading the diff alone — everything below is measured, not inferred.Ran on a worktree at
6269d9ecargo fmt --all --check— cleancargo clippy --workspace --all-targets --all-features -- -D warnings— clean (46.7 s)cargo test -p nostream-services --test maintenance— 10 passed (the 9 before plus the late-arm case), then the same target 10 more times back to back with 0 failurescargo test --workspace --all-features— 1820 passed, 0 failed (5 min 5 s) — the same count you quoterewrite/main(6d1454b1); feat(mcp): the maintenance tools, the counts the pass drops, and the run record #1226 did not touch these filesItem by item
store_outstanding_purgegains thedebug_assert!, the error log and the early return. Keeping the older handle and dropping the incoming one is the right side to keep — the newer purge is the one nothing has waited on yet — and the log names exactly what stopped being tracked.log_late_purgeit, start a fresh one, and report that one's counts. One note on what it is: coverage, not discrimination — the arm is unchanged fromc75a92c, so the test passes there too. That is the right shape for a branch that existed untested; it just is not a regression test, and I would not describe it as one.tracing::debug!(?outcome, "maintenance pass finished"), and D1 records the two extra fields.run_passdoc now names the window: between the take and the store the handle lives only in that pass, so a dropped pass detaches the purge again and an overlapping one finds nothing.purge_startedis set at the two arms instead of derived from the counter.passes_waited1, 10, 20, … — nine passes between the first and the second, ten after that. That matches "the first wait and every tenth after it".On 6, you are right and I was wrong
I claimed the property "four passes over one blocked purge start exactly one purge, and the pass that sees it finish reports its counts" was runtime-independent. It is not: after
gate.add_permits(1)the purge can complete before the third pass checksis_finished(), that pass then legitimately starts a second purge, and both halves of my proposed assertion flip. The runtime-independent slice is narrow —purge_starts == 1and!purge_startedafter the second pass, before any permit is added — and the test already asserts exactly those two, before the comment. Leaving item 6 as it is the honest resolution; removing the dependency would need the purge held by something other than a permit, which is a bigger change than the test is worth.Two notes, neither blocking
debug_assert!makes an overlap fatal in a dev build: the panic kills the loop task, and maintenance stops until restart. That is louder than the error log, which is the trade you chose deliberately — worth knowing it is a stop, not just a message.Landing
rewrite/mainaccepts merge commits only — squash and rebase are disabled — so a PR merge is head-preserving by construction: both commits keep your authorship. Since your fork cannot open the PR, I have opened #1247 from a branch at6269d9einside this repo. Your fork is untouched, and the branch is disposable whether or not it lands.chappie-daemon commentedon Nov 26, 2026
Landed path for
6269d9e: PR #1247, from the branchcontrib/1103-purge-in-flightin this repo (your fork untouched, both of your commits keep their authorship — the repository allows merge commits only).One commit on top, mine:
cd0bfd86. Greptile was right that the late-result test could not fail — deletinglog_late_purge(previous.handle.await)left every assertion passing — so the test now captures the log line and asserts its counts, and the target reports 9 passed / 1 failed with that call removed. Worth lifting into your fork if you keep one, since the branch here is disposable.fix(maintenance): hold a timed-out purge instead of detaching it (#1103…