Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 63 additions & 3 deletions pkgs/id/crates/id-core/src/world_caps.rs
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ const CHAT_HISTORY_BOUNDS: &[ProviderBound] = &[
/// Bounds for `records.read`: argument bytes plus the page byte cap.
const RECORDS_READ_BOUNDS: &[ProviderBound] = &[
ProviderBound::ArgsBytes(MAX_ARGS_BYTES),
ProviderBound::ResponseBytes(MAX_RECORDS_PAGE_BYTES),
ProviderBound::ResponseBytes(MAX_RECORDS_RESULT_PAGE_BYTES),
];
/// Bounds for `schedule.at`: argument bytes, id bytes, pending cap, and horizon.
const SCHEDULE_AT_BOUNDS: &[ProviderBound] = &[
Expand Down Expand Up @@ -532,9 +532,31 @@ pub const MAX_SCHEDULE_HORIZON_DAYS: u64 = 30;
pub const MAX_SCHEDULE_HORIZON_MS: u64 = MAX_SCHEDULE_HORIZON_DAYS * 24 * 60 * 60 * 1000;
/// Most schedules delivered in one wakeup. Any left due fire on the next.
pub const MAX_SCHEDULE_FIRES_PER_WAKEUP: usize = 64;
/// Largest page of records returned by `records.read`, in bytes.
/// Largest page of records served over the session protocol and the
/// host view, in bytes. Cap results are not served this way: a
/// `records.read` result is delivered through `result_event` and is
/// bounded by [`MAX_RECORDS_RESULT_PAGE_BYTES`] instead (#4888).
pub const MAX_RECORDS_PAGE_BYTES: usize = 768 * 1024;

/// Bytes of [`MAX_EVENT_BYTES`] reserved for the `result_event`
/// envelope around a `records.read` value: the outer
/// `{"cap":"result","id":...,"ok":true,"value":...}` object (request
/// ids are at most [`MAX_NAME_BYTES`] long), the value's own
/// `{"records":[...],"next_after":...}` wrapper, and a serialized
/// `next_after` key (record keys are at most 256 bytes, and JSON
/// escaping at most doubles that, plus the quotes). The fixed parts
/// measure under 200 bytes and the escaped key under 514, so 1024
/// leaves slack rather than sitting on the edge.
pub const RESULT_EVENT_ENVELOPE_BYTES: usize = 1024;

/// Largest page of records a `records.read` cap result may carry, in
/// bytes of serialized `{"key":...,"value":...}` entries (plus one
/// array comma each). Derived from the event limit minus the envelope
/// allowance, so a page admitted under this bound always fits the
/// `result_event` that delivers it: it can never be replaced by a
/// `result_too_large` error (#4888).
pub const MAX_RECORDS_RESULT_PAGE_BYTES: usize = MAX_EVENT_BYTES - RESULT_EVENT_ENVELOPE_BYTES;

/// Check a schedule id: 1 to [`MAX_SCHEDULE_ID_BYTES`] bytes, all printable
/// ASCII (space through `~`), so no control characters reach the journal.
///
Expand Down Expand Up @@ -1321,6 +1343,44 @@ mod tests {
);
}

#[test]
fn records_result_pages_always_fit_the_result_event() {
// A page admitted at the cap-result bound, delivered with the
// longest request id and a longest, escape-heavy next_after key,
// stays a records result — never result_too_large (#4888).
let entry = serde_json::json!({"key": "k", "value": "x".repeat(1024)});
let entry_bytes = serde_json::to_vec(&entry).unwrap().len() + 1;
let mut records = Vec::new();
let mut used = 0;
while used + entry_bytes <= MAX_RECORDS_RESULT_PAGE_BYTES {
records.push(entry.clone());
used += entry_bytes;
}
assert!(!records.is_empty());
// 256 raw key bytes (128 backslash+quote pairs), the longest a
// record key may be, and the worst case for JSON escaping.
let next_after: String = (0..128)
.flat_map(|_| [char::from_u32(92).unwrap(), '"'])
.collect();
assert_eq!(next_after.len(), 256);
let value = serde_json::json!({
"records": records,
"next_after": next_after,
});
let event = result_event(&"i".repeat(MAX_NAME_BYTES), Ok(value));
assert!(event.len() <= MAX_EVENT_BYTES, "event is {}", event.len());
let event: serde_json::Value = serde_json::from_str(&event).unwrap();
assert_eq!(event["ok"], true, "{event}");
assert!(event["value"]["records"].is_array());
// The registry reports the cap-result bound for records.read.
assert!(
RECORDS_READ_BOUNDS
.contains(&ProviderBound::ResponseBytes(MAX_RECORDS_RESULT_PAGE_BYTES))
);
// The session-protocol page budget is a separate, larger bound.
assert_eq!(MAX_RECORDS_PAGE_BYTES, 768 * 1024);
}

fn names(list: &[&str]) -> BTreeSet<String> {
list.iter().map(|name| (*name).to_owned()).collect()
}
Expand Down Expand Up @@ -1402,7 +1462,7 @@ mod tests {
.get("records.read")
.unwrap()
.bounds
.contains(&ProviderBound::ResponseBytes(MAX_RECORDS_PAGE_BYTES))
.contains(&ProviderBound::ResponseBytes(MAX_RECORDS_RESULT_PAGE_BYTES))
);
// Every provider registered today opted in explicitly, so the
// default ceiling is still the whole catalog — naming the choice
Expand Down
12 changes: 10 additions & 2 deletions pkgs/id/src/world/actor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -796,6 +796,10 @@ impl WorldActor {
/// `records.read`: a byte-bounded, prefix-scoped page of the world's
/// published records, key-ordered with the same exclusive `after` cursor
/// the session protocol uses. Follow `next_after` while it is non-empty.
/// The page is bounded by the cap-result budget
/// (world_caps::MAX_RECORDS_RESULT_PAGE_BYTES), not the session
/// protocol's larger page budget, so an admitted page always fits
/// the result event that delivers it (#4888).
fn execute_records_read(
&self,
args: &serde_json::Value,
Expand All @@ -818,8 +822,12 @@ impl WorldActor {
{
continue;
}
let size = key.len() + serde_json::to_vec(value).map_or(0, |v| v.len()) + 8;
if used + size > crate::world_session::MAX_RECORDS_PAGE_BYTES {
// Count the entry as it will actually be serialized in
// the result value, plus one byte for its array comma.
let size = serde_json::to_vec(&serde_json::json!({"key": key, "value": value}))
.map_or(usize::MAX, |entry| entry.len())
+ 1;
if used + size > crate::world_caps::MAX_RECORDS_RESULT_PAGE_BYTES {
if page.is_empty() {
return Err(CapError::bad_args());
}
Expand Down
77 changes: 77 additions & 0 deletions pkgs/id/src/world/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1099,6 +1099,83 @@ mod tests {
assert_eq!(oversized_result["error"], "bad_args");
}

#[tokio::test]
async fn records_read_pages_fit_the_result_event_that_delivers_them() {
// Regression for #4888: sixteen ~8 KiB records total ~128 KiB,
// which the old 768 KiB page admission accepted whole — and
// result_event then replaced the entire page with a
// result_too_large error above 64 KiB, so the program never saw
// a single record. The page must now stop at the cap-result
// bound and deliver records, with next_after naming the rest.
#[derive(Debug, Default)]
struct PageProbe {
answered: BTreeSet<String>,
results: BTreeMap<String, serde_json::Value>,
}

impl WorldProgram for PageProbe {
fn update(&mut self, event: &WorldEvent) -> Result<()> {
if let WorldEventKind::System { event } = &event.kind {
let value: serde_json::Value =
serde_json::from_str(event).unwrap_or(serde_json::Value::Null);
if value["cap"] == "result"
&& let Some(id) = value["id"].as_str()
{
self.answered.insert(id.to_owned());
self.results.insert(id.to_owned(), value);
}
}
Ok(())
}

fn wants(&mut self) -> Result<Option<String>> {
let requests: Vec<serde_json::Value> = [(
"records-page",
"records.read",
serde_json::json!({}),
)]
.into_iter()
.filter(|(id, _, _)| !self.answered.contains(*id))
.map(|(id, cap, args)| serde_json::json!({"id": id, "cap": cap, "args": args}))
.collect();
Ok(Some(
serde_json::json!({"v": 1, "requests": requests}).to_string(),
))
}

fn records(&mut self) -> Result<Option<String>> {
Ok(Some(
serde_json::json!({"results": self.results}).to_string(),
))
}
}

let mut core = world(128);
core.ledger
.set_granted(BTreeSet::from(["records.read".to_owned()]));
let mut actor = WorldActor::for_test(core, Box::new(PageProbe::default()), None);
let mut injected = Records::new();
for index in 0..16 {
injected.insert(
format!("r{index:02}"),
serde_json::Value::String("x".repeat(8000)),
);
}
actor.records_sender.send_replace((0, Arc::new(injected)));

actor.after_change().await;

let records = actor.records_sender.borrow().1.clone();
let page = &records["results"]["records-page"];
assert_eq!(page["ok"], true, "{page}");
let delivered = page["value"]["records"].as_array().unwrap();
// Each serialized entry is 8025 bytes with its comma; the
// 64512-byte cap-result bound admits exactly 8 of the 16.
assert_eq!(delivered.len(), 8, "{page}");
assert_eq!(delivered[0]["key"], "r00");
assert_eq!(page["value"]["next_after"], "r07");
}

#[tokio::test]
async fn a_granted_chat_history_request_is_served_over_the_ledger() {
let (world, token) = caps_world_sync(false).await;
Expand Down
Loading