Skip to content

Raise the gRPC message-size limit and stop diagnostics reporting a failed query as zero - #2294

Merged
mstomar125 merged 1 commit into
mainfrom
issue-2286-grpc-message-size
Aug 25, 2026
Merged

mstomar125 merged 1 commit into
mainfrom
issue-2286-grpc-message-size

Conversation

@mstomar125

Copy link
Copy Markdown
Contributor

Closes #2286

Root cause

Confirmed: a client-side receive-limit problem, not a server-side send problem.

tonic 0.12 defaults max_decoding_message_size to 4 MiB and max_encoding_message_size to usize::MAX (tonic-0.12.3/src/codec/mod.rs, DEFAULT_MAX_RECV_MESSAGE_SIZE / DEFAULT_MAX_SEND_MESSAGE_SIZE). Nothing in this repo configured either value on any client or server — so the daemon happily encoded and sent the 8.9 MB QueryNodesSimple response, and the CLI refused to decode it:

status: OutOfRange, message: "Error, decoded message length too large: found 8933414 bytes, the limit is: 4194304 bytes"

QueryNodesSimple is not special. Every list-shaped RPC in node_service.proto returns each matching node's full record in one unary message and has the same wall: GetRoots, GetChildren, GetChildrenTree, SearchNodes, GetCollectionMembers, GetCollectionMembersRecursive, MentionAutocomplete, ExecuteQuery, GetAllSchemas, GetNodesBatch, ExportMarkdown, GetMentioningRoots, GetAllCollections.

The "Total nodes: 0" is a second, independent defect: collect() substituted Vec::new() for the failed query, so a transport failure became an authoritative-looking zero. The diagnostics Errors: section did its job — the number above it did not.

Changes

Message-size limits — one constant, applied everywhere

  • nodespace-proto gains MAX_MESSAGE_SIZE_BYTES (64 MiB) and a with_message_limits! macro. tonic configures limits per generated stub, not on the shared Channel/Server, and each stub is a distinct type with no common trait — hence a macro rather than a function.
  • Applied to: every daemon service stub in build_base_router, all five CLI clients, all desktop-app clients across from_channel / set_active_database / swap_channel, the desktop app's CloudSyncServiceClient, and the dev-proxy's grpc-js channel options (grpc-js has the same 4 MiB default; browser mode should fail exactly where the packaged app does).
  • Both directions on both ends, so the threshold is symmetric: a message too large fails at the sender with a clear encode error rather than after crossing the socket.

Why 64 MiB and not pagination: the transport is a local UDS/Named Pipe between processes owned by the same user, and the daemon already holds the same records in memory to build the response, so the limit bounds memory rather than defending a trust boundary. The observed real-world response was 8.9 MB from a 63.5 MB database — 64 MiB leaves roughly an order of magnitude of headroom. It is a ceiling, not a bound; see the follow-up below.

Diagnostics stops reporting a failed query as zero

  • total_node_count, root_node_count, schema_count and recent_node_ids are now Option. A failed query leaves them None — deliberately not an empty Vec — and the human output prints unknown (query failed — see Errors below) while JSON emits null.
  • nodespace diagnostics now exits non-zero when the report carries any error, so a partial report can't read as a clean run to a script or to someone skimming the tail of the output.
  • Truncation at QUERY_LIMIT moved out of errors into a new warnings list, so a non-empty errors now means something actually failed.

Desktop app

Same root cause, fixed in the same PR rather than split out. The desktop app's bulk-fetch paths are Tauri commands over the same tonic client bundle — get_children_tree (a whole date page's subtree in one message, called on every page load via backend-adapter.ts), get_all_collections, get_collection_members, get_collection_members_recursive. On a large real database those would have hit the identical 4 MiB OutOfRange and surfaced as an empty view. Configuring GrpcClient covers all of them; there was no second, frontend-specific limit to raise (the webview receives this data over Tauri IPC, which has no such cap).

Tests

Two new integration tests in packages/cli/tests/cli_integration.rs:

  • query_nodes_simple_handles_response_over_the_default_grpc_limit — seeds 90 × 60 KB nodes (~5.1 MB of content), then asserts both halves: a client clamped back to tonic's 4 MiB default fails with OutOfRange (so the fixture can't silently stop exceeding the limit and make the test vacuous), and the client the CLI actually builds reads the whole response.
  • diagnostics_reports_unknown_counts_when_the_node_query_fails — drives collect() and run() through a client with a starved decode limit and asserts unknown counts, unknown recency, the underlying failure surfaced in errors, and a non-zero exit from run().

