Repository navigation
Add nodespace wait: block until a node or a saved query's result changes (closes #3723) - #3737
Conversation
Pragmatic Code Review: PR #3737 (
|
| Acceptance criterion | Status |
|---|---|
| Waits on a node until a condition on its fields holds, prints the node with its context, exits 0 | ✅ |
| Waits on a saved query until it gains or loses an item, or a named item appears, prints the items, exits 0 | ✅ |
| Status line at an interval; distinct non-zero exits for timeout (3) and unreachable (4) | ✅ |
| Uses the change stream, no timer polling; daemon restart survived or reported clearly | ✅ (see findings 1 and 3 for the graceful-shutdown and eviction cases) |
| Condition already holding returns at once | ✅ |
| Skill reference and the implementing and reviewing skills describe the wait | ✅ |
| Tests cover met later, already met, timeout, target cancelled, daemon unavailable | ✅ |
bun run quality:fix passes |
✅ as reported by the author; not re-run here |
bun run test:changed passes |
✅ as reported by the author; not re-run here |
Docs: ADR-093 §1 "A blocking read" and daemon-cli-protocol.md "The CLI's blocking read" match the implementation (exit codes, ordering, statelessness).
Findings
🔴 Critical
None.
🟡 Important
1. A parked wait will stall the daemon's graceful shutdown until its 15-second watchdog, which then skips teardown
📁 packages/cli/src/commands/wait.rs:459 (the stream), packages/daemon/src/services/node_service.rs:2976, packages/daemon/src/main.rs:862-924
- What happens. The
WatchNodesstream ends only when the client goes away or the per-databaseshutdown_tokenis cancelled. On daemon shutdown that token is cancelled byshutdown_all, which runs afterserve_with_incoming_shutdownreturns. Tonic's graceful drain waits for every open stream first, whichmain.rsitself documents ("an open WatchNodes stream is the leading suspect"). - Consequence. With a wait parked, a SIGTERM or tray Quit waits the full
SHUTDOWN_WATCHDOG_TIMEOUTand then callsforce_exit_on_serve_drain_timeout. That isprocess::exit(0)beforedrain_and_release_gpuand before the socket file is removed. - Why it belongs here. The mechanism is pre-existing for the desktop stream. This PR makes a long-lived, unattended stream the normal state during exactly the restart the feature is meant to survive.
- What the tests cover. The restart test drops the server runtime, which models a hard kill, so this path is not exercised.
- Suggested fix. Have
watch_nodesalso select on a daemon-wide token that is cancelled when the shutdown signal fires. The wait then sees the stream end, reconnects as designed, and the drain finishes at once. - Confirm first. Run a wait against a real daemon and send it SIGTERM.
- Principle: resource lifecycle; a new long-lived client must not degrade the server's shutdown path.
2. id joins NODE_COLUMNS, but the in-Rust sort has no id arm, so the two sort passes no longer agree for that name
📁 packages/core/src/services/query_service/mod.rs:354 and :474-480
- What changed.
NODE_COLUMNSis documented as "a sort field of one of these names reads the column, never a property".resolve_sorting_with(packages/core/src/ops/query_ops.rs:594) now skips property resolution forid, andresolve_fieldorders by the column in SQL. - The gap.
compare_nodes_by_fieldmatches onlycreated_at,modified_at,content,node_typeandtitle.idfalls through to the property arm with an unresolved scope. - Consequence for most types. Both sides read
None, and the result is right only becausesort_byis stable over the SQL order. - Consequence for a user type that declares a field named
id. SQL orders and appliesLIMITby the column, then Rust re-sorts by the property. Before this PR the same sort resolved to the property in both passes. - Suggested fix. Add
"id" => a.id.cmp(&b.id), with a sort-by-idassertion next to the new filter test. - Principle: one invariant, one place.
sort_nodessays both passes must agree.
3. On a non-default database, idle eviction ends the wait's stream, and the wait reports it as a lost daemon and reopens the database every cycle
📁 packages/cli/src/commands/wait.rs:580-585, packages/daemon/src/services/database_manager.rs:1160-1185, packages/daemon/src/services/node_service.rs:2931
- What happens. A background stream takes no active claim, and a parked wait makes no RPCs. A non-default, non-foreground database is therefore evicted after the 5-minute idle window, which cancels
shutdown_tokenand ends the stream. - What the wait does. It prints "lost the daemon while waiting on ... reconnecting for up to 2m", sleeps 2 seconds, reconnects and checks.
route()reopens the database, and the cycle repeats every 5 to 6 minutes. - Correctness is fine. Any write reopens the database, and the wait subscribes before it checks.
- What is wrong. The status line misreports the cause. The wait also defeats the eviction that
backgroundwas added to leave undisturbed (ADR-053). The default database is unaffected. - Options.
- Word the stream-end line for what is known ("the change stream ended; reconnecting"), and skip the 2-second sleep on the first attempt.
- Or have a database with an open watch stream count as in use.
- Principle: accurate diagnostics; a flag's stated purpose should hold end to end.
🟢 Suggestions
4. A disconnect-coded failure right after a reconnect ends the wait with exit 1
📁 packages/cli/src/commands/wait.rs:556, :576, :597
- What happens.
answeredis reset to false after every reconnect. If the firstopen_streamor check then fails withUnavailable,Internal,UnknownorCancelled(a daemon that flaps once more), the command fails with "the wait's check failed" and exit 1. - Why it matters. The skills tell the agent to re-run only on 3 and 5, and treat 1 as "fix the command".
- Suggested fix. Treat it as another reconnect attempt inside the same
reconnect_forwindow, which keeps the loop bounded and maps to exit 5. - Likelihood. I could not construct a likely real-world trigger, so this is low priority.
- Principle: the exit status is the contract.
5. Exit codes 3 and 4 and the --json outcome object are not asserted through run
📁 packages/cli/tests/it/wait.rs:447-462
- Only exit 5 is checked through
wait::run. The 3 and 4 cases stop atOutcome. - The
OutcometoWaitEnded.codemapping and the{"outcome","reason"}output are what the skills rely on. - Two short
run-level assertions would pin them. - Principle: test the contract, not only the mechanism.
6. No bound on a check or a dial that hangs
📁 packages/cli/src/commands/wait.rs:552, :514
--timeoutis only observed while parked on the stream.- A daemon that accepts a request but never answers holds the wait past its deadline.
- Wrapping the check and
connectintimeout_at(deadline)closes it.
Nits
- Nit: 📁
packages/agent/src/local_agent/tools.rs:1190,:2559. The local agent's tool description lists the metadata fields as "the 4 built-in fields created_at, modified_at, node_type, content". It already omittedtitleand now omitsid, whilecli.mdwas updated. - Nit: 📁
packages/cli/src/commands/wait.rs:401-404. A mistyped saved-query title at start exits 4 with "no longer exists". "was not found" would read correctly in both cases. - Nit: A node whose type default queries leave out, or an archived node, never matches and runs to the timeout. The PR notes the archived case. A line in
cli.mdwould save an agent a 3-hour wait.
Recommendation
APPROVE
The command is a net improvement, the wait loop and its tests are sound, and it matches the ADR-093 contract. Findings 1 to 3 are recommended before merge and are not blockers. Finding 2 is a one-line fix. Finding 1 should be confirmed against a real daemon first.
🤖 Generated with Claude Code
malibio
left a comment
There was a problem hiding this comment.
Automated pragmatic-code-review: APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.
Review addressed (commit 4e0cbfe)Addressed
Skipped
Note. |
Pragmatic Code Review: PR #3737 (
|
| # | Previous finding | Status |
|---|---|---|
| 1 | Parked wait stalls the daemon's graceful shutdown | Addressed |
| 2 | In-Rust sort has no id arm |
Addressed (test note in finding 2 below) |
| 3 | Evicted database reported as a lost daemon | Addressed (wording and immediate first attempt) |
| 4 | Flap after a reconnect ends as exit 1 | Not addressed as claimed: the new outage bound does not hold, and it introduced finding 1 |
| 5 | Exit codes and --json object not asserted |
Addressed (each_ending_has_its_own_exit_status_and_json_outcome) |
| 6 | No bound on a hung check or dial | Partly addressed: the check is bounded; open_stream and connect are not |
| Nits | "does not exist", archived-node sentence in cli.md |
Addressed |
| Skipped | Local agent tool description; counting a background stream as in use | Both reasons are sound |
New issues: one Critical (finding 1), two Suggestions.
What I verified
- All four serve functions pass the token. Each has
sharedin scope frombuild_shared_services, and passesshared.context.serving_ended.clone()as the second argument, matching the new signature(shutdown_future, serving_ended, timeout, on_timeout). That includes the two Windows-only ones (packages/daemon/src/main.rs:1970,:2080). - The manager shares the same token.
open_default_databasegetsshared.context.clone(), and a clonedCancellationTokenshares its state, sobuild_database_services'sshared.serving_ended.child_token()is a child of the onemain.rscancels. - Nothing else relied on the per-database token being independent. Its only reader is the
WatchNodesselect (packages/daemon/src/services/node_service.rs:2978).DatabaseServices::shutdowncancelling a child does not touch the parent or its siblings. The local agent'sshutdown_tokenis a separate token. - A database opened after cancellation behaves sanely. Its child token is born cancelled, so a stream on it ends at once and every other RPC works. The accept loop has already stopped by then.
- The desktop watcher does not spin. A clean stream end resets its backoff but still sleeps before reopening (
packages/desktop-app/app-lib/src/watcher.rs:239). - Cancelling a check at the deadline leaves no wrong state.
check_querysetsbaselinesynchronously after its lastawait, and the wait returnsTimedOutstraight after the cancellation. lost_sinceis cleared where it should be.Pendingclears it;MetandUnreachablereturn.
Findings
🔴 Critical
1. A wait can loop forever, past reconnect_for and past --timeout, when the daemon accepts connections but keeps failing with a disconnect-like code
📁 packages/cli/src/commands/wait.rs:541-561 (reconnect), :629 (the open_stream arm), :644-645
- The gap.
reconnectreadsgive_uponly after a failedconnect. Whenconnectsucceeds it returns the client without looking atgive_upor the deadline. - The loop. With
ever_answerednow sticky, a disconnect-coded failure fromopen_streamgoes back toreconnectevery time.lost_sincestays set, so each pass sleepsreconnect_every, connects, fails, and repeats. Nothing on that path readsgive_upordeadline. - A concrete trigger.
is_disconnectincludesCode::Internal, and the routing layer returnsStatus::internalfor a database it cannot open (packages/daemon/src/db_routing.rs:85). Two ways to get there:- The daemon restarts into a version that refuses the database as another version's. That is the restart this feature is meant to survive.
- A non-default database is evicted after its idle window and then cannot be reopened (file moved or locked).
- Consequence. The wait prints one line, then retries every 2 seconds without end. It never exits 3 or 5, and the daemon's message saying why the database will not open is never shown again.
- The check path is only half bounded. A persistent disconnect-coded failure from
target.checkdoes end at the deadline (exit 3) throughtimeout_at, but not atreconnect_for, so the comment at:588-591and the commit message's claim do not hold there either. - This is a regression in this commit. Before it,
answered = falseafter a reconnect made the same failure exit 1 with the daemon's message. - Suggested fix. In
watch, before callingreconnect, end the wait whenInstant::now() >= give_up(asTimedOutif the deadline has passed, otherwiseDaemonUnavailablecarryingstatus_text(&disconnected)so the reason is visible). Wrappingopen_streamandconnectintimeout_at(deadline)closes the rest of previous finding 6. - Test. A fake daemon that answers one check, then returns
InternalfromWatchNodes, with a shortreconnect_for, should end asDaemonUnavailable. - Principle: a blocking command's exit contract. Every loop needs a bound that does not depend on the peer's behaviour.
🟡 Important
None.
🟢 Suggestions
2. The sort-by-id assertion passes with or without the new arm
📁 packages/core/src/ops/query_ops.rs:2524-2536
- For a
task, the old fall-through readNoneon both sides, and the stable re-sort kept the SQL order. The assertion therefore does not fail if theidarm incompare_nodes_by_fieldis removed. - The case the arm fixes is a type that declares its own field named
id. A test on such a type, where the property order differs from the column order, would pin it. - The arm itself is correct. This is about the test's value, not the fix.
- Principle: a test should fail when the change it covers is reverted.
3. Nothing spaces out successive immediate reconnects
📁 packages/cli/src/commands/wait.rs:603-608, :633
- A
Pendingcheck clearslost_since, so the next stream end reconnects at once again. If a daemon answers checks but ends each new stream immediately, the wait dials, subscribes and checks in a tight loop. - I could not construct a trigger with the current daemon: after
serving_endedis cancelled the accept loop is closed, and eviction gives the reopened database a fresh token. So this is defensive only. - A cheap guard is to reconnect at once only when the stream that just ended had lived at least
reconnect_every. - Principle: a client's retry rate should not be set by the server alone.
Nits
- Nit: 📁
packages/daemon/src/main.rs:838-842,:924-927. The doc comment and the forced-exit log line still name an openWatchNodesstream as the leading suspect for a stalled drain. After this commit that cause is removed, and a long in-flight request is what remains. - Nit: 📁
packages/cli/src/commands/wait.rs:242.from_outcomemapsOutcome::Met(_)to the timeout ending. It is unreachable fromrun, but a caller that passed it would get a silent exit 3.
Recommendation
REQUEST CHANGES
The daemon-side fix is correct and well tested, and findings 2, 3 and 5 of the first review and the nits are properly addressed. Finding 1 blocks: the reworked outage tracking lets the command run past its own --timeout without end, with a trigger that sits on the restart path the feature exists for. The fix is a few lines in watch plus one test.
🤖 Generated with Claude Code
malibio
left a comment
There was a problem hiding this comment.
Automated pragmatic-code-review (re-review): REQUEST CHANGES (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.
Re-review addressed (commits 9c98ea0 and the one after it)
Rust workspace suite: 5256 passed. |
Pragmatic Code Review: PR #3737 (
|
| # | Previous finding | Status |
|---|---|---|
| 1 (Critical) | Wait loops forever when the daemon takes connections but fails every request | Addressed |
| 2 (Suggestion) | Sort-by-id test passed with or without the arm |
Addressed |
| 3 (Suggestion) | Nothing spaced out successive immediate reconnects | Addressed |
| Nit | Forced-exit log line named WatchNodes streams |
Addressed |
| Nit | from_outcome's Met arm |
Declined; the reason is sound (private, one caller) |
New issues: none blocking. Two Suggestions.
Path walk (packages/cli/src/commands/wait.rs:541-673)
| Path | What ends it | Outcome |
|---|---|---|
(a) connect fails forever |
reconnect reads give_up after each failed dial (:557) |
Exit 5, or exit 3 when the deadline is the nearer bound |
(b) connect succeeds, open_stream fails disconnect-like forever |
lost_since stays set, so began is fixed; watch reads give_up before each reconnect (:653); each pass sleeps reconnect_every because first is false |
Exit 5 with the daemon's status in the reason, or exit 3 at the deadline |
(c) open_stream succeeds, check fails disconnect-like forever |
Same as (b): break status reaches the same give_up test, and only a Pending check clears lost_since |
Exit 5 with the daemon's status, or exit 3 |
| (d) Everything succeeds, stream ends at once every time | Each Pending starts a new outage, so reconnect_for never applies; the deadline does (sleep_until at :619, timeout_at at :596 and :603, and give_up is capped at the deadline). at_once is false for a stream that lived under reconnect_every, so the pace is one cycle per reconnect_every |
Exit 3 at the deadline |
(e) open_stream or check hangs |
timeout_at(deadline) on both |
Exit 3 at the deadline |
Normal paths:
- A real restart is survived. The stream ends,
reconnectretries until the dial succeeds, the wait subscribes and then checks, and aPendingcheck clears the outage.a_wait_survives_a_daemon_restart_and_sees_what_changed_meanwhilepasses. - A first-time failure still fails the command.
ever_answeredis false until a check is answered, so bothopen_streamand check errors go tocheck_failedwith the daemon's message (:615,:635).a_filter_the_daemon_rejects_fails_the_commandpasses. - Exit 3 versus 5 is right at the boundary. When the deadline is the nearer bound,
give_upequals it, and theNonearm tests the deadline first. - One connect past
give_upis harmless.reconnectreturns a client without readinggive_up, but the next failure reaches the test at:653.
Findings
🔴 Critical
None.
🟡 Important
None.
🟢 Suggestions
1. During an outage, a hung request runs to --timeout, not reconnect_for
📁 packages/cli/src/commands/wait.rs:596, :603, :554
open_streamand the check are bounded bydeadlineonly. A daemon that comes back, takes the request and never answers holds the wait until--timeout(exit 3), where the outage bound would have ended it sooner as exit 5.- The dial in
reconnect(and the first one at:580) has no time bound at all. I could not construct a hang on a local socket, so this is defensive. - Bounding the three by
give_upwhilelost_sinceis set would makereconnect_forhold for every way the daemon can fail to answer. The wait is bounded either way, so this does not block. - Principle: one bound per contract.
reconnect_forshould not depend on how the peer fails.
2. Path (d) prints two lines per cycle until the timeout
📁 packages/cli/src/commands/wait.rs:609-611, :640-648
- A daemon that answers checks but ends every stream at once makes the wait print "the change stream ended ... reconnecting" and "reconnected; still waiting" every
reconnect_every(2s by default) until--timeout. - The previous review found no trigger for this with the current daemon, and that still holds. Noted only because the retry is now paced but its output is not.
Tests
- 📁
packages/cli/tests/it/wait.rs:521a_daemon_that_returns_but_fails_every_request_ends_the_wait: exercises path (b) through a real tonic server with aRefusinginterceptor, and asserts both the outcome and that the reason carries the daemon's message. It covers the regression. - 📁
packages/core/src/ops/query_ops.rs:2542a_sort_by_id_reads_the_column_on_a_type_with_an_id_field: the property values order the two nodes opposite to their ids, so the assertion depends on theidarm in the in-Rust sort. By reading it, it fails when the arm is removed; I did not run that.
Recommendation
APPROVE
The Critical is fixed: every path through watch now ends at reconnect_for or the deadline, with the outcome the skills expect, and the test pins the case that looped. The two Suggestions are optional.
🤖 Generated with Claude Code
malibio
left a comment
There was a problem hiding this comment.
Automated pragmatic-code-review (re-review 2): APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.
Second re-review addressedVerdict was APPROVE with two optional Suggestions, both declined:
No code changed in this pass. No re-review needed. |
…ges (closes #3723) A CLI command over the daemon's change stream: wait node <id> --until <filters> [--unless <filters>] and wait query <id|title> [--until change|gain|loss|not-empty | --item <id>]. Exits 0 when the condition holds, 3 on timeout, 4 when it can no longer be reached, 5 when the daemon is unavailable; a daemon restart is survived. A metadata filter can name a node's id, so a filter set is asked of one node. A background watch stream takes no active-database claim. The implementing and reviewing skills and the CLI reference describe the wait. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…by id - The daemon ends every open WatchNodes stream when it is told to stop, before tonic drains: a parked wait (or any connected window) held the drain until the 15s watchdog forced the exit and skipped teardown. Confirmed on a real daemon before and after. - An outage is bounded by reconnect_for from when it began, so a daemon that flaps after a reconnect ends as exit 5, not exit 1. The first reconnect attempt is immediate, and the status line says the stream ended. - A check is bounded by the wait's deadline. - The in-Rust sort has an id arm, matching the SQL ordering. - The outcome-to-exit-status mapping and the --json object are tested. - Unreachable reasons read 'does not exist'; the reference says an archived node waits until the timeout. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…emon answers - A daemon that takes connections but fails every request with a disconnect-like status (one that cannot open the database) kept the wait retrying without end, past reconnect_for and --timeout. The outage bound is now checked before each reconnect, opening the stream is bounded by the deadline, and the exit-5 reason carries what the daemon answered. New test, shown to fail with the bound removed. - The first reconnect is immediate only after a stream that lasted. - The sort-by-id test uses a type that declares its own id field, and fails without the sort arm. - The forced-exit log line no longer blames WatchNodes streams. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
347b79a to
61c9ddd
Compare
Closes #3723
What
nodespace waitblocks until a node or a saved query's result changes in a stated way, then prints it and exits. A session that hands work to someone else starts it in the background and is resumed by its harness when it exits.gained/lost, is on stdout--timeoutpassed--itemnode gone, or the node matches--unlessHow
nodespace querytakes, run as a query narrowed to that one node. For that, a metadata filter can now nameid(NODE_COLUMNS).WatchNodes, not a timer. The command opens the stream, checks, then waits for events, so a change between the check and the first event is seen. After an event it takes every event already delivered and checks once.WatchRequestgainsbackground: such a stream takes no active-database claim, so opening or closing a wait never moves embedding priority or eviction immunity away from the window on that database.statusis no longerin_review, stated by the skill.--json, exits 3, 4 and 5 print{"outcome", "reason"}.Skills and docs
references/cli.md: a "Wait for a change" section with the exit-status table, and the generated command surface.architecture/daemon-cli-protocol.md.Scope notes
in_reviewback toin_progress, ordone). Adapt the community implement and review workflows into NodeSpace delivery skills: test-first, review by a separate session, a decision per finding #3720 rewrites those skills and should carry the wait step over with its new statuses.Tests
packages/cli/tests/it/wait.rs(13): met later, already met, timeout with status lines,--unless, deleted and missing node, rejected filter, daemon not running (outcome and exit status), daemon gone for good, daemon restart with a change made while disconnected, query gain / loss /not-empty/--item, deleted saved query and item, argument parsing.idasks the other filters of one node. Daemon: a background stream neither takes nor releases the active claim.bun run test:changedpasses (rust, skill, scripts tiers).🤖 Generated with Claude Code