Skip to content
Merged
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
179 changes: 170 additions & 9 deletions pkgs/id/src/world_records.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use std::path::Path;
use std::sync::Arc;
use std::time::Duration;

use anyhow::{Context, Result, bail};
use anyhow::{Context, Result, bail, ensure};
use futures_lite::StreamExt;
use iroh_blobs::{Hash, api::Store};
use iroh_docs::{
Expand All @@ -36,7 +36,9 @@ use iroh_docs::{
};
use tokio::task::JoinHandle;

use crate::world::{Records, WorldHandle};
use crate::world::{
MAX_RECORD_KEY_BYTES, MAX_RECORD_VALUE_BYTES, MAX_RECORDS, Records, WorldHandle,
};

/// The host side: one world's records document.
#[derive(Clone, Debug)]
Expand Down Expand Up @@ -167,15 +169,30 @@ impl RecordsStore {
existing.insert(key.to_owned(), entry.content_hash());
}
}
// Delete obsolete keys before writing additions (Codex review
// on PR #6495): with add-before-delete, replacing one valid
// MAX_RECORDS-sized set with a disjoint one transiently put
// up to twice the cap of entries in the doc, and a follower
// reading that intermediate state was refused by the
// receipt-side cap in read_records. Delete-first keeps every
// intermediate doc state at or below
// max(old set, new set), so a conforming publisher never
// produces an over-cap doc.
let obsolete: Vec<String> = existing
.keys()
.filter(|key| !records.contains_key(*key))
.cloned()
.collect();
for key in &obsolete {
self.doc.del(self.author, doc_key(key)).await?;
existing.remove(key);
}
for (key, value) in records {
let bytes = serde_json::to_vec(value)?;
if existing.remove(key) != Some(Hash::new(&bytes)) {
self.doc.set_bytes(self.author, doc_key(key), bytes).await?;
}
}
for key in existing.keys() {
self.doc.del(self.author, doc_key(key)).await?;
}
Ok(())
}

