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
129 changes: 95 additions & 34 deletions pkgs/id/src/local_events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use crate::chain::{ChainExt, Event, MAX_AFTER, sign};
use crate::documents::{DOCUMENT_KIND, DocumentRef, REMOVAL_KIND};
use crate::event_store::{EventStore, Ingest};
use crate::notes::{
AppliedNote, CREATE_KIND as NOTE_CREATE_KIND, NoteOp, NoteRecord,
AppliedNote, CREATE_KIND as NOTE_CREATE_KIND, NoteFoldError, NoteOp, NoteRecord,
REVISE_KIND as NOTE_REVISE_KIND, check_note_op, fold_notes,
};
use crate::search::{Hit, ValueMatch, search_store};
Expand Down Expand Up @@ -170,6 +170,45 @@ pub struct Published {
/// Every applied event's entry by ID, and every applied event's parents by ID.
type Log = (HashMap<Hash, Entry>, HashMap<Hash, Vec<Hash>>);

/// Folds store note events while quarantining malformed remote revisions.
///
/// Unknown/foreign-parent revisions are removed first. If the remaining same-note graph is
/// cyclic, remove a revision identified by the strict fold and repeat so its dependents are
/// quarantined too; unrelated healthy notes remain readable.
fn fold_remote_notes(
mut applied: Vec<AppliedNote>,
) -> std::result::Result<Vec<NoteRecord>, NoteFoldError> {
loop {
let owners: HashMap<Hash, Hash> = applied
.iter()
.map(|event| match &event.op {
NoteOp::Create { .. } => (event.id, event.id),
NoteOp::Revise { note, .. } => (event.id, *note),
})
.collect();
let before = applied.len();
applied.retain(|event| match &event.op {
NoteOp::Create { .. } => true,
NoteOp::Revise { note, parents, .. } => {
owners.get(note) == Some(note)
&& parents
.iter()
.all(|parent| owners.get(parent) == Some(note))
}
});
if applied.len() != before {
continue;
}

match fold_notes(&applied) {
Err(NoteFoldError::CyclicParent { revision, .. }) => {
applied.retain(|event| event.id != revision);
}
result => return result,
}
}
}

/// The event store, and the key the node signs its events with.
#[derive(Debug)]
pub struct LocalEvents {
Expand Down Expand Up @@ -490,39 +529,11 @@ impl LocalEvents {
_ => None,
})
.collect();
// Quarantine invalid remote revisions (PR #3908 Codex P1): ingest
// applies a signed note.revise after checking only its shape, so a
// peer can land a revision naming an unknown note or parent, and
// the strict fold would then fail every note query in the store --
// notes(), note_history(), and revise_note() with it. Drop,
// repeatedly (a revision that names a dropped one as parent goes
// too), every revise whose note has no create here or whose
// parents are not revisions of that note. The events stay in the
// store; valid notes fold exactly as before.
let mut applied = applied;
loop {
let owners: HashMap<Hash, Hash> = applied
.iter()
.map(|event| match &event.op {
NoteOp::Create { .. } => (event.id, event.id),
NoteOp::Revise { note, .. } => (event.id, *note),
})
.collect();
let before = applied.len();
applied.retain(|event| match &event.op {
NoteOp::Create { .. } => true,
NoteOp::Revise { note, parents, .. } => {
owners.get(note) == Some(note)
&& parents
.iter()
.all(|parent| owners.get(parent) == Some(note))
}
});
if applied.len() == before {
break;
}
}
Ok(fold_notes(&applied)?)
// Ingest checks only a revision's shape, not whether its note graph
// can be folded. Quarantine invalid remote revisions so one bad event
// cannot disable notes(), note_history(), or revise_note() for the
// healthy notes in this store. The events stay in the store.
Ok(fold_remote_notes(applied)?)
}

/// The note `note`: its revisions in ID order and its current heads.
Expand Down Expand Up @@ -982,6 +993,56 @@ mod tests {
.is_ok());
}

