diff --git a/.changeset/mcp-offset-bound.md b/.changeset/mcp-offset-bound.md new file mode 100644 index 000000000..a845151cc --- /dev/null +++ b/.changeset/mcp-offset-bound.md @@ -0,0 +1,2 @@ +--- +--- diff --git a/crates/nostream-mcp/src/lib.rs b/crates/nostream-mcp/src/lib.rs index 4dce3fe9f..65a260a53 100644 --- a/crates/nostream-mcp/src/lib.rs +++ b/crates/nostream-mcp/src/lib.rs @@ -35,12 +35,12 @@ pub use credential::{ pub use error::McpError; pub use server::{ AUDIT_DENIED, AdminMcp, DeleteEventArgs, FORBIDDEN, GetEventArgs, InvoicesGetArgs, - InvoicesListArgs, ListEventsArgs, MAX_FILTER_TERMS, MAX_ROWS_PER_PAGE, MCP_INSTRUCTIONS, - MCP_SERVER_NAME, NOT_FOUND, OUTCOME_ALREADY_DELETED, OUTCOME_DELETED, OUTCOME_NOT_DELETEABLE, - OUTCOME_NOT_FOUND, ReportAction, ReportsActionArgs, ReportsListArgs, Requires, SettingsSetArgs, - TOOL_DELETE_EVENT, TOOL_GET_EVENT, TOOL_INVOICES_GET, TOOL_INVOICES_LIST, TOOL_LIST_EVENTS, - TOOL_MAINTENANCE_LAST_RUN, TOOL_MAINTENANCE_RUN, TOOL_RELAY_STATUS, TOOL_REPORTS_ACTION, - TOOL_REPORTS_LIST, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, TOOL_USER_ADMIN, TOOL_USER_GET, TOOLS, - Tool, UNAUTHORIZED, UserAction, UserAdminArgs, UserGetArgs, arguments_parse, audit_action, - required_scope, + InvoicesListArgs, ListEventsArgs, MAX_FILTER_TERMS, MAX_ROWS_PER_PAGE, MAX_ROWS_PER_SKIP, + MCP_INSTRUCTIONS, MCP_SERVER_NAME, NOT_FOUND, OUTCOME_ALREADY_DELETED, OUTCOME_DELETED, + OUTCOME_NOT_DELETEABLE, OUTCOME_NOT_FOUND, ReportAction, ReportsActionArgs, ReportsListArgs, + Requires, SettingsSetArgs, TOOL_DELETE_EVENT, TOOL_GET_EVENT, TOOL_INVOICES_GET, + TOOL_INVOICES_LIST, TOOL_LIST_EVENTS, TOOL_MAINTENANCE_LAST_RUN, TOOL_MAINTENANCE_RUN, + TOOL_RELAY_STATUS, TOOL_REPORTS_ACTION, TOOL_REPORTS_LIST, TOOL_SETTINGS_GET, + TOOL_SETTINGS_SET, TOOL_USER_ADMIN, TOOL_USER_GET, TOOLS, Tool, UNAUTHORIZED, UserAction, + UserAdminArgs, UserGetArgs, arguments_parse, audit_action, required_scope, }; diff --git a/crates/nostream-mcp/src/server.rs b/crates/nostream-mcp/src/server.rs index 20d5dd2d7..ec9728572 100644 --- a/crates/nostream-mcp/src/server.rs +++ b/crates/nostream-mcp/src/server.rs @@ -105,6 +105,21 @@ pub const MAX_FILTER_TERMS: usize = 64; /// takes a direction from `limit`. pub const MAX_ROWS_PER_PAGE: u64 = nostream_storage::DEFAULT_PAGE_ROWS; +/// The most rows an `invoices_list` call may skip: this door's own ceiling, 5,000 rows. +/// +/// The skip is linear in the rows it passes and then saturates at the pending set, so an +/// arbitrarily large offset costs a whole index walk for an answer that may be empty. Over 20,000 +/// pending rows it measured 0.941 ms at `offset: 5_000` with `limit: 0` (the skip loop alone, +/// best of five), against 7.936 ms for the 500-row page at offset 0 and 1.562 ms at `u64::MAX`. +/// A ceiling at this door's own page ([`MAX_ROWS_PER_PAGE`]) was rejected because at `limit: 500` +/// it leaves a caller two pages deep; 5,000 leaves eleven. +/// +/// The magnitude matches [`nostream_storage::MAX_PAGE_ROWS`], the relay's largest event page — +/// the largest single page the tree already asks a backend to answer — and it is measured against +/// that clamp rather than derived from it: the invoice read has no page bound of its own, and a +/// relocation of the relay's event page must not move this door's published `maximum`. +pub const MAX_ROWS_PER_SKIP: u64 = 5_000; + /// The refusal for a credential whose document is absent, unreadable or no longer a document this /// door accepts — the HTTP gate's `401`. pub const UNAUTHORIZED: &str = "Unauthorized"; @@ -497,7 +512,8 @@ pub struct UserGetArgs { #[derive(Debug, Clone, Default, Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] pub struct InvoicesListArgs { - /// Rows to skip, oldest first; absent skips none. + /// Rows to skip, oldest first; absent skips none; at most 5000. + #[schemars(range(min = 0, max = MAX_ROWS_PER_SKIP))] pub offset: Option, /// Page size: 1 to 500 rows, oldest first; absent uses 500. #[schemars(range(min = 1, max = 500))] @@ -793,7 +809,8 @@ the relay has not cached and the door has never written reads as absent. Changes description = "List the pending invoices, oldest first, paged by `offset` and `limit` — \ the store's own pending walk, so a completed or expired invoice is not here and `invoices_get` \ is how to read one whatever its status. `limit` is 1 to 500 rows, absent 500; `offset` skips \ -that many. A confirmed invoice stays in this list while its status reads `pending`" +that many, and at most 5000. A confirmed invoice stays in this list while its status reads \ +`pending`" )] async fn invoices_list( &self, @@ -981,11 +998,12 @@ maintenance worker runs in another process and its passes are not visible here" /// decide either (R12). async fn pending_invoices(&self, arguments: &InvoicesListArgs) -> Result { let limit = page_bound(arguments.limit)?; + let offset = offset_bound(arguments.offset)?; let invoices = self .state .stores() .invoices - .find_pending_invoices(arguments.offset.unwrap_or(0), limit) + .find_pending_invoices(offset, limit) .await?; Ok(json!({ "invoices": invoices })) } @@ -1174,6 +1192,21 @@ fn page_bound(limit: Option) -> Result { }) } +/// The skip a call asks for, checked against the bound its `inputSchema` states (R12, D3). +/// +/// An absent offset skips none. Anything past [`MAX_ROWS_PER_SKIP`] is refused here, before the +/// repository call, so the walk's cost is bounded at the door rather than by the pending set. +fn offset_bound(offset: Option) -> Result { + let offset = offset.unwrap_or(0); + (offset <= MAX_ROWS_PER_SKIP) + .then_some(offset) + .ok_or_else(|| { + McpError::Criterion(format!( + "offset: a walk skips at most {MAX_ROWS_PER_SKIP} rows, {offset} was given" + )) + }) +} + /// The events' page size, from the one bound. fn page_size(criteria: &ListEventsArgs) -> Result { // The bound caps the page at `MAX_ROWS_PER_PAGE`, so this conversion cannot narrow. diff --git a/crates/nostream-mcp/tests/fixtures/tools_list.json b/crates/nostream-mcp/tests/fixtures/tools_list.json index a88cb8b43..80625cfa4 100644 --- a/crates/nostream-mcp/tests/fixtures/tools_list.json +++ b/crates/nostream-mcp/tests/fixtures/tools_list.json @@ -55,7 +55,7 @@ "name": "invoices_get" }, { - "description": "List the pending invoices, oldest first, paged by `offset` and `limit` — the store's own pending walk, so a completed or expired invoice is not here and `invoices_get` is how to read one whatever its status. `limit` is 1 to 500 rows, absent 500; `offset` skips that many. A confirmed invoice stays in this list while its status reads `pending`", + "description": "List the pending invoices, oldest first, paged by `offset` and `limit` — the store's own pending walk, so a completed or expired invoice is not here and `invoices_get` is how to read one whatever its status. `limit` is 1 to 500 rows, absent 500; `offset` skips that many, and at most 5000. A confirmed invoice stays in this list while its status reads `pending`", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, @@ -71,8 +71,9 @@ ] }, "offset": { - "description": "Rows to skip, oldest first; absent skips none.", + "description": "Rows to skip, oldest first; absent skips none; at most 5000.", "format": "uint64", + "maximum": 5000, "minimum": 0, "type": [ "integer", diff --git a/crates/nostream-mcp/tests/store_families.rs b/crates/nostream-mcp/tests/store_families.rs index cadb3906c..e6c90dd4f 100644 --- a/crates/nostream-mcp/tests/store_families.rs +++ b/crates/nostream-mcp/tests/store_families.rs @@ -16,7 +16,8 @@ //! | `a_short_pubkey_is_refused_after_its_dispatch_line` | a prefix is refused by the length check before any store call, and its dispatch line exists | //! | `a_read_only_document_reads_and_is_refused_the_user_write` | the four reads answer under a document that grants nothing, the write is denied and recorded, and no row is written | //! | `invoices_list_is_the_pending_walk_oldest_first` | the list is the store's pending index, not a status filter: an expired row is absent and still readable by id | -//! | `invoices_list_pages_by_offset_and_refuses_a_page_outside_the_bound` | `offset`/`limit` are the store's own page, and 0 and 501 are the one refusal | +//! | `invoices_list_pages_by_offset_and_refuses_a_page_outside_the_bound` | `offset`/`limit` are the store's own page, 0 and 501 are the one refusal, and the skip ceiling refuses 5001 and serves 5000 | +//! | `invoices_list_serves_the_page_at_the_offset_ceiling` | the page at the ceiling is served, and the bound is on `offset`, not on `offset + limit` | //! | `invoices_get_answers_the_row_and_a_miss_is_null` | the thirteen fields, and a miss as a result — an id that is 64 hex characters is no different | //! | `a_confirmed_invoice_still_reads_pending` | confirmation sets the paid fields and leaves the status, and the list keeps naming the row | //! | `reports_list_is_the_actionable_queue_newest_first` | the queue is `find_actionable`: newest first, and a report an operator allowed is not in it | @@ -35,8 +36,8 @@ use chrono::{DateTime, Utc}; use common::{Fixture, Grant, TestMcp, event, id_of, payload, text}; use nostream_core::{EventId, Filter, Pubkey}; use nostream_mcp::{ - FORBIDDEN, TOOL_INVOICES_GET, TOOL_INVOICES_LIST, TOOL_REPORTS_LIST, TOOL_USER_ADMIN, - TOOL_USER_GET, audit_action, + FORBIDDEN, MAX_ROWS_PER_SKIP, TOOL_INVOICES_GET, TOOL_INVOICES_LIST, TOOL_REPORTS_LIST, + TOOL_USER_ADMIN, TOOL_USER_GET, audit_action, }; use nostream_storage::repositories::{ EventRepository, FieldUpdate, Invoice, InvoiceRepository, InvoiceStatus, InvoiceUnit, @@ -643,6 +644,73 @@ async fn invoices_list_pages_by_offset_and_refuses_a_page_outside_the_bound() { "{given}" ); } + + let served = client + .call(TOOL_INVOICES_LIST, json!({ "offset": MAX_ROWS_PER_SKIP })) + .await; + assert_eq!(served.is_error, Some(false), "{}", text(&served)); + assert!(ids(&payload(&served), "invoices").is_empty()); + + for given in [MAX_ROWS_PER_SKIP + 1, u64::MAX] { + let refused = client + .call(TOOL_INVOICES_LIST, json!({ "offset": given })) + .await; + assert_eq!(refused.is_error, Some(true), "{given}: {}", text(&refused)); + assert_eq!( + text(&refused), + format!("offset: a walk skips at most {MAX_ROWS_PER_SKIP} rows, {given} was given"), + "{given}" + ); + } + + let both = client + .call( + TOOL_INVOICES_LIST, + json!({ "limit": 0, "offset": MAX_ROWS_PER_SKIP + 1 }), + ) + .await; + assert_eq!( + text(&both), + "limit: a page holds between 1 and 500 rows, 0 was given" + ); +} + +#[tokio::test] +async fn invoices_list_serves_the_page_at_the_offset_ceiling() { + let fixture = TestMcp::start().await; + let pubkey = key(); + for index in 0..=MAX_ROWS_PER_SKIP { + seed_invoice( + &fixture, + &invoice( + &format!("inv-skip-{index:05}"), + &pubkey, + InvoiceStatus::Pending, + instant(1_699_999_100 + index as i64), + ), + ) + .await; + } + let client = fixture.client().await; + + let last = client + .call( + TOOL_INVOICES_LIST, + json!({ "offset": MAX_ROWS_PER_SKIP, "limit": 1 }), + ) + .await; + assert_eq!(last.is_error, Some(false), "{}", text(&last)); + assert_eq!(ids(&payload(&last), "invoices"), vec!["inv-skip-05000"]); + + let below = MAX_ROWS_PER_SKIP - 1; + let paged = client + .call(TOOL_INVOICES_LIST, json!({ "offset": below, "limit": 2 })) + .await; + assert_eq!(paged.is_error, Some(false), "{}", text(&paged)); + assert_eq!( + ids(&payload(&paged), "invoices"), + vec!["inv-skip-04999", "inv-skip-05000"] + ); } #[tokio::test] diff --git a/crates/nostream-mcp/tests/tools_list.rs b/crates/nostream-mcp/tests/tools_list.rs index 8014aa0a8..3e15033f0 100644 --- a/crates/nostream-mcp/tests/tools_list.rs +++ b/crates/nostream-mcp/tests/tools_list.rs @@ -18,10 +18,10 @@ mod common; use common::TestMcp; use nostream_mcp::{ - MAX_ROWS_PER_PAGE, TOOL_DELETE_EVENT, TOOL_GET_EVENT, TOOL_INVOICES_GET, TOOL_INVOICES_LIST, - TOOL_LIST_EVENTS, TOOL_MAINTENANCE_LAST_RUN, TOOL_MAINTENANCE_RUN, TOOL_RELAY_STATUS, - TOOL_REPORTS_ACTION, TOOL_REPORTS_LIST, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, TOOL_USER_ADMIN, - TOOL_USER_GET, + MAX_ROWS_PER_PAGE, MAX_ROWS_PER_SKIP, TOOL_DELETE_EVENT, TOOL_GET_EVENT, TOOL_INVOICES_GET, + TOOL_INVOICES_LIST, TOOL_LIST_EVENTS, TOOL_MAINTENANCE_LAST_RUN, TOOL_MAINTENANCE_RUN, + TOOL_RELAY_STATUS, TOOL_REPORTS_ACTION, TOOL_REPORTS_LIST, TOOL_SETTINGS_GET, + TOOL_SETTINGS_SET, TOOL_USER_ADMIN, TOOL_USER_GET, }; use serde_json::{Value, json}; @@ -145,6 +145,12 @@ async fn the_required_parameters_are_typed() { json!(MAX_ROWS_PER_PAGE), "the schema's bound is the tool's page bound" ); + assert_eq!( + tool(TOOL_INVOICES_LIST)["inputSchema"]["properties"]["offset"]["maximum"], + json!(MAX_ROWS_PER_SKIP), + "the schema's skip bound is the tool's skip ceiling" + ); + assert_eq!(MAX_ROWS_PER_SKIP, 5_000, "the ceiling D2 fixes"); assert!( tool(TOOL_GET_EVENT)["inputSchema"]["properties"] diff --git a/docs/rewrite/decisions/0018-users-invoices-and-report-reads.md b/docs/rewrite/decisions/0018-users-invoices-and-report-reads.md index 877c65da3..800907b56 100644 --- a/docs/rewrite/decisions/0018-users-invoices-and-report-reads.md +++ b/docs/rewrite/decisions/0018-users-invoices-and-report-reads.md @@ -113,7 +113,8 @@ paged past 500. Paid for: zero storage code in this slice. `invoices_list` takes `offset` and `limit`, passes them to `find_pending_invoices`, and answers `{"invoices": [...]}` with no re-sort and no `truncated` marker: a caller pages with `offset`, and the store's own `(offset, limit)` is the whole protocol. A marker no repository state can decide -would be a guess. +would be a guess. ADR 0020 caps the skip this paragraph leaves open, at the door rather than in +the protocol. `invoices_get` takes the id verbatim — no hex prefix, no length rule, no normalisation — because `invoice.id` is opaque text by migration, and an id that happens to be 64 hex characters is a @@ -137,7 +138,8 @@ page, and `invoices_list`'s offset walks a live index, so a pending row that lea between two pages — its status moving off `Pending`, which the payments worker's expiry does — shifts the walk, and a row can be skipped or answered twice. Insertion cannot: the index is `created_at ‖ id` ascending, so a new invoice lands after the cursor. Paid for: one number and -one message for the three tools that page. +one message for the three tools that page. ADR 0020 is the record for capping how far that offset +may skip. ### D7 — The absent-name example moves to `maintenance_run`, and five audit names land diff --git a/docs/rewrite/decisions/0020-mcp-offset-ceiling.md b/docs/rewrite/decisions/0020-mcp-offset-ceiling.md new file mode 100644 index 000000000..2f1b1987e --- /dev/null +++ b/docs/rewrite/decisions/0020-mcp-offset-ceiling.md @@ -0,0 +1,98 @@ +# ADR 0020: The MCP invoice walk's skip ceiling + +- **Status:** accepted (job 040, Phase 2) +- **Deciders:** the rewrite team, on the operator's steer recorded in #1183 and this job's spec +- **Date:** 2026-11-27 + +## Context + +Slice 4 of #1183 gave `invoices_list` the first caller-chosen `offset` on the MCP surface, and +`limit` alone was bounded. #1223 records the gap: an `offset` of any `u64` reaches +`find_pending_invoices`, and both backends pay for the rows it passes rather than for the page it +answers — LMDB iterates the pending index one key at a time until the offset is reached +(`crates/nostream-storage/src/lmdb/invoices.rs`), and Postgres runs the partial index with +`OFFSET $2` (`crates/nostream-storage/src/postgres/invoices.rs`). The cost is a slow read and not +a wrong one: the read is granted, the rows are the operator's to see, and nothing is disclosed or +written. + +Job 040's recon measured the shape on a temporary LMDB store holding 20,000 pending rows: the skip +is linear in the rows passed at about 0.09 µs per key, and it saturates at the pending set — 0.941 +ms at `offset: 5_000` with `limit: 0` (the skip loop alone, best of five) and 1.562 ms at +`u64::MAX` for an empty page, against 7.936 ms for the 500-row page at offset 0. An offset above +the index costs the whole pending set, never the offset itself, so what is missing is a ceiling at +the door rather than a cheaper walk. + +The two candidates were a ceiling and a keyset cursor. Both are priced below. + +## Decisions + +### D1 — A ceiling at the door, not a keyset cursor + +The ceiling is enforced in `pending_invoices` before the repository call, and the store's +`(offset, limit)` protocol, both backend bodies and the trait are unchanged. The cursor would have +removed the cost rather than capped it, and its price in this tree is counted where it can be: +`find_pending_invoices` on six implementors, a new `repository-parity.json` step and its replay arm +in `crates/nostream-storage/tests/common/mod.rs`, and a Postgres `ORDER BY created_at, id` tie-break +that no test here can run, because this sandbox has no database. Its door-side price is not in that +count and would be paid too: `offset: u64` becomes an opaque cursor in the published schema and +description, its `(created_at, id)` encoding has to be defined and refused when malformed, and a +caller loses random access to a page. ADR 0018's consequences rule out a storage move for these +reads, and this door does not need one: the note recorded no disclosure and no write, so what is +being bounded is a read's cost. + +**Cost:** paging stops at the ceiling, where a cursor would have removed the cost instead of +capping it. The ceiling is one constant, one function, one schema attribute, one snapshot and two +cases; the cursor is six implementors plus the parity harness, and its Postgres ordering cannot be +verified in this sandbox. It would also remove a cost this design keeps: a pending row that leaves +the queue between two pages shifts the walk, so a row can be skipped or answered twice, and a cursor +keyed on `(created_at, id)` would not shift. + +### D2 — The ceiling is `MAX_ROWS_PER_SKIP` = 5,000 rows, this door's own number + +Chosen on the measurement rather than on a round figure, and held here rather than borrowed: +`offset` is this door's argument, the invoice read has no page bound of its own +(`find_pending_invoices` takes any `limit`), and the page bound the door does state is 500. At 5,000 +keys the skip costs 0.941 ms against the 7.936 ms page the store already serves, so the ceiling +bounds the walk at about a tenth of the answer it precedes. A ceiling at the page bound (500) was +rejected because at `limit: 500` it leaves a caller two pages deep; 5,000 leaves eleven. The +magnitude matches `nostream_storage::MAX_PAGE_ROWS`, the relay's largest event page — the largest +single page the tree already asks a backend to answer — and it is measured against that clamp +rather than derived from it: a change to the relay's event page is a decision about `REQ`, and it +must not move an MCP schema. + +**Cost:** the ceiling is the door's own number, so the day the walk is re-measured it moves here and +nowhere else — at the price of a second 5,000 in the tree, where `MAX_PAGE_ROWS` already carries +one. A pending set deeper than 5,500 rows at `limit: 500` is unreachable through MCP; that reach is +what the bounded skip trades away, and nothing in the tree measures how deep a real deployment's +pending set is. Paid for: no cross-crate coupling — a relay or storage change cannot move this +door's published `maximum`, fail its snapshot, or leave its prose stale. + +### D3 — The refusal is the door's, with one fixed text + +`offset_bound` sits beside `page_bound`, defaults an absent offset to `0`, accepts any value at or +below the ceiling and refuses anything above it with +`offset: a walk skips at most {MAX_ROWS_PER_SKIP} rows, {offset} was given`, raised as +`McpError::Criterion` and rendered as an `isError: true` result. The schema carries the same number +through `#[schemars(range(min = 0, max = MAX_ROWS_PER_SKIP))]`, and the tool's description states +it, so the advertisement and the enforcement cannot drift. `page_bound` still runs first, so a call +with both arguments outside their bounds answers the `limit` text as it did before. The store never +sees a value above the ceiling from this door. + +**Cost:** a non-MCP caller can still hand the repository any `u64`, so the store's `OFFSET` still +takes a negative value there — the `as i64` wrap stays a failed call and not a leak — and this door +pays for that with zero storage change. Paid for: one refusal a caller can act on, in the same +shape the page bound already uses. + +## Consequences + +The surface is unchanged: fourteen tools, and `invoices_list` takes the same two arguments. What +moves is the maximum the schema publishes and the reach of one call. + +Nothing under `crates/nostream-storage` moves: no trait method, no backend arm, no parity step, no +migration. `find_pending_invoices` keeps accepting any `u64` from a caller that is not this door, +and the LMDB walk still answers an empty page past the index while the Postgres `OFFSET` still +fails at the driver for a negative value. + +A keyset cursor remains the honest successor: it would remove the skip from both backends instead +of capping it at the door, at the price D1 states. Until a slice takes it, a caller pages at most +eleven pages deep at `limit: 500`, and the store's walk is bounded at 5,000 keys.