Expand All @@ -201,26 +218,62 @@ impl RecordsStore {

/// Read every record from a (local or replicated) records doc.
///
/// Receipt-side cap enforcement (#6483): a replicated doc is not
/// trusted just because a conforming publisher would have passed
/// `crate::world::parse_records`. The same `MAX_RECORD*` caps are
/// re-checked here, matching `parse_records` and
/// `AdminHistoryBudget::add_record`: at most `MAX_RECORDS` records,
/// keys non-empty, at most `MAX_RECORD_KEY_BYTES` bytes and free of
/// control characters, and values at most `MAX_RECORD_VALUE_BYTES`
/// serialized. Key and count checks run before the entry's blob is
/// fetched, so an over-cap doc fails early rather than after
/// materializing every blob; a value's size can only be measured once
/// that one blob is in hand (the blob store serves whole blobs), and
/// is checked before any later entry is fetched. Any violation is an
/// error naming the offending record key. Callers surface it: the
/// `mirror --follow` loop in `commands::world` propagates it with
/// `?`, so a refusal ends the follow with an error instead of
/// silently retry-spinning.
///
/// # Errors
///
/// Docs or blob failures, or a value that is not JSON.
/// Docs or blob failures, a value that is not JSON, or a record that
/// exceeds one of the `MAX_RECORD*` caps.
pub async fn read_records(doc: &Doc, blobs: &Store) -> Result<Records> {
let mut records = Records::new();
let mut seen = 0usize;
let entries = doc.get_many(Query::all().build()).await?;
tokio::pin!(entries);
while let Some(entry) = entries.try_next().await? {
let Some(key) = record_key(entry.key()) else {
continue;
};
ensure!(
!key.is_empty() && key.len() <= MAX_RECORD_KEY_BYTES,
"record key {key:?} must be 1..={MAX_RECORD_KEY_BYTES} bytes"
);
ensure!(
!key.chars().any(char::is_control),
"record key {key:?} contains a control character"
);
seen += 1;
ensure!(
seen <= MAX_RECORDS,
"records doc contains more than {MAX_RECORDS} records; the limit is {MAX_RECORDS}"
Comment on lines +260 to +262

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve followers during valid record-set replacements

When a world replaces keys near the 4096-record limit, this check can reject a legitimate intermediate publication state. RecordsStore::reconcile writes all additions before deleting obsolete keys, so even two valid 4096-record sets can temporarily produce more than 4096 document entries. In commands/world.rs, mirror --follow rereads after an InsertRemote with only a fixed 200ms delay and propagates this error, permanently terminating the follower if reconciliation or replication exposes that intermediate state long enough. Keep receipt-side enforcement, but distinguish transient publication states from a persistently over-cap document, or make publication atomic.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9162ddf (lane code-d, resuming task 10970 after lane code-v parked it on CI): RecordsStore::reconcile now deletes obsolete keys before writing additions, so every intermediate doc state stays at or below max(old set, new set) and a conforming publisher can no longer produce a transient over-cap doc for a follower to be refused on. Receipt-side enforcement in read_records is unchanged — a persistently over-cap doc from a non-conforming source is still refused. Added regression test reconcile_replacing_a_full_set_stays_readable (full MAX_RECORDS set replaced by a disjoint full set, read back exactly); cargo test world_records from pkgs/id: 13 passed, 0 failed on the laptop.

);
let bytes = blobs
.blobs()
.get_bytes(entry.content_hash())
.await
.with_context(|| format!("content of record {key:?} is not available yet"))?;
records.insert(
key.to_owned(),
serde_json::from_slice(&bytes).with_context(|| format!("record {key:?}"))?,
let value: serde_json::Value =
serde_json::from_slice(&bytes).with_context(|| format!("record {key:?}"))?;
let size = serde_json::to_vec(&value).map_or(usize::MAX, |v| v.len());
ensure!(
size <= MAX_RECORD_VALUE_BYTES,
"record {key:?} is {size} bytes; the limit is {MAX_RECORD_VALUE_BYTES}"
);
records.insert(key.to_owned(), value);
}
Ok(records)
}
Expand Down Expand Up @@ -537,4 +590,112 @@ mod tests {

host.shutdown().await;
}

#[tokio::test]
async fn reconcile_replacing_a_full_set_stays_readable() {
// Regression for the Codex finding on PR #6495: replacing one
// MAX_RECORDS-sized set with a disjoint one must end in a doc
// that read_records accepts (delete-first ordering keeps every
// intermediate state within the cap as well).
let host = Node::spawn().await;
let store = RecordsStore::open(&host.docs, None).await.unwrap();
let mut first = Records::new();
for i in 0..MAX_RECORDS {
first.insert(format!("a{i}"), 1.into());
}
store.reconcile(&first).await.unwrap();
let mut second = Records::new();
for i in 0..MAX_RECORDS {
second.insert(format!("b{i}"), 2.into());
}
store.reconcile(&second).await.unwrap();
let read = read_records(&store.doc, &host.blobs).await.unwrap();
assert_eq!(read, second);
host.shutdown().await;
}

async fn write_raw(store: &RecordsStore, key: &str, bytes: Vec<u8>) {
store
.doc
.set_bytes(store.author, doc_key(key), bytes)
.await
.unwrap();
}

async fn read_err(store: &RecordsStore, blobs: &Store) -> String {
read_records(&store.doc, blobs)
.await
.unwrap_err()
.to_string()
}

#[tokio::test]
async fn read_records_accepts_a_conforming_doc() {
let host = Node::spawn().await;
let store = RecordsStore::open(&host.docs, None).await.unwrap();
write_raw(&store, "a", b"1".to_vec()).await;
write_raw(
&store,
&"k".repeat(MAX_RECORD_KEY_BYTES),
b"\"two\"".to_vec(),
)
.await;
let read = read_records(&store.doc, &host.blobs).await.unwrap();
assert_eq!(read.len(), 2);
assert_eq!(read["a"], 1);
host.shutdown().await;
}

#[tokio::test]
async fn read_records_refuses_an_oversized_value() {
let host = Node::spawn().await;
let store = RecordsStore::open(&host.docs, None).await.unwrap();
let big = serde_json::Value::String("x".repeat(MAX_RECORD_VALUE_BYTES + 1));
write_raw(&store, "big", serde_json::to_vec(&big).unwrap()).await;
let err = read_err(&store, &host.blobs).await;
assert!(err.contains("big") && err.contains("8192"), "{err}");
host.shutdown().await;
}

#[tokio::test]
async fn read_records_refuses_an_over_long_key() {
let host = Node::spawn().await;
let store = RecordsStore::open(&host.docs, None).await.unwrap();
write_raw(&store, &"k".repeat(MAX_RECORD_KEY_BYTES + 1), b"1".to_vec()).await;
let err = read_err(&store, &host.blobs).await;
assert!(err.contains("256"), "{err}");
host.shutdown().await;
}

#[tokio::test]
async fn read_records_refuses_a_control_character_key() {
let host = Node::spawn().await;
let store = RecordsStore::open(&host.docs, None).await.unwrap();
write_raw(&store, "bad\u{1}key", b"1".to_vec()).await;
let err = read_err(&store, &host.blobs).await;
assert!(err.contains("control character"), "{err}");
host.shutdown().await;
}

#[tokio::test]
async fn read_records_refuses_an_empty_key() {
let host = Node::spawn().await;
let store = RecordsStore::open(&host.docs, None).await.unwrap();
write_raw(&store, "", b"1".to_vec()).await;
let err = read_err(&store, &host.blobs).await;
assert!(err.contains("1..=256"), "{err}");
host.shutdown().await;
}

#[tokio::test]
async fn read_records_refuses_too_many_records() {
let host = Node::spawn().await;
let store = RecordsStore::open(&host.docs, None).await.unwrap();
for i in 0..=MAX_RECORDS {
write_raw(&store, &format!("k{i}"), b"1".to_vec()).await;
}
let err = read_err(&store, &host.blobs).await;
assert!(err.contains("4096"), "{err}");
host.shutdown().await;
}
}
Loading