extern crate alloc;
use crate::kairos::{Clock, TickCounter};
use crate::metis::{Anchor, Cut, Dot, DotSet, Dotted, Locus, Rhapsody};
use super::super::d;
use crate::metis::dot::RawDot;
const SCALE: u64 = 65_536;
const FRAME_HEADER: usize = 5;
const ORIGIN_LOCUS: usize = 30;
const DOT_LOCUS: usize = 42;
fn woven_document(station: u32, n: u64) -> Dotted<Rhapsody> {
let clock = Clock::with_default_config(TickCounter::new(), station).unwrap();
let mut rhapsody = Rhapsody::new();
let mut context = DotSet::new();
let mut prev: Option<Dot> = None;
for index in 1..=n {
let anchor = prev.map_or(Anchor::Origin, |dot| Anchor::After(dot.into()));
let rank = clock.now(0u16);
let dot = d(station, index);
assert!(
rhapsody.weave(dot, Locus { anchor, rank }),
"every woven dot is fresh"
);
let _ = context.insert(dot);
prev = Some(dot);
}
Dotted::try_new(rhapsody, context).unwrap()
}
fn owed_probe(state: &Dotted<Rhapsody>, scale: usize) -> (usize, usize, usize, usize) {
let mut one_behind = DotSet::new();
for index in 1..SCALE {
let _ = one_behind.insert(d(1, index));
}
let owed = state.delta_for(&one_behind);
let owed_skeleton = owed.store().skeleton_len();
let owed_frame = owed.store().to_bytes().len();
assert_eq!(
owed_skeleton, scale,
"one owed keystroke ships the whole skeleton through the bare owed read"
);
assert!(
owed_frame > 2 * 1024 * 1024,
"the one-keystroke owed fragment frames at snapshot size"
);
let witnessed = state.delta_for_witnessed(&one_behind, &one_behind);
let witnessed_skeleton = witnessed.store().skeleton_len();
let witnessed_frame = witnessed.store().to_bytes().len();
assert_eq!(
witnessed_skeleton, 1,
"one owed keystroke ships one locus through the witnessed read"
);
assert!(
witnessed_frame < 128,
"the witnessed one-keystroke fragment frames in tens of bytes"
);
assert_eq!(
state.merge(&witnessed).store().order(),
state.store().order(),
"the witnessed fragment converges the peer exactly"
);
(
owed_skeleton,
owed_frame,
witnessed_skeleton,
witnessed_frame,
)
}
fn snapshot_wire_pins(
rhapsody: &Rhapsody,
scale: usize,
runs: usize,
) -> (alloc::vec::Vec<u8>, alloc::vec::Vec<u8>) {
let snapshot = rhapsody.to_snapshot_bytes();
let v2 = rhapsody.to_bytes();
let suffix = 5 + 2 * 16;
assert_eq!(v2.len(), 5 + 30 + (scale - 1) * 42 + suffix);
assert_eq!(snapshot.len(), 9 + runs * 46 + (scale - runs) * 6 + suffix);
assert!(
snapshot.len() * 6 < v2.len(),
"the late-joiner bootstrap compresses at least sixfold on honest traffic"
);
assert_eq!(
Rhapsody::from_snapshot_bytes(&snapshot).as_ref(),
Ok(rhapsody),
"the editor-scale snapshot round-trips"
);
(snapshot, v2)
}
fn alternating_document(chunk: u64, chunks: u64) -> Rhapsody {
let clock_a = Clock::with_default_config(TickCounter::new(), 1).unwrap();
let clock_b = Clock::with_default_config(TickCounter::new(), 2).unwrap();
let mut rhapsody = Rhapsody::new();
let mut prev: Option<Dot> = None;
let mut minted = [0u64; 2];
for turn in 0..chunks {
let station = u32::try_from(turn % 2).unwrap() + 1;
let clock = if station == 1 { &clock_a } else { &clock_b };
for _ in 0..chunk {
if let Some(anchor) = prev
&& let Some(top) = rhapsody.children_of(Anchor::After(anchor.into())).next()
&& let Some(locus) = rhapsody.locus(top)
{
clock.observe(locus.rank);
}
minted[station as usize - 1] += 1;
let dot = d(station, minted[station as usize - 1]);
let anchor = prev.map_or(Anchor::Origin, |dot| Anchor::After(dot.into()));
assert!(rhapsody.weave(
dot,
Locus {
anchor,
rank: clock.now(0u16),
}
));
prev = Some(dot);
}
}
rhapsody
}
fn order_thread_pins(rhapsody: &Rhapsody, order: &[Dot], scale: usize, runs: usize) {
assert_eq!(
rhapsody.order_thread_fragments(),
runs,
"the order thread coalesces to exactly the maximal chain runs"
);
assert_eq!(
rhapsody.order_thread_region_nodes(),
scale,
"the region segments cover every placed dot exactly once"
);
assert_eq!(
rhapsody.order_thread_region_segments(),
runs,
"the endpoint plane coalesces to exactly the maximal chain runs"
);
assert_eq!(
rhapsody.order_thread_region_forest_nodes(),
runs,
"one link-cut node per run-boundary edge endpoint, none elsewhere"
);
let region_dot = core::mem::size_of::<(u32, u64)>();
let node_id = core::mem::size_of::<u32>();
let link_node = 3 * node_id;
let endpoint_before = scale * (2 * link_node + region_dot + (region_dot + node_id));
let endpoint_after = runs * ((region_dot + node_id) + region_dot + link_node + region_dot);
assert!(
endpoint_after * 32 < endpoint_before,
"the segmented endpoint plane undercuts the per-dot form at document scale \
({endpoint_after} against {endpoint_before} bytes)"
);
#[cfg(feature = "std")]
std::println!(
"endpoint plane: {endpoint_after} bytes exact ({runs} segments) against the per-dot form's {endpoint_before} (arc 11 phase five)"
);
assert_eq!(rhapsody.order_len(), scale);
for offset in [0usize, 1, 63, 64, scale / 2, scale - 2, scale - 1] {
let dot = rhapsody.order_at(offset).expect("in-range offsets resolve");
assert_eq!(order[offset], dot);
assert_eq!(rhapsody.offset_of(dot), Some(offset));
}
assert_eq!(rhapsody.order_at(scale), None);
assert_eq!(
rhapsody
.order_walk_rev()
.take(3)
.collect::<alloc::vec::Vec<_>>(),
[order[scale - 1], order[scale - 2], order[scale - 3]],
"the reverse walk reads the tail without an order() pass"
);
}
fn child_plane_pins(
rhapsody: &Rhapsody,
scale: usize,
runs: usize,
coalesced_document: usize,
phase_four_document: usize,
) {
let child_explicit = rhapsody.child_explicit_children();
assert_eq!(
child_explicit, runs,
"the child plane stores exactly the run-boundary children"
);
assert_eq!(
rhapsody.child_explicit_buckets(),
runs,
"each run-boundary child is the sole exception under its own anchor"
);
assert_eq!(scale % child_explicit, 0);
assert!(
phase_four_document * 4 < coalesced_document,
"the coalesced child plane undercuts the phase-two form at document scale \
({phase_four_document} against {coalesced_document} bytes)"
);
}
fn count_maximal_runs(rhapsody: &Rhapsody, order: &[Dot]) -> usize {
let mut runs = 1usize;
for pair in order.windows(2) {
let (prev, next) = (pair[0], pair[1]);
let continues = next.station() == prev.station()
&& next.counter() == prev.counter() + 1
&& rhapsody.locus(next).map(|l| l.anchor) == Some(Anchor::After(prev.into()));
if !continues {
runs += 1;
}
}
runs
}
#[cfg_attr(miri, ignore)]
#[test]
fn ordering_closed_forms_and_run_coalescing() {
let entry = core::mem::size_of::<((u32, u64), Locus)>();
let child_share = core::mem::size_of::<(u32, u64)>();
let floor_per_char = entry + child_share;
assert!(
floor_per_char >= 48,
"the size_of floor per woven element holds ({floor_per_char} bytes)"
);
let scale = usize::try_from(SCALE).unwrap();
let document_floor = floor_per_char * scale;
assert!(
document_floor > 3 * 1024 * 1024,
"a 65,536-char document's ordering state floors in megabytes before map overhead"
);
let slot = core::mem::size_of::<Option<core::num::NonZeroU32>>();
let column = core::mem::size_of::<Locus>();
let interned_per_char = slot + column + child_share;
assert!(
interned_per_char < floor_per_char,
"the interned plane undercuts the map form's own floor \
({interned_per_char} against {floor_per_char} bytes)"
);
let interned_document = interned_per_char * scale;
assert!(
interned_document < document_floor,
"the interned plane undercuts the map floor at document scale \
({interned_document} against {document_floor} bytes)"
);
let chunk = 64u64;
let chunks = SCALE / chunk;
let rhapsody = alternating_document(chunk, chunks);
let order = rhapsody.order();
assert_eq!(order.len(), scale);
let runs = count_maximal_runs(&rhapsody, &order);
let chunks = usize::try_from(chunks).unwrap();
assert_eq!(
runs, chunks,
"honest alternating traffic coalesces to exactly one run per authored chunk"
);
let explicit = rhapsody.skeleton_explicit_entries();
assert_eq!(
explicit, runs,
"the plane's explicit entries are exactly the maximal chain runs"
);
let coalesced_document = scale * slot + explicit * column + scale * child_share;
assert!(
coalesced_document < interned_document,
"the coalesced plane undercuts the phase-one form at document scale \
({coalesced_document} against {interned_document} bytes)"
);
let child_explicit = rhapsody.child_explicit_children();
let phase_four_document = scale * slot + explicit * column + child_explicit * child_share;
child_plane_pins(
&rhapsody,
scale,
runs,
coalesced_document,
phase_four_document,
);
order_thread_pins(&rhapsody, &order, scale, runs);
let (snapshot, v2) = snapshot_wire_pins(&rhapsody, scale, runs);
assert_eq!(
snapshot[1..5],
u32::try_from(explicit).unwrap().to_be_bytes()
);
assert_eq!(v2[1..5], u32::try_from(scale).unwrap().to_be_bytes());
#[cfg(feature = "std")]
{
std::println!("\n=== ORDERING CLOSED FORMS (arc 11, S192) ===");
std::println!(
"size_of floor/char: {floor_per_char} B (entry {entry} + child share {child_share}; map overhead on top)"
);
std::println!("65,536-char floor: {document_floor} bytes");
std::println!(
"interned plane/char: {interned_per_char} B (slot {slot} + locus column {column} + child share {child_share}; no map overhead on the identity plane)"
);
std::println!("65,536-char interned: {interned_document} bytes");
std::println!(
"coalesced plane: {coalesced_document} bytes exact ({scale} slots x {slot} B + {explicit} explicit loci x {column} B + child share; arc 11 phase two)"
);
std::println!(
"coalesced children: {phase_four_document} bytes exact ({child_explicit} explicit children x {child_share} B replace the {scale}-element child share; arc 11 phase four)"
);
std::println!(
"run coalescing: {scale} elements / {runs} runs = {} elements/run",
scale / runs
);
std::println!(
"snapshot frame: {} bytes against v2's {} ({}x; arc 5, PRD 0023)",
snapshot.len(),
v2.len(),
v2.len() / snapshot.len()
);
std::println!("============================================\n");
}
}
#[cfg_attr(miri, ignore)]
#[test]
fn editor_scale_probe() {
let state = woven_document(1, SCALE);
let scale = usize::try_from(SCALE).unwrap();
assert_eq!(state.store().skeleton_len(), scale);
assert_eq!(state.store().visible_len(), scale);
let frame = state.store().to_bytes();
let suffix = state.context().to_bytes().len();
assert_eq!(
frame.len(),
FRAME_HEADER + ORIGIN_LOCUS + DOT_LOCUS * (scale - 1) + suffix,
"the v2 snapshot frame is linear at 42 bytes per dot-anchored locus"
);
assert!(
frame.len() > 2 * 1024 * 1024,
"a 65,536-char document snapshot exceeds two megabytes"
);
let order = state.store().order();
assert_eq!(order.len(), scale, "one render visits every woven element");
let viewport = 100;
let anchor_slot = scale / 2;
let resume = order[anchor_slot - 1];
let window: alloc::vec::Vec<Dot> = state
.store()
.order_walk_after(resume)
.expect("a placed element resumes")
.take(viewport)
.collect();
assert_eq!(
window,
order[anchor_slot..anchor_slot + viewport],
"the mid-document viewport agrees with the whole-order slice"
);
let cut = Cut::floor_of(state.context());
let mut remote = Rhapsody::new();
let remote_clock = Clock::with_default_config(TickCounter::new(), 2).unwrap();
assert!(
remote.weave(
d(2, 1),
Locus {
anchor: Anchor::After(RawDot {
station: 1,
counter: SCALE
}),
rank: remote_clock.now(0u16),
},
),
"the remote keystroke weaves fresh"
);
let mut remote_context = DotSet::new();
let _ = remote_context.insert(d(2, 1));
let delta = Dotted::try_new(remote, remote_context).unwrap();
let merged = state.merge(&delta);
let floored = merged.delta_for_since(&cut);
assert!(
floored.context().to_bytes().len() <= 64,
"the floored per-keystroke context frame stays tens of bytes at 65k chars"
);
let (owed_skeleton, owed_frame, witnessed_skeleton, witnessed_frame) =
owed_probe(&state, scale);
assert!(
owed_skeleton > witnessed_skeleton && owed_frame > witnessed_frame,
"the witnessed read is smaller on both loci and bytes"
);
let per_keystroke_rebuild = scale + 1;
let session_rebuild_total = scale * (scale + 1) / 2;
let session_weave_total = scale;
assert!(
per_keystroke_rebuild > scale,
"one composed keystroke re-touches the whole skeleton"
);
assert!(
session_rebuild_total / session_weave_total > 32_000,
"a composed 65k session re-pays the rebuild tens of thousands of times over the weave path"
);
#[cfg(feature = "std")]
{
let frame_len = frame.len();
let floored_context = floored.context().to_bytes().len();
std::println!("\n=== EDITOR-SCALE PROBE (S181, 65,536 chars) ===");
std::println!("snapshot frame: {frame_len} bytes (42 bytes/locus, linear)");
std::println!("per-render order() visits: {scale} (O(n) per caret re-render)");
std::println!("floored keystroke context: {floored_context} bytes (scale-invariant)");
std::println!(
"owed fragment, one behind: {owed_skeleton} loci / {owed_frame} bytes (bare owed read)"
);
std::println!(
"witnessed owed, one behind: {witnessed_skeleton} locus / {witnessed_frame} bytes (arc-10 cure)"
);
std::println!(
"composed keystroke rebuild: {per_keystroke_rebuild} entries (weave path: 1); session total {session_rebuild_total} vs {session_weave_total}"
);
std::println!("===============================================\n");
}
}