#[test]
fn test_cyclic_remote_revisions_do_not_disable_healthy_notes() {
fn applied_create(byte: u8) -> AppliedNote {
AppliedNote {
id: id(byte),
author: [1; 32],
op: NoteOp::Create {
content: DocumentRef::for_bytes("text/markdown", b"note").unwrap(),
},
}
}

fn applied_revise(event: u8, note: u8, parents: &[u8]) -> AppliedNote {
AppliedNote {
id: id(event),
author: [1; 32],
op: NoteOp::Revise {
note: id(note),
content: DocumentRef::for_bytes("text/markdown", b"revision").unwrap(),
parents: parents.iter().map(|parent| id(*parent)).collect(),
},
}
}

for cyclic in [
vec![applied_revise(21, 20, &[21])],
vec![applied_revise(21, 20, &[22]), applied_revise(22, 20, &[21])],
vec![
applied_revise(21, 20, &[22]),
applied_revise(22, 20, &[23]),
applied_revise(23, 20, &[21]),
],
] {
let mut events = vec![
applied_create(10),
applied_revise(11, 10, &[10]),
applied_create(20),
];
events.extend(cyclic);
events.push(applied_revise(24, 20, &[21]));

let notes = fold_remote_notes(events).unwrap();
assert_eq!(notes.len(), 2);
assert_eq!(notes[0].id, id(10));
assert_eq!(notes[0].revisions.len(), 2);
assert_eq!(notes[1].id, id(20));
assert_eq!(notes[1].revisions.len(), 1);
}
}

#[test]
fn test_revise_reserves_parent_author_head_past_the_after_cap() {
// PR #3908 Codex P2: with more other authors than MAX_AFTER, the
Expand Down
50 changes: 48 additions & 2 deletions pkgs/id/src/notes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,14 @@ pub enum NoteFoldError {
/// The note the parent belongs to.
note: Hash,
},
/// A revision graph contains a cycle, so its revisions cannot be folded causally.
#[error("revision {revision} names parent {parent} in a cycle")]
CyclicParent {
/// A revision in the cycle.
revision: Hash,
/// The present, same-note revision it is waiting on.
parent: Hash,
},
}

/// Folds applied note events into one record per note, in note ID order.
Expand All @@ -227,7 +235,7 @@ pub enum NoteFoldError {
///
/// Returns [`NoteFoldError`] when two events share an ID, a revision names a note with no
/// create event in the set, or a revision names a parent that is unknown or belongs to
/// another note.
/// another note. Returns [`NoteFoldError::CyclicParent`] when revisions form a cycle.
pub fn fold_notes(events: &[AppliedNote]) -> Result<Vec<NoteRecord>, NoteFoldError> {
let mut by_id: HashMap<Hash, &AppliedNote> = HashMap::with_capacity(events.len());
for event in events {
Expand Down Expand Up @@ -325,7 +333,7 @@ pub fn fold_notes(events: &[AppliedNote]) -> Result<Vec<NoteRecord>, NoteFoldErr
.find(|parent| !folded.contains(parent))
.copied()
.unwrap_or(stuck.id);
return Err(NoteFoldError::UnknownParent {
return Err(NoteFoldError::CyclicParent {
revision: stuck.id,
parent,
});
Expand Down Expand Up @@ -551,4 +559,42 @@ mod tests {
})
);
}

#[test]
fn test_the_fold_reports_cycles_separately_from_unknown_parents() {
for (events, revision, parent) in [
(
vec![create(10, b"a"), revise(11, 10, b"self", &[11])],
11,
11,
),
(
vec![
create(10, b"a"),
revise(11, 10, b"first", &[12]),
revise(12, 10, b"second", &[11]),
],
11,
12,
),
(
vec![
create(10, b"a"),
revise(11, 10, b"first", &[12]),
revise(12, 10, b"second", &[13]),
revise(13, 10, b"third", &[11]),
],
11,
12,
),
] {
assert_eq!(
fold_notes(&events),
Err(NoteFoldError::CyclicParent {
revision: hash(revision),
parent: hash(parent),
})
);
}
}
}
Loading