diff --git a/.claude/board/STATUS_BOARD.md b/.claude/board/STATUS_BOARD.md index fd3633011..cd058ed5c 100644 --- a/.claude/board/STATUS_BOARD.md +++ b/.claude/board/STATUS_BOARD.md @@ -7,6 +7,7 @@ Plan `.claude/plans/xlog-knowledge-spine-v1.md` (charter, DOCS ONLY); harvest `x | D-XLOG-KNOWLEDGE-0 | Charter: three IR routes kept separate, donor roles, gates G0..G8, STOP conditions | In PR (#2093), docs only | | D-XLOG-KNOWLEDGE-G0 | xlog.md + fork source harvest, page/claim/source manifest; 2.80x Scallop claim marked CONFLICT | Partial: 12 pages read, `/llms.txt` 404; manifest not built | | D-XLOG-KNOWLEDGE-G1 | Reproduce the coverage census at pinned SHAs; add Datafrog as an independent comparator; falsifiers | Shipped (#2095): census reproduced byte-identical (lance-graph `bdee050`, xlog `beac406` = tree of `656def9`). Datafrog arm (`datafrog_arm.rs`, AdaWorldAPI fork `edd7cfc`): agrees on 85/87 oracle-agrees rules, 2 not applicable (integer constant), 0 disagree; rungs unchanged. 4 disable runs red; broken join -> 68 disagreements in the census, 0 rung changes. Entry `2026-11-15-d-xlog-knowledge-g1-datafrog.md` | +| D-DIRSIM-DT64-LANES | dir-sim results through the DT64 lane socket at DR64 / DR256 / n x DR256 | In PR: `dt64::DirLanes` (feature `dt64`); axis from survivors (40,64 -> DR64; 65,200 -> DR256; 512 -> 2 x DR256; 1000 -> 4); cells read in place through `View` (overlay-correct, 0 alloc on the read path); old-version binding refused (`ForeignFrame`), foreign population refused (`NotUsers`); 4 of 5 disables red (frame-revision disable inert: the refusal is per store instance). Lanes: UPN + primary SMTP only | | D-DIRSIM-LINEAR-RESTORE | `VersionStore::restore` continues the previous overlay along a linear history | In PR: replay+restore 1.19 ms at 1 024 re-reads (was 50 ms), 0.45 ms at 128; 64-step chain applies exactly 64 changes (old fold 2 080); branch re-folds from root; disable red. Closes the quadratic-replay open point of `2026-11-16-d-dirsim-delta-read-1.md` | | D-DIRSIM-DELTA-READ-1 | Read what changed between observations from the stored deltas; history cost probe | In PR: `VersionStore::history` (34-47 ns, 0 alloc at 1..1024 re-reads); `view`/`diff` linear in lineage; replay quadratic (50 ms cold at 1024) - linear restore proposed. Entry `2026-11-16-d-dirsim-delta-read-1.md` | | D-DIRSIM-REOBSERVE | dir-sim stores a re-read as its verified changes; plan intent from the nearest observation | In PR: `VersionStore::reobserve`; one membership change = 1 change, 125 B log batch vs 11 094 B for a second root; 3 disable runs red. Entry `2026-11-16-d-dirsim-reobserve.md` | diff --git a/.github/workflows/identity.yml b/.github/workflows/identity.yml index 04a9465e7..81ed85e2b 100644 --- a/.github/workflows/identity.yml +++ b/.github/workflows/identity.yml @@ -97,6 +97,10 @@ jobs: # view_actors and membership_path need the rbac feature; without # this step they compile only locally. run: cargo test --manifest-path crates/lance-graph-dir-sim/Cargo.toml --features rbac + - name: Run the simulator's DT64 lane tests (feature dt64) + # dt64_lanes needs the dt64 feature; without this step it compiles + # only locally. + run: cargo test --manifest-path crates/lance-graph-dir-sim/Cargo.toml --features dt64 --test dt64_lanes - name: The tests pinning Exchange behaviour exist run: | cargo test -q --manifest-path crates/lance-graph-dir-sim/Cargo.toml -- --list \ diff --git a/crates/lance-graph-dir-sim/Cargo.toml b/crates/lance-graph-dir-sim/Cargo.toml index 22600ef72..b485a47c2 100644 --- a/crates/lance-graph-dir-sim/Cargo.toml +++ b/crates/lance-graph-dir-sim/Cargo.toml @@ -38,6 +38,9 @@ ogar-az = { git = "https://github.com/AdaWorldAPI/OGAR", branch = "main" } # The actor source over a view (`actors`, feature `rbac`): the contract's # zero-dep `ActorSource` socket. lance-graph-contract = { path = "../lance-graph-contract", optional = true } +# The DT64 lane socket over a version (`dt64`, feature `dt64`): dir-sim as a +# LaneSource + SelectionSource, its query results as DR selections. +lance-graph-dt64 = { path = "../lance-graph-dt64", optional = true } # Group-to-role grants are the authority's versioned policy # (`ogar_rbac::GroupRolePolicy`); `GroupRoles::from_policy` reads one # version of it. The directory supplies membership only. @@ -53,6 +56,7 @@ lance-graph-contract = { path = "../lance-graph-contract" } [features] rbac = ["dep:lance-graph-contract", "dep:ogar-rbac"] +dt64 = ["dep:lance-graph-dt64", "dep:lance-graph-contract"] # mask-risc names ndarray by its canonical git coordinate; point it at the # sibling checkout so this workspace has one ndarray identity and needs no diff --git a/crates/lance-graph-dir-sim/src/dt64.rs b/crates/lance-graph-dir-sim/src/dt64.rs new file mode 100644 index 000000000..88855f75a --- /dev/null +++ b/crates/lance-graph-dir-sim/src/dt64.rs @@ -0,0 +1,216 @@ +//! A version's users through the DT64 lane socket, and dir-sim results as DR +//! selections. +//! +//! ```text +//! VersionStore::view(v) ──► DirLanes (LaneSource + SelectionSource) +//! users_with_key / subtree / … ──► Kept ──select──► (sel, Axis) +//! Axis = DR64 | DR256 | n × DR256 +//! BindStore::bind_lanes ──► LaneBinding::selected(field, sel) +//! ──► (UserLane, &[u32]) read lane.get(i) per i +//! ``` +//! +//! **A cell is a virtual tuple.** A [`UserLane`] holds no column. Reading row +//! `i` asks the version's [`View`] for that user's attribute, so a base value, +//! an overridden value and a user the version created all read correctly, and +//! nothing is copied into a second object universe. `A[i]:B[i]` is two such +//! reads at one known `i`; there is no tuple, row object or join. +//! +//! **The DR axis follows the survivors.** A selection's axis is +//! `Axis::for_survivors(kept.len())`: up to 64 rows one DR64 tile, up to 256 one +//! DR256 tile, more `ceil(n / 256)` DR256 tiles (512 rows are two). The count is +//! a popcount of the result bitmap; choosing the axis decodes no row. The +//! selection's position list, the socket's form (`SelectionSource`), is built +//! once per selection, bounded by its survivors, never per field or per read. +//! +//! **One version, one frame store.** A [`DirLanes`] is built over one version +//! and owns the frame store its frames come from. A binding made over another +//! version's `DirLanes` is refused (`ForeignFrame`) before any lane is +//! borrowed, so a reader cannot read one version's selection against another +//! version's cells. +//! +//! `Scope` is a consistency check between reader, lanes and selections, as +//! everywhere in DT64; it is not authorization. + +use lance_graph_contract::ontology::FieldRef; +use lance_graph_dt64::dr::{Axis, Frame, FrameRevisions, FrameStore, Scope}; +use lance_graph_dt64::{CoordSpace, LaneAddr, LaneSource, SchemaRev, SelAddr, SelectionSource}; +use ogar_dir_sim::{Attribute, VersionId}; + +use crate::{Kept, UserOrdinal, View}; + +/// Field 0 of the user lanes: the UPN value. +pub const F_UPN: u8 = 0; +/// Field 1 of the user lanes: the primary SMTP value. +pub const F_SMTP: u8 = 1; + +/// The schema revision these lanes serve. +pub const LANE_REV: SchemaRev = SchemaRev(1); + +/// One user attribute of one version, read cell by cell. It holds no values. +#[derive(Clone, Copy)] +pub struct UserLane<'a, 's> { + view: &'a View<'s>, + attr: Attribute, +} + +impl UserLane<'_, '_> { + /// The attribute's value id for the user at `row`; `None` when the user + /// has no such value, or `row` is past the version's users. + pub fn get(&self, row: u32) -> Option { + let g = self.view.user_guid(UserOrdinal(u16::try_from(row).ok()?))?; + self.view.attr(&g, self.attr).map(|v| v.0) + } +} + +/// Why a result was not admitted as a selection. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SelectRefusal { + /// The result was computed over another population size than this + /// version's users (a group result, or another version's users). + NotUsers { + /// Rows of the result. + rows: usize, + /// Users of this version. + users: usize, + }, + /// More selections than a `u16` id addresses. + Full, +} + +/// A selection the source holds. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Selected { + /// Its id for [`lance_graph_dt64::LaneBinding::selected`]. + pub sel: u16, + /// The DR axis its survivors take. + pub axis: Axis, +} + +/// A version's users as a DT64 lane and selection source. +pub struct DirLanes<'a, 's> { + view: &'a View<'s>, + version: VersionId, + class: u32, + scope: Scope, + frames: FrameStore, + selections: Vec>, +} + +impl<'a, 's> DirLanes<'a, 's> { + /// The users of `view` (version `version`), bound as class `class` for + /// reader `scope`. + pub fn new(view: &'a View<'s>, version: VersionId, class: u32, scope: Scope) -> Self { + Self { + view, + version, + class, + scope, + frames: FrameStore::new(FrameRevisions { + source: version.0, + relation_map: 0, + coordinates: version.0, + }), + selections: Vec::new(), + } + } + + /// The row order the lanes and selections are in: this version's user + /// ordinals. + pub fn space(&self) -> CoordSpace { + CoordSpace { + population: u64::from(self.class), + coordinates: self.version.0, + } + } + + /// The DR axis the version's whole user population takes. + pub fn identity_axis(&self) -> Axis { + Axis::for_survivors(self.view.users_len()) + } + + /// Hold `kept` (a result over this version's users) as a selection. + /// + /// # Errors + /// + /// [`SelectRefusal`]: the result is over another population, or the + /// source holds `u16::MAX + 1` selections already. + pub fn select(&mut self, kept: &Kept) -> Result { + let users = self.view.users_len(); + if kept.universe() != users { + return Err(SelectRefusal::NotUsers { + rows: kept.universe(), + users, + }); + } + let sel = u16::try_from(self.selections.len()).map_err(|_| SelectRefusal::Full)?; + let axis = Axis::for_survivors(kept.len()); + // Rows are user ordinals, at most 65,536, so each fits a `u32`. + self.selections + .push(kept.rows().into_iter().map(|r| r as u32).collect()); + Ok(Selected { sel, axis }) + } +} + +impl LaneSource for DirLanes<'_, '_> { + type Lane<'b> + = UserLane<'b, 'b> + where + Self: 'b; + + fn lane_of( + &self, + class: u32, + rev: SchemaRev, + field: u8, + _basis: &FieldRef, + _frame: &Frame, + ) -> Option { + if class != self.class || rev != LANE_REV || field > F_SMTP { + return None; + } + Some(LaneAddr { + space: self.space(), + lane: u16::from(field), + scope: self.scope, + }) + } + + fn borrow(&self, addr: &LaneAddr) -> Option> { + if addr.space != self.space() { + return None; + } + let attr = match addr.lane { + 0 => Attribute::Upn, + 1 => Attribute::PrimarySmtp, + _ => return None, + }; + Some(UserLane { + view: self.view, + attr, + }) + } + + fn frames(&self) -> &FrameStore { + &self.frames + } +} + +impl SelectionSource for DirLanes<'_, '_> { + fn selection_of(&self, sel: u16, _frame: &Frame) -> Option { + self.selections.get(usize::from(sel))?; + Some(SelAddr { + space: self.space(), + sel, + scope: self.scope, + }) + } + + fn borrow_positions(&self, addr: &SelAddr) -> Option<&[u32]> { + if addr.space != self.space() { + return None; + } + self.selections + .get(usize::from(addr.sel)) + .map(Vec::as_slice) + } +} diff --git a/crates/lance-graph-dir-sim/src/exec.rs b/crates/lance-graph-dir-sim/src/exec.rs index f4f45098e..822518c4d 100644 --- a/crates/lance-graph-dir-sim/src/exec.rs +++ b/crates/lance-graph-dir-sim/src/exec.rs @@ -58,6 +58,21 @@ impl Kept { materialize_rows(&self.bits, self.n_rows) } + /// How many rows were kept: a popcount, no row is decoded. + pub fn len(&self) -> usize { + self.bits.iter().map(|w| w.count_ones() as usize).sum() + } + + /// Whether no row was kept. + pub fn is_empty(&self) -> bool { + self.bits.iter().all(|w| *w == 0) + } + + /// Rows of the relation the program ran over (kept or not). + pub fn universe(&self) -> usize { + self.n_rows + } + /// Add one row (a delta-sized correction, e.g. an overridden value). pub(crate) fn set(&mut self, row: usize) { debug_assert!(row < self.n_rows); diff --git a/crates/lance-graph-dir-sim/src/lib.rs b/crates/lance-graph-dir-sim/src/lib.rs index 711c3ebc9..27df83d3c 100644 --- a/crates/lance-graph-dir-sim/src/lib.rs +++ b/crates/lance-graph-dir-sim/src/lib.rs @@ -39,6 +39,8 @@ pub mod actors; pub mod ad; pub mod bind; pub mod cloud; +#[cfg(feature = "dt64")] +pub mod dt64; mod exec; pub mod groups; pub mod image; diff --git a/crates/lance-graph-dir-sim/tests/dt64_lanes.rs b/crates/lance-graph-dir-sim/tests/dt64_lanes.rs new file mode 100644 index 000000000..e35f313c0 --- /dev/null +++ b/crates/lance-graph-dir-sim/tests/dt64_lanes.rs @@ -0,0 +1,276 @@ +//! dir-sim results through the DT64 lane socket, at every DR tile width. +//! +//! A `subtree` result over a version's users is held as a selection; its DR +//! axis follows its survivors (DR64, DR256, 2 × DR256, n × DR256). Fields are +//! read at the selected rows as virtual tuples through the version's view, and +//! compared with the view itself as the oracle. +#![cfg(feature = "dt64")] + +use std::alloc::{GlobalAlloc, Layout, System}; +use std::cell::Cell; + +use lance_graph_contract::class_view::{ClassId, ClassView, WideFieldMask}; +use lance_graph_contract::ontology::{DisplayTemplate, FieldRef}; +use lance_graph_dir_sim::dt64::{DirLanes, SelectRefusal, F_SMTP, F_UPN, LANE_REV}; +use lance_graph_dir_sim::{ + groups_where, subtree, GroupWhere, NodeKind, Observation, ObservedNode, UserOrdinal, ValueId, + VersionStore, +}; +use lance_graph_dt64::dr::{Axis, FrameRefusal, Scope, Width}; +use lance_graph_dt64::{ + BindStore, ClassSchema, Extent, LaneBinding, LaneRefusal, LaneRequest, LaneSource, RouteAt, +}; +use ogar_dir_core::{DirectoryScope, Dn128, Guid128}; +use ogar_dir_sim::Attribute; + +struct Counting; +thread_local! { + static ALLOCS: Cell = const { Cell::new(0) }; +} +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, l: Layout) -> *mut u8 { + let _ = ALLOCS.try_with(|a| a.set(a.get() + 1)); + // SAFETY: forwarded unchanged to the system allocator. + unsafe { System.alloc(l) } + } + unsafe fn dealloc(&self, p: *mut u8, l: Layout) { + // SAFETY: forwarded unchanged to the system allocator. + unsafe { System.dealloc(p, l) } + } +} +#[global_allocator] +static GLOBAL: Counting = Counting; +fn allocs() -> u64 { + ALLOCS.with(Cell::get) +} + +const SCOPE: DirectoryScope = DirectoryScope(Guid128([0x5C; 16])); +const USER: u32 = 0x0D1B_0001; +const VIEW_CLASS: ClassId = 0x0D1B; +const POSITION: u16 = 3; +const READER: Scope = Scope { id: 7 }; + +struct Basis(Vec); +impl ClassView for Basis { + fn fields(&self, class: ClassId) -> &[FieldRef] { + if class == VIEW_CLASS { + &self.0 + } else { + &[] + } + } + fn template(&self, _class: ClassId) -> DisplayTemplate { + DisplayTemplate::Detail + } + fn dolce_category_id(&self, _class: ClassId) -> u8 { + 0 + } +} +fn basis() -> Basis { + Basis(vec![ + FieldRef::new("dir:userPrincipalName", "UPN"), + FieldRef::new("dir:primarySmtp", "Primary SMTP"), + ]) +} + +fn user(u: usize) -> Guid128 { + let mut b = [0u8; 16]; + b[0] = 1; + b[1..3].copy_from_slice(&(u as u16).to_le_bytes()); + Guid128(b) +} + +/// `inside` users under OU [1], `outside` users under OU [2]. +fn observation(inside: usize, outside: usize) -> Observation { + let mut o = Observation { + scope: SCOPE, + nodes: Vec::new(), + members: Vec::new(), + }; + for u in 0..inside + outside { + let mut n = + ObservedNode::user(&format!("u{u}@example.test"), &format!("m{u}@example.test")); + n.dn = Some(Dn128::new(if u < inside { &[1] } else { &[2] }).unwrap()); + o.nodes.push((user(u), n)); + } + o +} + +fn store() -> BindStore { + let mut s = BindStore::new(); + s.register( + &basis(), + USER, + ClassSchema { + schema_rev: LANE_REV, + field_count: 2, + extent: Extent::DR64_CUBE, + }, + Vec::new(), + ) + .unwrap(); + s +} + +fn bind( + store: &BindStore, + lanes: &DirLanes<'_, '_>, + route: RouteAt, + frame: &lance_graph_dt64::dr::Frame, +) -> Result { + store.bind_lanes( + &basis(), + lanes.frames(), + lanes, + LaneRequest { + route, + rev: LANE_REV, + fields: &WideFieldMask::from_positions(&[F_UPN, F_SMTP]), + frame, + scope: READER, + selection: lanes.space(), + }, + ) +} + +fn inside_ou() -> Dn128 { + Dn128::new(&[1]).unwrap() +} + +/// The axis follows the survivors at each width, and every selected cell +/// equals the view's own attribute (the oracle) without any allocation on the +/// read path. Falsifier: a fixed axis, an axis from the population instead of +/// the survivors, or a lane read that ignores the row. +#[test] +fn every_tile_width_reads_the_selected_cells_as_the_view_does() { + let cases = [ + (40, Axis::new(Width::W64, 1)), + (64, Axis::new(Width::W64, 1)), + (65, Axis::new(Width::W256, 1)), + (200, Axis::new(Width::W256, 1)), + (512, Axis::new(Width::W256, 2)), + (1000, Axis::new(Width::W256, 4)), + ]; + for (inside, want) in cases { + let mut st = VersionStore::new(); + let v = st.observe("ad", 0, observation(inside, 7)).unwrap(); + let view = st.view(v).unwrap(); + let mut lanes = DirLanes::new(&view, v, USER, READER); + let kept = subtree(&view, SCOPE, NodeKind::User, &inside_ou()).unwrap(); + assert_eq!(kept.len(), inside, "the fixture selects `inside` users"); + let picked = lanes.select(&kept).unwrap(); + assert_eq!(picked.axis, want, "{inside} survivors"); + assert_eq!( + lanes.identity_axis(), + Axis::for_survivors(inside + 7), + "the population's axis is its own" + ); + + let mut bs = store(); + let version = bs.route(POSITION, USER).unwrap(); + let route = RouteAt { + position: POSITION, + version, + }; + let frame = lanes.frames().seal(); + let b = bind(&bs, &lanes, route, &frame).unwrap(); + + let basis = basis(); + let a0 = allocs(); + let mut agree = 0usize; + for (f, attr) in [(F_UPN, Attribute::Upn), (F_SMTP, Attribute::PrimarySmtp)] { + let (lane, rows) = b + .selected(&bs, &basis, lanes.frames(), &lanes, f, picked.sel) + .unwrap(); + assert_eq!(rows.len(), inside); + for &r in rows { + let g = view.user_guid(UserOrdinal(r as u16)).unwrap(); + if lane.get(r) == view.attr(&g, attr).map(|x| x.0) && lane.get(r).is_some() { + agree += 1; + } + } + } + assert_eq!(allocs() - a0, 0, "the read path allocates nothing"); + assert_eq!(agree, 2 * inside, "every selected cell equals the oracle"); + } +} + +/// A re-observed version reads its overridden and created users through the +/// same socket, and a binding made over the previous version is refused +/// before a lane is borrowed. Falsifier: a lane over the base snapshot only +/// (the override or the created user reads wrong), or a shared frame store. +#[test] +fn a_reobserved_version_reads_its_overlay_and_refuses_the_old_binding() { + let mut st = VersionStore::new(); + let v0 = st.observe("ad", 0, observation(3, 1)).unwrap(); + let mut next = observation(3, 1); + next.nodes[1].1.primary_smtp = Some("moved@example.test".into()); + let mut created = ObservedNode::user("new@example.test", "new-mail@example.test"); + created.dn = Some(inside_ou()); + next.nodes.push((user(9), created)); + let v1 = st.reobserve("ad", 1, next).unwrap(); + assert_ne!(v0, v1); + + let mut bs = store(); + let version = bs.route(POSITION, USER).unwrap(); + let route = RouteAt { + position: POSITION, + version, + }; + + let old_view = st.view(v0).unwrap(); + let old = DirLanes::new(&old_view, v0, USER, READER); + let old_binding = bind(&bs, &old, route, &old.frames().seal()).unwrap(); + + let view = st.view(v1).unwrap(); + assert!(view.delta_len() > 0, "v1 is an overlay over v0's snapshot"); + let mut lanes = DirLanes::new(&view, v1, USER, READER); + let kept = subtree(&view, SCOPE, NodeKind::User, &inside_ou()).unwrap(); + assert_eq!(kept.len(), 4, "three observed and one created user inside"); + let picked = lanes.select(&kept).unwrap(); + + // The old binding against the new version: refused, nothing borrowed. + assert_eq!( + old_binding + .selected(&bs, &basis(), lanes.frames(), &lanes, F_SMTP, picked.sel) + .err(), + Some(LaneRefusal::Frame(FrameRefusal::ForeignFrame)) + ); + + let b = bind(&bs, &lanes, route, &lanes.frames().seal()).unwrap(); + let (lane, rows) = b + .selected(&bs, &basis(), lanes.frames(), &lanes, F_SMTP, picked.sel) + .unwrap(); + let read = |g: Guid128| { + let r = view.user_ordinal(&g).unwrap().0 as u32; + assert!(rows.contains(&r)); + lane.get(r) + .and_then(|id| view.dicts().value(ValueId(id))) + .map(str::to_string) + }; + assert_eq!(read(user(1)).as_deref(), Some("moved@example.test")); + assert_eq!(read(user(9)).as_deref(), Some("new-mail@example.test")); + assert_eq!(read(user(0)).as_deref(), Some("m0@example.test")); +} + +/// A result over groups is not a selection of users. Falsifier: admitting any +/// bitmap whatever its population. +#[test] +fn a_result_over_another_population_is_refused() { + let mut o = observation(5, 0); + for g in 0..3 { + o.nodes.push((user(100 + g), ObservedNode::group())); + } + let mut st = VersionStore::new(); + let v = st.observe("ad", 0, o).unwrap(); + let view = st.view(v).unwrap(); + let mut lanes = DirLanes::new(&view, v, USER, READER); + let groups = groups_where(&view, &GroupWhere::And(Vec::new())); + assert_eq!( + lanes.select(&groups), + Err(SelectRefusal::NotUsers { rows: 3, users: 5 }) + ); + // Silence half: a users result of the same version is admitted. + let users = subtree(&view, SCOPE, NodeKind::User, &inside_ou()).unwrap(); + assert!(lanes.select(&users).is_ok()); +}