Results: cargo test -p nodespace-cli -p nodespace-daemon -p nodespace-proto — all green (27 CLI integration + 168 daemon unit + the rest). bun run quality:fix clean: eslint 0 errors, svelte-check 0 errors/0 warnings across 2295 files, cargo clippy --all-targets -- -D warnings clean.

Follow-up

#2289 — raising the ceiling doesn't bound anything. The list RPCs should get a count-only path (diagnostics pulls up to 100,000 full records to print one number) and a cursor contract. That needs SqliteStore::query_nodes to gain a deterministic ORDER BY first: it currently builds SELECT * FROM node … LIMIT n OFFSET m with no ordering, so offset-paging it today can skip or duplicate rows.

Note for nodespace-sync: nodespaced-pro chains its own .add_service(CloudSyncServiceServer::new(…)) onto build_base_router. That stub keeps tonic's 4 MiB decode default unless it is wrapped in with_message_limits! too — the build_base_router doc example now shows this. Its responses are unaffected (send is unlimited by default, and the desktop-side client is configured here), so nothing is broken today.

…iled query as zero

tonic (and grpc-js) default the decode limit to 4 MiB, which several
list-shaped RPCs exceed on a real database: `QueryNodesSimple`,
`GetRoots`, `GetChildrenTree`, `GetCollectionMembers*` and friends each
return every matching node's full record in one unary message. Nothing
configured that limit anywhere, so a multi-megabyte response failed with
`OutOfRange` on the client's decode step.

- Add `MAX_MESSAGE_SIZE_BYTES` (64 MiB) and a `with_message_limits!`
  macro to `nodespace-proto`. tonic configures the limit per generated
  stub rather than on the shared channel/server, and each stub is a
  distinct type with no common trait, hence a macro.
- Apply it to every daemon service stub in `build_base_router`, every
  CLI client, every desktop-app client (including the Pro client), and
  the dev-proxy's grpc-js channel options.
- Make `nodespace diagnostics` report unknown rather than zero when the
  query behind a figure fails: the count/recency fields become `Option`,
  the human and JSON output render `unknown` / `null`, and the command
  exits non-zero so a partial report can't read as a clean run.
- Split truncation-at-`QUERY_LIMIT` out of `errors` into a new
  `warnings` list, so a non-empty `errors` means something actually
  failed.

Tests: a CLI integration test seeds a >4 MiB `QueryNodesSimple` response
and asserts a client left on tonic's default fails with `OutOfRange`
while the configured client reads it in full; a second drives `collect`
and `run` through a starved client and asserts unknown counts plus a
non-zero exit.

Co-Authored-By: Claude <[email protected]>
@mstomar125

Copy link
Copy Markdown
Contributor Author

Self-review

Adversarial pass over my own diff. Not a substitute for review — core policy requires a second pair of eyes, so this stays open.

Verified against the vendored source, not memory. The claim that tonic's decode default is 4 MiB and its encode default is unlimited is checked against ~/.cargo/registry/.../tonic-0.12.3/src/codec/mod.rs (DEFAULT_MAX_RECV_MESSAGE_SIZE = 4 * 1024 * 1024, DEFAULT_MAX_SEND_MESSAGE_SIZE = usize::MAX). That asymmetry is what makes this a client-side receive bug: the daemon sent the 8.9 MB response without complaint.

The macro is the part I'd push back on hardest. A macro to set two builder methods is unusual. The reason it isn't a function: tonic puts max_decoding_message_size on each generated stub type, and those types share no trait — NodeServiceClient, NodeServiceServer, SettingsServiceClient etc. have identical method names and no common bound, so a generic helper can't be written without adding a trait of our own. With ~30 construction sites across four crates, inlining the constant at each was the alternative, and drift there is silent (a stub that misses the call keeps 4 MiB and fails only on a large database). If a reviewer prefers the explicit form, it's a mechanical change.

Things a reviewer should push on:

  1. Is 64 MiB the right number? It's a judgement call, and the doc comment says so. Observed: 8.9 MB response from a 63.5 MB database. 64 MiB is ~7x that. Bigger costs memory in both processes; smaller re-opens the same failure sooner. I'd rather be argued down to 32 MiB than up to 256 MiB.
  2. Client encode is now capped where it previously wasn't. Client send defaulted to usize::MAX; it is now 64 MiB. I checked that no RPC in this contract sends a payload near that (imports pass paths, not file contents; model downloads and chat are streams; the previous server-side decode cap was 4 MiB, so anything over that already failed). Still, this is the one place the change can only make something stricter, so it deserves a second look.
  3. diagnostics now exits non-zero. This is a behavior change for any script parsing its output. I believe that's the point — the issue is precisely that a failed run looked successful — but if something in CI consumes nodespace diagnostics --json and checks the exit code, it will start failing where it used to pass silently on a partial report.
  4. Truncation moved from errors to a new warnings list. Deliberate: with run now failing on non-empty errors, leaving the truncation notice there would make a very large (but healthy) database exit non-zero. The tradeoff is one more field on the JSON contract.

