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
2 changes: 1 addition & 1 deletion core/continuum-context/src/cause.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use sha2::{Digest, Sha256};
/// One occurrence, named by the producer that persists it (an act, a message, an engram):
/// stable across epochs and restarts, never an in-view position. Two reads of one file are two
/// occurrences with two ids; the file they read is the item's `key`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
pub struct ElementId(u128);

impl ElementId {
Expand Down
65 changes: 52 additions & 13 deletions core/continuum-context/src/epoch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ impl Block for String {
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Event<T = String> {
pub source: SourceId,
/// The occurrence this block renders (`crate::cause`); `None` for a source's fold block,
/// which stands for a range of items.
pub element: Option<crate::cause::ElementId>,
/// The level the view rendered it at: what a render receipt reports she was shown.
pub level: crate::level::Level,
pub version: u32,
pub text: T,
/// The source ended with this notice; turnover drops it entirely.
Expand Down Expand Up @@ -77,16 +82,23 @@ impl<T: Block> Epoch<T> {

/// Record a source's current rendering. Appends only when it differs from that source's
/// latest version; never edits an earlier block.
pub fn observe(&mut self, source: SourceId, text: T) -> Observed {
pub fn observe(&mut self, source: SourceId, element: Option<crate::cause::ElementId>, level: crate::level::Level, text: T) -> Observed {
let latest = self.events.iter().rposition(|e| e.source == source);
if let Some(i) = latest {
if self.events[i].text == text {
// The same bytes now stand for another occurrence or level (a short item whose
// pointer is itself, a re-read of unchanged content): the prompt is unchanged, so
// nothing appends, but what the block IS updates in place, or a receipt would
// report the old occurrence or level (Codex on #5639).
let event = &mut self.events[i];
event.element = element;
event.level = level;
return Observed::Unchanged;
}
self.superseded_chars += self.events[i].text.chars();
}
let version = latest.map_or(0, |i| self.events[i].version + 1);
self.events.push(Event { source, version, text, retired: false });
self.events.push(Event { source, element, level, version, text, retired: false });
Observed::Appended { version }
}

Expand All @@ -102,8 +114,8 @@ impl<T: Block> Epoch<T> {
return Observed::Unchanged;
}
self.superseded_chars += self.events[i].text.chars();
let version = self.events[i].version + 1;
self.events.push(Event { source, version, text: notice, retired: true });
let (element, version) = (self.events[i].element, self.events[i].version + 1);
self.events.push(Event { source, element, level: crate::level::Level::Pointer, version, text: notice, retired: true });
Observed::Appended { version }
}

Expand All @@ -124,6 +136,12 @@ impl<T: Block> Epoch<T> {
self.events.iter().any(|e| &e.source == source)
}

/// Every block after the head, in prompt order, superseded versions included: what a render
/// receipt projects.
pub fn events(&self) -> &[Event<T>] {
&self.events
}

/// The view in order: the head, then every event as it arrived.
pub fn render(&self) -> impl Iterator<Item = &T> {
self.head.iter().chain(self.events.iter().map(|e| &e.text))
Expand All @@ -142,6 +160,27 @@ impl<T: Block> Epoch<T> {

#[cfg(test)]
mod tests {
// what this catches: a receipt reporting stale evidence when identical bytes change meaning:
// a block first shown as a pointer whose whole is the same bytes, or a re-read of unchanged
// content by a new occurrence (Codex on #5639). The prompt must not grow; the metadata must.
#[test]
fn identical_bytes_with_a_new_level_or_occurrence_update_the_block_without_appending() {
use crate::cause::ElementId;
use crate::level::Level;
let mut e = Epoch::<String>::new(1, Vec::new());
let (first, second) = (ElementId::of(&[b"read 1"]), ElementId::of(&[b"read 2"]));
assert_eq!(e.observe(src("open-views/a.rs"), Some(first), Level::Pointer, "a.rs: 3 lines".into()), Observed::Appended { version: 0 });
assert_eq!(e.observe(src("open-views/a.rs"), Some(first), Level::Full, "a.rs: 3 lines".into()), Observed::Unchanged);
assert_eq!((e.events().len(), e.events()[0].level), (1, Level::Full), "same bytes, now its whole");
assert_eq!(e.observe(src("open-views/a.rs"), Some(second), Level::Full, "a.rs: 3 lines".into()), Observed::Unchanged);
assert_eq!((e.events().len(), e.events()[0].element), (1, Some(second)), "same bytes, now the newer occurrence");
}

/// A test block: whole, standing for no particular occurrence.
fn seen(e: &mut Epoch<String>, source: SourceId, text: String) -> Observed {
e.observe(source, None, crate::level::Level::Full, text)
}

use super::*;

fn src(s: &str) -> SourceId {
Expand All @@ -166,7 +205,7 @@ mod tests {
let mut previous = joined(&e);
for act in acts {
for (s, t) in act {
e.observe(src(s), t.to_string());
seen(&mut e, src(s), t.to_string());
}
let now = joined(&e);
assert!(now.starts_with(&previous), "an act rewrote the prefix:\n{previous}\n---\n{now}");
Expand All @@ -178,9 +217,9 @@ mod tests {
#[test]
fn an_unchanged_source_appends_nothing() {
let mut e = Epoch::<String>::new(1, vec![]);
assert_eq!(e.observe(src("kanban"), "v1".into()), Observed::Appended { version: 0 });
assert_eq!(e.observe(src("kanban"), "v1".into()), Observed::Unchanged);
assert_eq!(e.observe(src("kanban"), "v2".into()), Observed::Appended { version: 1 });
assert_eq!(seen(&mut e, src("kanban"), "v1".into()), Observed::Appended { version: 0 });
assert_eq!(seen(&mut e, src("kanban"), "v1".into()), Observed::Unchanged);
assert_eq!(seen(&mut e, src("kanban"), "v2".into()), Observed::Appended { version: 1 });
assert_eq!(e.superseded_chars(), 2);
}

Expand All @@ -191,12 +230,12 @@ mod tests {
fn per_item_sources_append_only_the_item_that_changed() {
let mut e = Epoch::<String>::new(1, vec![]);
for view in ["a.rs", "b.rs", "c.rs"] {
e.observe(src(&format!("open-views/{view}")), format!("{view} v1 {}", "x".repeat(1000)));
seen(&mut e, src(&format!("open-views/{view}")), format!("{view} v1 {}", "x".repeat(1000)));
}
let before: usize = e.chars();
e.observe(src("open-views/a.rs"), "a.rs v1 ".to_string() + &"x".repeat(1000));
e.observe(src("open-views/b.rs"), "b.rs v2".into());
e.observe(src("open-views/c.rs"), "c.rs v1 ".to_string() + &"x".repeat(1000));
seen(&mut e, src("open-views/a.rs"), "a.rs v1 ".to_string() + &"x".repeat(1000));
seen(&mut e, src("open-views/b.rs"), "b.rs v2".into());
seen(&mut e, src("open-views/c.rs"), "c.rs v1 ".to_string() + &"x".repeat(1000));
let after: usize = e.chars();
assert_eq!(after - before, "b.rs v2".len(), "only the changed view was appended");
}
Expand All @@ -206,7 +245,7 @@ mod tests {
#[test]
fn retiring_a_source_appends_its_notice_once() {
let mut e = Epoch::<String>::new(1, vec![]);
e.observe(src("open-views/a.rs"), "a.rs contents".into());
seen(&mut e, src("open-views/a.rs"), "a.rs contents".into());
let before = joined(&e);
assert_eq!(e.retire(src("open-views/a.rs"), "[closed a.rs]".into()), Observed::Appended { version: 1 });
assert!(joined(&e).starts_with(&before));
Expand Down
12 changes: 12 additions & 0 deletions core/continuum-context/src/level.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
//! How much of an item the view renders. The view decides it; the epoch records it on each block,
//! so a render receipt says what she was actually shown.

/// Whole, its summary, its pointer, or inside its source's one fold block with the rest of the
/// oldest run.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum Level {
Full,
Summary,
Pointer,
Folded,
}
2 changes: 2 additions & 0 deletions core/continuum-context/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@
//! - [`cause`]: what each element follows from: its occurrence id, its cause, its content.
//! - [`epoch`]: a stable head, then keyed blocks that only append.
//! - [`source`]: what a context source offers: its current items, each under a stable key.
//! - [`level`]: how much of an item the view rendered (whole, summary, pointer, folded).
//! - [`levels`]: each item's summary level, generated from its shape (mipmaps for context).
//! - [`motion`]: how each source moves between epoch starts, which orders the next start.
//! - [`view`]: one mind's epoch fed by its sources; turnover is the only rewrite.

pub mod cause;
pub mod epoch;
pub mod level;
pub mod levels;
pub mod motion;
pub mod source;
Expand Down
69 changes: 64 additions & 5 deletions core/continuum-context/src/view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ use crate::source::{Item, Source};

mod allot;

use allot::{allot, rank, Level};
use allot::{allot, rank};
pub use crate::level::Level;
pub use allot::floor;

/// The item key a source's fold block is observed under: no source keys an item with it.
Expand Down Expand Up @@ -75,6 +76,26 @@ pub struct Start {
pub folded: usize,
}

/// One block she was shown, as the view rendered it (`View::receipt`).
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Rendered {
pub source: SourceId,
/// The occurrence it renders; `None` for a fold block, which stands for a range.
pub element: Option<crate::cause::ElementId>,
pub level: Level,
pub version: u32,
/// A superseding notice for a source that ended.
pub retired: bool,
pub chars: usize,
}

/// What one submitted prompt showed her, in prompt order (the view's half of the render receipt).
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Receipt {
pub epoch: u64,
pub items: Vec<Rendered>,
}

/// Serializable, so a mind's view survives her restart with the rest of her volatile state:
/// restored, it renders the same bytes, and the engine's saved page for it still matches.
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
Expand All @@ -99,6 +120,11 @@ pub struct View<T: Block> {
/// redoes. Never saved: a restored view has no unsent act.
#[serde(skip)]
act: Option<Mark>,
/// What the last sent prompt showed her, until the request that carried it is served:
/// taken there ([`View::take_submitted`]), so a prompt the engine never accepted is never
/// receipted. Never saved: a restored view has nothing in flight.
#[serde(skip)]
submitted: Option<Receipt>,
}

fn key(source: &str, item: &str) -> SourceId {
Expand Down Expand Up @@ -216,12 +242,14 @@ impl<T: Block> View<T> {
appended: Vec::new(),
motion: Motion::default(),
act: None,
submitted: None,
};
for ((source, items), grant) in sources.iter().zip(offered).zip(grants) {
let allot::Allotment { levels, mut fold } = allot(&**source, &items, grant);
let mut rendered = Vec::with_capacity(items.len());
for (item, level) in items.into_iter().zip(levels) {
let id = key(source.name(), &item.key);
let element = item.id();
let item_key = item.key.clone(); // its fingerprint after the level consumed it; once per item per start
let text = match level {
Level::Full => Some(crate::source::whole(&**source, item)),
Expand All @@ -239,14 +267,14 @@ impl<T: Block> View<T> {
view.folded.insert(id);
if let Some(block) = fold.take() {
rendered.push((fingerprint(FOLD_KEY, &block), block.chars()));
view.epoch.observe(key(source.name(), FOLD_KEY), block);
view.epoch.observe(key(source.name(), FOLD_KEY), None, Level::Folded, block);
}
continue;
}
};
if let Some(text) = text {
rendered.push((fingerprint(&item_key, &text), text.chars()));
view.epoch.observe(id, text);
view.epoch.observe(id, Some(element), level, text);
}
}
motion.record(source.name(), rendered);
Expand Down Expand Up @@ -304,6 +332,13 @@ impl<T: Block> View<T> {
/// so nothing may rewind past it and [`View::readmit`] answers `None` until the next act.
pub fn sent(&mut self) {
self.act = None;
self.submitted = Some(self.receipt());
}

/// The receipt of the last sent prompt, once: the caller takes it where the request that
/// carried it was served, and drops it when the request failed.
pub fn take_submitted(&mut self) -> Option<Receipt> {
self.submitted.take()
}

fn append(&mut self, sources: &[&dyn Source<T>], limit: Option<(usize, usize)>) -> Advance {
Expand All @@ -319,7 +354,7 @@ impl<T: Block> View<T> {
// An item with no pointer would leave her view entirely if collapsed (a peer's
// new turn), so it always arrives whole: admission never drops what she has
// not seen.
let fits = |chars: usize| limit.map_or(true, |(limit, _)| self.epoch.chars() + chars <= limit); // map_or: no limit admits every arrival whole
let fits = |chars: usize| limit.is_none_or(|(limit, _)| self.epoch.chars() + chars <= limit); // no limit admits every arrival whole
let oversized = limit.is_some_and(|(_, oversized)| crate::source::whole_chars(&item) > oversized);
let level = if self.collapsed.contains(&id) {
Level::Pointer
Expand All @@ -334,14 +369,15 @@ impl<T: Block> View<T> {
self.collapsed.insert(id.clone());
Level::Pointer
};
let element = item.id();
let text = match level {
Level::Full => Some(crate::source::whole(&**source, item)),
Level::Summary => item.summary.or(item.pointer),
Level::Pointer | Level::Folded => item.pointer,
};
if let Some(text) = text {
let chars = text.chars();
if let Observed::Appended { .. } = self.epoch.observe(id, text) {
if let Observed::Appended { .. } = self.epoch.observe(id, Some(element), level, text) {
advance.items += 1;
advance.chars += chars;
}
Expand All @@ -364,6 +400,29 @@ impl<T: Block> View<T> {
self.epoch.render()
}

/// What she is shown, in prompt order: each block after the head with its occurrence, the
/// level the view rendered it at, its version and its size. Taken where the prompt is
/// SUBMITTED (the caller binds owner, memory incarnation and request there), never at
/// rendering: a prompt built but not accepted was not seen (HER-TOOLS, the render receipt).
pub fn receipt(&self) -> Receipt {
Receipt {
epoch: self.epoch.id(),
items: self
.epoch
.events()
.iter()
.map(|event| Rendered {
source: event.source.clone(),
element: event.element,
level: event.level,
version: event.version,
retired: event.retired,
chars: event.text.chars(),
})
.collect(),
}
}

/// How each source moved across this view's starts.
pub fn motion(&self) -> &Motion {
&self.motion
Expand Down
10 changes: 1 addition & 9 deletions core/continuum-context/src/view/allot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,7 @@
use crate::epoch::Block;
use crate::source::{whole_chars, Item, Source};

/// How much of an item the view renders: whole, its summary, its pointer, or inside its
/// source's one fold block with the rest of the oldest run.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Level {
Full,
Summary,
Pointer,
Folded,
}
pub(super) use crate::level::Level;

/// How much of an item a level shows, for comparing two levels of one item.
pub(super) fn rank(level: &Level) -> u8 {
Expand Down
29 changes: 29 additions & 0 deletions core/continuum-context/src/view/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -563,3 +563,32 @@ fn an_act_appends_one_result_and_neither_turns_over_nor_grows_the_floor() -> Res
assert!(!view.start_would_restore(&[&actions], |_| vec![grant])?, "the same grant restores nothing");
Ok(())
}

// what this catches: a receipt that cannot say which occurrence she was shown, or at what level,
// or in what order (the acknowledgement of a task's end reads exactly this, HER-TASKS; the
// allocator reads it to learn what a grant bought).
#[test]
fn the_receipt_names_each_shown_occurrence_and_its_level_in_prompt_order() -> Result<(), GrantMismatch> {
let mut results = Fake::new("results", 1);
results.push("r1", &"a".repeat(3_000));
results.push("r2", "two");
let (mut view, _) = View::start(Vec::new(), &[&results as &dyn Source<String>], |_| vec![100])?;
results.push("r3", "three");
view.advance(&[&results]);
let receipt = view.receipt();
let id = |k: &str| Some(ElementId::of(&[k.as_bytes()]));
let shown: Vec<_> = receipt.items.iter().map(|r| (r.element, r.level)).collect();
assert_eq!(shown[shown.len() - 2..], [(id("r2"), Level::Full), (id("r3"), Level::Full)], "{shown:?}");
match shown[0] {
(element, Level::Pointer) => assert_eq!(element, id("r1")),
(None, Level::Folded) => {}
other => panic!("the oldest, too large for the grant, is not whole: {other:?}"),
}
assert_eq!(receipt.epoch, view.epoch_id());
assert_eq!(receipt.items.iter().map(|r| r.chars).sum::<usize>(), view.chars(), "the receipt accounts for every block after the head");
assert_eq!(view.take_submitted(), None, "nothing was sent yet");
view.sent();
assert_eq!(view.take_submitted(), Some(receipt), "the sent prompt's receipt, taken once");
assert_eq!(view.take_submitted(), None);
Ok(())
}
Loading