What the tests actually prove. query_nodes_simple_handles_response_over_the_default_grpc_limit asserts both directions on purpose — a test that only checked the success path would keep passing if the fixture ever stopped exceeding 4 MiB, and would then be proving nothing. The OutOfRange half is the guard against that. Note the seeded node count is compared against a pre-seed baseline because the daemon bootstraps its own nodes; asserting an exact total would have been wrong.

What I did not do. No pagination. QueryNodesSimple already takes limit/offset, so paging looks free — but SqliteStore::query_nodes emits SELECT * FROM node … LIMIT n OFFSET m with no ORDER BY, so offset-paging it today can skip or duplicate rows. Making that safe means giving the store a deterministic order, which changes every existing caller and belongs in its own change: filed as #2289 along with the count-only RPC that would let diagnostics stop pulling 100,000 full records to print one number.

Not validated against a real large database. The reproduction in the issue used a 63.5 MB historical database that I don't have here; the evidence in this PR is the synthetic >4 MiB response in the integration test. The arithmetic says 64 MiB covers roughly a 450 MB database at the observed response-to-database ratio, but that ratio is one data point.

@mstomar125
mstomar125 merged commit b4791e8 into main Aug 25, 2026
@mstomar125
mstomar125 deleted the issue-2286-grpc-message-size branch August 25, 2026 08:47
malibio added a commit that referenced this pull request Sep 8, 2026
* Bound GetChildrenTree's subtree payload with an actionable error (closes #2108)

The rest of #2108's issues were already fixed by #2294/#2319 (unknown-vs-zero
diagnostics fallbacks, count-only RPCs, bounded ordered recent-node query, and
the configured 64MiB gRPC message-size ceiling). The one remaining defect: on
the app's hot path for opening a document, get_children_tree still built and
serialized an entire subtree into one JSON payload with no node-count bound —
only depth is guarded (MAX_TREE_DEPTH). A wide-but-shallow subtree (many
siblings under one parent) can still produce a message the gRPC transport
rejects with an opaque OutOfRange at decode time.

The frontend eagerly loads a document's full tree in one call with no
lazy-expand fallback (shared-node-store.svelte.ts's loadChildrenTree), so
truncating the response would silently drop content rather than degrade
gracefully. Per the issue's stated preference, state and enforce a maximum
document size instead:

- Add MAX_TREE_NODES (20,000) next to the existing MAX_TREE_DEPTH guard in
  node_service/mod.rs, checked in get_children_tree before the tree is built.
- Add NodeServiceError::TreeTooLarge -> OpsError::TreeTooLarge -> a
  RESOURCE_EXHAUSTED gRPC status carrying node_id/count/max in metadata
  (mirrors the SubtreeAccessDenied FAILED_PRECONDITION pattern), so a caller
  gets a specific, actionable failure instead of a raw transport decode error.
- Regression tests: core-level tests seeding a subtree just over/at the limit
  (gated behind RUN_LONG_TESTS, matching the existing large-subtree test
  convention — this seeds 20k+ nodes and takes ~80s), and a fast daemon-level
  unit test asserting the status code and metadata.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KavcAieXx31wYVQfjz1wk6

* Address review: clarify short-circuit scope and heuristic nature of MAX_TREE_NODES

Comment-only changes from pragmatic-code-review on PR #2493 (both Suggested
Improvements, non-blocking):

- hierarchy.rs: clarify the MAX_TREE_NODES check only skips the remaining
  mention-lookup and tree-build/serialization, not the DB fetch that already
  ran in get_subtree_data — that fetch is one consolidated query and can't be
  split into count-then-fetch without a schema/query change.
- mod.rs: note MAX_TREE_NODES is a heuristic node-count cap, not a guaranteed
  byte ceiling, since per-node content/properties size is still unbounded.
  Accepted deliberately given typical nodes are short text/task fragments,
  rather than adding a byte-accumulation pass to close the residual case.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KavcAieXx31wYVQfjz1wk6

---------

Co-authored-by: Claude Sonnet 5 <[email protected]>
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.

QueryNodesSimple exceeds gRPC's 4MB message-size limit on large databases, and the failure is silently misreported (diagnostics shows 'Total nodes: 0')

1 participant