diff --git a/.claude/board/STATUS_BOARD.md b/.claude/board/STATUS_BOARD.md index 53bc60f07..ad0657959 100644 --- a/.claude/board/STATUS_BOARD.md +++ b/.claude/board/STATUS_BOARD.md @@ -9,6 +9,7 @@ Plan `.claude/plans/xlog-knowledge-spine-v1.md` (charter, DOCS ONLY); harvest `x | 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-LICENSE-DR64 | Licences from ogar-az (OGAR #380) as DR64 planes over a dir-sim version: <=64 (sku, via, state) codes per tenant, read plane, exact capacity | In PR: `license::LicensePlanes`; 6 tests, 3 disable runs red (not-read->read, no 65th-code cap, no code dedupe). Next: DT64 `LaneSource` binding over the planes. DR512 reserved for users per OU per group (operator) | | 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-LICENSE-DT64-1 | Licence-state planes (#2105) through the DT64 lane + selection sockets (#2106): codes bound by predicate IRI, StatePlane as a membership mask, evidence and coverage kept with the planes | In PR: Gate 0 corrections to #2105 (content-ordered codes, owned evidence, nextLink coverage); `dt64::LicenseLanes`; 512-user projection oracle-equal, warm read 0 allocs; depends on #2105 + #2106 | | 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 070731b4d..88915d33f 100644 --- a/.github/workflows/identity.yml +++ b/.github/workflows/identity.yml @@ -93,7 +93,7 @@ jobs: - 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 + run: cargo test --manifest-path crates/lance-graph-dir-sim/Cargo.toml --features dt64 --test dt64_lanes --test license_dt64 - 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/src/dt64.rs b/crates/lance-graph-dir-sim/src/dt64.rs index 88855f75a..1d59092d1 100644 --- a/crates/lance-graph-dir-sim/src/dt64.rs +++ b/crates/lance-graph-dir-sim/src/dt64.rs @@ -30,12 +30,29 @@ //! //! `Scope` is a consistency check between reader, lanes and selections, as //! everywhere in DT64; it is not authorization. +//! +//! **Licence-state codes through the same socket** (D-DIRSIM-LICENSE-DT64-1). +//! [`LicenseLanes`] serves a version's [`LicensePlanes`] in the row order of +//! that version's [`DirLanes`]: one lane per licence-state code (at most 64), +//! over the version's user ordinals (any number of DR tiles). The code axis +//! and the user axis are two axes; nothing builds a user × code × group +//! table. A lane is a membership plane ([`StatePlane`]), not a value lane: +//! read a row with [`StatePlane::contains`], or hand its words to a mask-RISC +//! program as a mask. A field resolves to a code by the code's identity (its +//! `predicate_iri`), never by position, so a code that moved is a refused +//! binding, not a re-pointed one. The assignment paths behind a bit stay with +//! the planes' owner ([`LicensePlanes::explain`]); the borrowed plane carries +//! none. 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 lance_graph_contract::class_view::{ClassId, ClassView}; +use lance_graph_contract::ontology::DisplayTemplate; + +use crate::license::{Coverage, LicensePlanes}; use crate::{Kept, UserOrdinal, View}; /// Field 0 of the user lanes: the UPN value. @@ -75,6 +92,27 @@ pub enum SelectRefusal { }, /// More selections than a `u16` id addresses. Full, + /// No licence-state code at that index. + NoSuchCode(usize), +} + +/// Hold `kept` as one more position list of `selections`. +fn hold( + selections: &mut Vec>, + kept: &Kept, + users: usize, +) -> Result { + if kept.universe() != users { + return Err(SelectRefusal::NotUsers { + rows: kept.universe(), + users, + }); + } + let sel = u16::try_from(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`. + selections.push(kept.rows().into_iter().map(|r| r as u32).collect()); + Ok(Selected { sel, axis }) } /// A selection the source holds. @@ -135,19 +173,17 @@ impl<'a, 's> DirLanes<'a, 's> { /// [`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 }) + hold(&mut self.selections, kept, self.view.users_len()) + } + + /// The version the lanes are over. + pub fn version(&self) -> VersionId { + self.version + } + + /// The version's user slots (deleted users included). + pub fn users_len(&self) -> usize { + self.view.users_len() } } @@ -214,3 +250,258 @@ impl SelectionSource for DirLanes<'_, '_> { .map(Vec::as_slice) } } + +// ---- Licence-state codes (D-DIRSIM-LICENSE-DT64-1) --------------------------- + +/// The schema revision the licence-state lanes serve. +pub const LICENSE_REV: SchemaRev = SchemaRev(1); + +/// The field basis of a licence-state class: one field per code of a +/// [`LicensePlanes`], in its code order, each named by the code's identity. +/// +/// A store binds the class over this basis once and never re-binds it +/// (D5): when a later observation changes the codes, its basis differs, and +/// a binding made over the old one is refused rather than re-pointed. +pub struct LicenseBasis { + class: ClassId, + fields: Vec, +} + +impl LicenseBasis { + /// The basis of `planes`' codes for the view class of `class`. Built once + /// per binding, cold. + pub fn of(planes: &LicensePlanes, class: u32) -> Self { + let fields = (0..planes.states().len()) + .filter_map(|c| planes.predicate_iri(c)) + .map(|iri| FieldRef::new(iri, iri)) + .collect(); + Self { + class: lance_graph_dt64::view_class(class), + fields, + } + } + + /// Fields in the basis: the number of codes. + pub fn len(&self) -> usize { + self.fields.len() + } + + /// Whether the basis has no field. + pub fn is_empty(&self) -> bool { + self.fields.is_empty() + } +} + +impl ClassView for LicenseBasis { + fn fields(&self, class: ClassId) -> &[FieldRef] { + if class == self.class { + &self.fields + } else { + &[] + } + } + fn template(&self, _class: ClassId) -> DisplayTemplate { + DisplayTemplate::Detail + } + fn dolce_category_id(&self, _class: ClassId) -> u8 { + 0 + } +} + +/// One licence-state code's plane over a version's user ordinals, borrowed +/// from the planes' owner. A membership mask, one bit per user: never index +/// it as a value lane. +#[derive(Clone, Copy, Debug)] +pub struct StatePlane<'a> { + words: &'a [u64], + n_rows: usize, +} + +impl<'a> StatePlane<'a> { + /// Whether user `row` holds the code (and its licences were read). A row + /// past the version's users holds nothing. + pub fn contains(&self, row: u32) -> bool { + let r = row as usize; + r < self.n_rows && (self.words[r / 64] >> (r % 64)) & 1 == 1 + } + + /// The plane's words, for a mask-RISC program's masks. + pub fn words(&self) -> &'a [u64] { + self.words + } + + /// Rows the plane covers: the version's user slots. + pub fn n_rows(&self) -> usize { + self.n_rows + } +} + +/// Why licence planes were not served. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LicenseSourceRefusal { + /// The planes are over another version than the directory lanes. + OtherVersion { + /// The planes' version. + planes: VersionId, + /// The directory lanes' version. + lanes: VersionId, + }, + /// The planes cover another number of user slots. + OtherPopulation { + /// The planes' user slots. + planes: usize, + /// The directory lanes' user slots. + users: usize, + }, + /// The licence pages are not one whole collection, so the planes cannot + /// stand for the version's licences. + Incomplete(Coverage), +} + +/// A version's licence planes as a DT64 lane and selection source, in the +/// row order of that version's [`DirLanes`]. +pub struct LicenseLanes<'p> { + planes: &'p LicensePlanes, + class: u32, + space: CoordSpace, + scope: Scope, + frames: FrameStore, + selections: Vec>, +} + +impl<'p> LicenseLanes<'p> { + /// Serve `planes` as class `class` for reader `scope`, in `dir`'s row + /// order. + /// + /// # Errors + /// + /// [`LicenseSourceRefusal`]: the planes are over another version or + /// population than `dir`, or their pages are not one whole collection. + pub fn over( + dir: &DirLanes<'_, '_>, + planes: &'p LicensePlanes, + class: u32, + scope: Scope, + ) -> Result { + if planes.version() != dir.version() { + return Err(LicenseSourceRefusal::OtherVersion { + planes: planes.version(), + lanes: dir.version(), + }); + } + if planes.users_len() != dir.users_len() { + return Err(LicenseSourceRefusal::OtherPopulation { + planes: planes.users_len(), + users: dir.users_len(), + }); + } + match planes.coverage() { + Coverage::Complete => {} + other => return Err(LicenseSourceRefusal::Incomplete(other)), + } + let version = planes.version().0; + Ok(Self { + planes, + class, + space: dir.space(), + scope, + frames: FrameStore::new(FrameRevisions { + source: version, + relation_map: 0, + coordinates: version, + }), + selections: Vec::new(), + }) + } + + /// The row order: the directory lanes' user ordinals. + pub fn space(&self) -> CoordSpace { + self.space + } + + /// Hold the users with licence-state code `code` as a selection. + /// + /// # Errors + /// + /// [`SelectRefusal::NoSuchCode`], or the source is full. + pub fn select_state(&mut self, code: usize) -> Result { + let kept = self + .planes + .with_state(code) + .ok_or(SelectRefusal::NoSuchCode(code))?; + hold(&mut self.selections, &kept, self.planes.users_len()) + } + + /// Hold `kept` (a result over this version's users) as a selection. + /// + /// # Errors + /// + /// [`SelectRefusal`] as for [`DirLanes::select`]. + pub fn select(&mut self, kept: &Kept) -> Result { + hold(&mut self.selections, kept, self.planes.users_len()) + } +} + +impl LaneSource for LicenseLanes<'_> { + type Lane<'b> + = StatePlane<'b> + where + Self: 'b; + + /// The code whose identity is `basis.predicate_iri`. The field position + /// is not read: two bases can order their fields differently. + fn lane_of( + &self, + class: u32, + rev: SchemaRev, + _field: u8, + basis: &FieldRef, + _frame: &Frame, + ) -> Option { + if class != self.class || rev != LICENSE_REV { + return None; + } + let code = self.planes.code_of(basis.predicate_iri.as_str())?; + Some(LaneAddr { + space: self.space, + lane: u16::try_from(code).ok()?, + scope: self.scope, + }) + } + + fn borrow(&self, addr: &LaneAddr) -> Option> { + if addr.space != self.space { + return None; + } + Some(StatePlane { + words: self.planes.plane(usize::from(addr.lane))?, + n_rows: self.planes.users_len(), + }) + } + + fn frames(&self) -> &FrameStore { + &self.frames + } +} + +impl SelectionSource for LicenseLanes<'_> { + /// Only under this source's current frame. + fn selection_of(&self, sel: u16, frame: &Frame) -> Option { + self.frames.check(frame).ok()?; + 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 822518c4d..b7fa8f77e 100644 --- a/crates/lance-graph-dir-sim/src/exec.rs +++ b/crates/lance-graph-dir-sim/src/exec.rs @@ -73,6 +73,28 @@ impl Kept { self.n_rows } + /// The rows both results kept, as one bitmap AND; `None` when the two + /// were computed over relations of different sizes. + /// + /// A `Kept` carries its relation's size, not its identity: the caller + /// vouches that both results are over the same version's rows (as + /// [`crate::dt64::DirLanes::select`] does). The DT64 sockets then check + /// the coordinate space when the result is read. + pub fn and(&self, other: &Kept) -> Option { + if self.n_rows != other.n_rows { + return None; + } + Some(Kept { + bits: self + .bits + .iter() + .zip(&other.bits) + .map(|(a, b)| a & b) + .collect(), + n_rows: 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/license.rs b/crates/lance-graph-dir-sim/src/license.rs index 7ef2183cd..5476f256e 100644 --- a/crates/lance-graph-dir-sim/src/license.rs +++ b/crates/lance-graph-dir-sim/src/license.rs @@ -23,12 +23,32 @@ //! //! The assigning group's identity is not part of a code (that would multiply //! codes by groups); several group paths to one SKU in one state set one bit. +//! +//! Corrections for the DT64 binding (D-DIRSIM-LICENSE-DT64-1, Gate 0): +//! +//! * **A code's index is its content, not its arrival.** Codes are ordered by +//! `(sku, via, state)`, so reordering Graph pages or users gives the same +//! code at the same index. Each code also has a stable identity, +//! [`LicensePlanes::predicate_iri`], which a DT64 binding resolves through; +//! a later observation that adds a code moves indices, and a binding made +//! before is refused, not re-pointed. +//! * **The plane is an accelerator, not the evidence.** The decoded pages +//! are owned here, beside the planes. [`LicensePlanes::paths`] returns a +//! user's typed assignment paths (with `assignedByGroup`), and +//! [`LicensePlanes::effective`] the separately collected `assignedLicenses` +//! SKUs; the two are never equated. +//! * **A partial collection says so.** [`LicensePlanes::coverage`] reads the +//! pages' `@odata.nextLink`s: a link nobody followed is +//! [`Coverage::Partial`], never complete coverage. use lance_graph_mask_risc::{words_for, Foreign, Planes}; use lance_graph_quack::{Agg, Filter, Mask}; use ogar_az::license::{LicensesPage, PathState, SkuCapacity, SkuPage}; use ogar_dir_core::Guid128; +use ogar_az::license::{EffectiveSku, LicensePath}; +use ogar_dir_sim::VersionId; + use crate::exec::{self, Kept}; use crate::{UserOrdinal, View}; @@ -45,6 +65,9 @@ pub enum Via { } /// One licence-state code: a SKU, how it is assigned, and its reported state. +/// +/// Ordered by `(sku, via, state)`, with states as `Active < Disabled < Error +/// < Other(text)`: that order is the code index. #[derive(Clone, Debug, PartialEq, Eq)] pub struct LicenseState { /// The SKU. @@ -55,6 +78,102 @@ pub struct LicenseState { pub state: PathState, } +impl LicenseState { + fn key(&self) -> ([u8; 16], u8, u8, &str) { + let (rank, text) = match &self.state { + PathState::Active => (0, ""), + PathState::Disabled => (1, ""), + PathState::Error => (2, ""), + PathState::Other(t) => (3, t.as_str()), + }; + let via = match self.via { + Via::Direct => 0, + Via::Group => 1, + }; + (self.sku.0, via, rank, text) + } + + /// The code's stable identity, the predicate a DT64 field binds. The + /// state is the Graph text as read (`Other` can never hold `Active`, + /// `Disabled` or `Error`, so the text is unique) and comes last, so a + /// colon inside it cannot be confused with a separator. + fn iri(&self) -> String { + let via = match self.via { + Via::Direct => "direct", + Via::Group => "group", + }; + let state = match &self.state { + PathState::Active => "Active", + PathState::Disabled => "Disabled", + PathState::Error => "Error", + PathState::Other(t) => t.as_str(), + }; + format!( + "urn:graph:licenseAssignmentState:{}:{via}:{state}", + self.sku + ) + } + + fn matches(&self, p: &LicensePath) -> bool { + p.sku == self.sku + && p.state == self.state + && (p.assigned_by_group.is_some() == (self.via == Via::Group)) + } +} + +/// Whether the licence pages are one whole collection. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Coverage { + /// No page was given. + NotCollected, + /// Exactly one page ends the collection and every other page links on. + Complete, + /// No page ends the collection: a `@odata.nextLink` was not followed. + Partial, + /// More than one page ends a collection: the pages are not one run. + Ambiguous, +} + +impl Coverage { + fn of<'a>(links: impl Iterator>) -> Coverage { + let (mut pages, mut ends) = (0usize, 0usize); + for l in links { + pages += 1; + if l.is_none() { + ends += 1; + } + } + match (pages, ends) { + (0, _) => Coverage::NotCollected, + (_, 1) => Coverage::Complete, + (_, 0) => Coverage::Partial, + _ => Coverage::Ambiguous, + } + } +} + +/// What the source holds for one user's licence property. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Evidence<'a, T> { + /// The user is on no licence page. + NotListed, + /// The user is listed and the property was absent or `null`. + NotRead, + /// The property as read; an empty slice is "read, none". + Read(&'a [T]), +} + +/// Why a code was not explained for a user. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ExplainRefusal { + /// No code at that index. + NoSuchCode(usize), + /// The user is on no licence page. + NotListed, + /// The user's assignment paths were not read. + NotRead, +} + /// Why licence planes were not built. #[derive(Clone, Debug, PartialEq, Eq)] pub enum LicenseError { @@ -76,6 +195,8 @@ pub enum LicenseError { /// A tenant's licences over one version's users. #[derive(Clone, Debug, PartialEq, Eq)] pub struct LicensePlanes { + /// The version whose users the planes are over. + version: VersionId, n_users: usize, /// The users that exist in this version; a deleted user keeps its slot /// but is not here. @@ -83,11 +204,19 @@ pub struct LicensePlanes { read: Vec, states: Vec, planes: Vec>, + /// Parallel to `states`: each code's stable identity. + iris: Vec>, capacity: Vec, + /// The decoded pages, owned: the evidence the planes summarise. + pages: Vec, + sku_pages: Vec, + /// Per user ordinal: `(page, entry)` of its listing, if listed. + listed: Vec>, } impl LicensePlanes { - /// Build the planes from decoded licence and capacity pages. + /// Build the planes from decoded licence and capacity pages over the users + /// of `v`, which is version `version`. The pages are kept as the evidence. /// /// # Errors /// @@ -95,8 +224,9 @@ impl LicensePlanes { /// user listed twice, or a SKU listed twice in the capacity pages. pub fn build( v: &View<'_>, - licenses: &[LicensesPage], - skus: &[SkuPage], + version: VersionId, + licenses: Vec, + skus: Vec, ) -> Result { let n_users = v.users_len(); let words = words_for(n_users); @@ -112,7 +242,12 @@ impl LicensePlanes { } let mut states: Vec = Vec::new(); let mut planes: Vec> = Vec::new(); - for u in licenses.iter().flat_map(|p| &p.users) { + let mut listed: Vec> = vec![None; n_users]; + let entries = licenses + .iter() + .enumerate() + .flat_map(|(pi, p)| p.users.iter().enumerate().map(move |(ui, u)| (pi, ui, u))); + for (pi, ui, u) in entries { let o = v .user_ordinal(&u.user) .ok_or(LicenseError::UnknownUser(u.user))?; @@ -121,6 +256,10 @@ impl LicensePlanes { return Err(LicenseError::DuplicateUser(u.user)); } seen[row / 64] |= 1 << (row % 64); + listed[row] = Some(( + u32::try_from(pi).expect("pages fit u32"), + u32::try_from(ui).expect("entries fit u32"), + )); let Some(paths) = &u.paths else { continue; }; @@ -159,21 +298,142 @@ impl LicensePlanes { } capacity.push(s.clone()); } + // The code index is the code's content: sort the (at most 64) codes + // and move each plane with its code. + let mut order: Vec = (0..states.len()).collect(); + order.sort_by(|&a, &b| states[a].key().cmp(&states[b].key())); + let mut taken: Vec)>> = + states.into_iter().zip(planes).map(Some).collect(); + let (states, planes): (Vec, Vec>) = order + .iter() + .map(|&i| taken[i].take().expect("each index once")) + .unzip(); + let iris = states.iter().map(|s| s.iri().into_boxed_str()).collect(); Ok(Self { + version, n_users, live, read, states, planes, + iris, capacity, + pages: licenses, + sku_pages: skus, + listed, }) } - /// The licence-state codes, in first-seen order; the index is the plane. + /// The licence-state codes in `(sku, via, state)` order; the index is + /// the plane. Reordering pages or users does not move a code. pub fn states(&self) -> &[LicenseState] { &self.states } + /// The version whose users the planes are over. + pub fn version(&self) -> VersionId { + self.version + } + + /// Users of the version (slots, deleted ones included). + pub fn users_len(&self) -> usize { + self.n_users + } + + /// The stable identity of code `code`: the predicate a DT64 field binds. + pub fn predicate_iri(&self, code: usize) -> Option<&str> { + self.iris.get(code).map(|s| &**s) + } + + /// The code whose identity is `iri`. At most 64 string compares; no + /// allocation. + pub fn code_of(&self, iri: &str) -> Option { + self.iris.iter().position(|s| &**s == iri) + } + + /// Code `code`'s plane over the user ordinals, if it exists: one bit per + /// read user holding the code. + pub fn plane(&self, code: usize) -> Option<&[u64]> { + self.planes.get(code).map(Vec::as_slice) + } + + /// Whether the licence pages are one whole collection. + pub fn coverage(&self) -> Coverage { + Coverage::of(self.pages.iter().map(|p| &p.next_link)) + } + + /// Whether the capacity pages are one whole collection. + pub fn capacity_coverage(&self) -> Coverage { + Coverage::of(self.sku_pages.iter().map(|p| &p.next_link)) + } + + fn listing(&self, o: UserOrdinal) -> Option<&ogar_az::license::UserLicenses> { + let (pi, ui) = (*self.listed.get(usize::from(o.0))?)?; + self.pages + .get(pi as usize) + .and_then(|p| p.users.get(ui as usize)) + } + + /// The user's `licenseAssignmentStates` as decoded: every path with its + /// assigning group. This is the evidence; the planes only summarise it. + pub fn paths(&self, o: UserOrdinal) -> Evidence<'_, LicensePath> { + match self.listing(o) { + None => Evidence::NotListed, + Some(u) => match &u.paths { + None => Evidence::NotRead, + Some(p) => Evidence::Read(p), + }, + } + } + + /// The user's `assignedLicenses` (effective SKUs) as decoded. A separate + /// property with its own collection state: it is never derived from, or + /// substituted for, the assignment paths. + pub fn effective(&self, o: UserOrdinal) -> Evidence<'_, EffectiveSku> { + match self.listing(o) { + None => Evidence::NotListed, + Some(u) => match &u.effective { + None => Evidence::NotRead, + Some(e) => Evidence::Read(e), + }, + } + } + + /// The assignment paths behind code `code` for user `o`: for a group + /// code, one per assigning group. Borrowed from the evidence. + /// + /// # Errors + /// + /// [`ExplainRefusal`]: no such code, or the user's paths are not held. + pub fn explain( + &self, + o: UserOrdinal, + code: usize, + ) -> Result, ExplainRefusal> { + let state = self + .states + .get(code) + .ok_or(ExplainRefusal::NoSuchCode(code))?; + match self.paths(o) { + Evidence::NotListed => Err(ExplainRefusal::NotListed), + Evidence::NotRead => Err(ExplainRefusal::NotRead), + Evidence::Read(p) => Ok(p.iter().filter(move |x| state.matches(x))), + } + } + + /// How many assignment paths to `sku` the read users of this version + /// have. Counted over the evidence; a holder with two paths counts two + /// here and once in [`Self::holder_count`]. Two paths are not two seats. + pub fn path_count(&self, sku: &Guid128) -> usize { + (0..self.n_users) + .filter(|&row| self.live[row / 64] & (1 << (row % 64)) != 0) + .filter_map(|row| match self.paths(UserOrdinal(row as u16)) { + Evidence::Read(p) => Some(p.iter().filter(|x| x.sku == *sku).count()), + _ => None, + }) + .sum() + } + /// The decoded capacity of `sku`, if its capacity was read. pub fn capacity(&self, sku: &Guid128) -> Option<&SkuCapacity> { self.capacity.iter().find(|c| c.sku == *sku) diff --git a/crates/lance-graph-dir-sim/tests/license_dt64.rs b/crates/lance-graph-dir-sim/tests/license_dt64.rs new file mode 100644 index 000000000..a3576edb6 --- /dev/null +++ b/crates/lance-graph-dir-sim/tests/license_dt64.rs @@ -0,0 +1,839 @@ +//! D-DIRSIM-LICENSE-DT64-1: a version's licence planes through the DT64 lane +//! and selection sockets, read in the row order of the version's directory +//! lanes. Every answer is compared with an independent scalar oracle built +//! from the fixture's own rule, never from the planes. +#![cfg(feature = "dt64")] + +use std::alloc::{GlobalAlloc, Layout, System}; +use std::cell::Cell; +use std::time::Instant; + +use lance_graph_contract::class_view::{ClassId, ClassView, WideFieldMask}; +use lance_graph_contract::ontology::{DisplayTemplate, FieldRef}; +use lance_graph_dir_sim::dt64::{ + DirLanes, LicenseBasis, LicenseLanes, LicenseSourceRefusal, SelectRefusal, F_UPN, LANE_REV, + LICENSE_REV, +}; +use lance_graph_dir_sim::license::{ + Coverage, ExplainRefusal, LicenseError, LicensePlanes, Via, MAX_LICENSE_STATES, +}; +use lance_graph_dir_sim::{ + subtree, NodeKind, Observation, ObservedNode, UserOrdinal, VersionStore, +}; +use lance_graph_dt64::dr::{FrameRefusal, Scope}; +use lance_graph_dt64::{ + BindStore, ClassSchema, CoordSpace, Extent, LaneBinding, LaneRefusal, LaneRequest, LaneSource, + RouteAt, +}; +use ogar_az::license::{ingest_licenses_page, LicensesPage, PathState}; +use ogar_dir_core::{DirectoryScope, Dn128, Guid128}; + +// ---- counting allocator: allocations and bytes ------------------------------ + +struct Counting; +thread_local! { + static ALLOCS: Cell = const { Cell::new(0) }; + static BYTES: 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)); + let _ = BYTES.try_with(|b| b.set(b.get() + l.size() as u64)); + // 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, u64) { + (ALLOCS.with(Cell::get), BYTES.with(Cell::get)) +} + +// ---- fixture ---------------------------------------------------------------- + +const TENANT: DirectoryScope = DirectoryScope(Guid128([0x5C; 16])); +const USER: u32 = 0x0D1B_0001; +const LICENSE: u32 = 0x0D1C_0001; +const USER_POS: u16 = 3; +const LICENSE_POS: u16 = 4; +const READER: Scope = Scope { id: 7 }; +const USERS: usize = 512; +const INSIDE: usize = 5; +const SKUS: usize = 8; +const GROUPS: usize = 5; +const STATES: [&str; 4] = ["Active", "Disabled", "Error", "PendingInput"]; + +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) +} +fn sku(i: usize) -> String { + format!("00000000-0000-4000-8000-{:012x}", 0x5100 + i) +} +fn group(i: usize) -> String { + format!("00000000-0000-4000-8000-{:012x}", 0x6100 + i) +} + +/// The fixture's rule, written once, read by both the pages and the oracle. +/// `None`: the property is absent. Each path is `(sku, group, state)`. +fn rule(u: usize) -> Option, usize)>> { + if u % 11 == 5 { + return None; + } + if u % 13 == 6 { + return Some(Vec::new()); + } + let (s, st) = (u % SKUS, (u / SKUS) % STATES.len()); + let mut p = Vec::new(); + if u.is_multiple_of(3) { + p.push((s, None, st)); + } + p.push((s, Some(u % GROUPS), st)); + if u.is_multiple_of(7) { + // A second assigning group for the same SKU in the same state. + p.push((s, Some((u + 1) % GROUPS), st)); + } + Some(p) +} + +fn entry(u: usize) -> String { + match rule(u) { + None => format!(r#"{{"id":"{}"}}"#, user(u)), + Some(paths) => { + let items: Vec = paths + .iter() + .map(|&(s, g, st)| match g { + Some(g) => format!( + r#"{{"skuId":"{}","state":"{}","assignedByGroup":"{}"}}"#, + sku(s), + STATES[st], + group(g) + ), + None => format!(r#"{{"skuId":"{}","state":"{}"}}"#, sku(s), STATES[st]), + }) + .collect(); + format!( + r#"{{"id":"{}","licenseAssignmentStates":[{}]}}"#, + user(u), + items.join(",") + ) + } + } +} + +/// The users in four pages of 128, linked except the last, in `order`. +fn pages(order: [usize; 4], reverse_users: bool) -> Vec { + order + .iter() + .map(|&p| { + let mut us: Vec = (p * 128..(p + 1) * 128).collect(); + if reverse_users { + us.reverse(); + } + let body: Vec = us.into_iter().map(entry).collect(); + let mut page = + ingest_licenses_page(&format!(r#"{{"value":[{}]}}"#, body.join(","))).unwrap(); + page.next_link = (p < 3).then(|| format!("https://graph.example/users?page={}", p + 1)); + page + }) + .collect() +} + +fn inside_ou() -> Dn128 { + Dn128::new(&[1]).unwrap() +} + +fn observation() -> Observation { + let mut o = Observation { + scope: TENANT, + nodes: Vec::new(), + members: Vec::new(), + }; + for u in 0..USERS { + 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 +} + +struct UserBasis(Vec); +impl ClassView for UserBasis { + fn fields(&self, class: ClassId) -> &[FieldRef] { + if class == lance_graph_dt64::view_class(USER) { + &self.0 + } else { + &[] + } + } + fn template(&self, _class: ClassId) -> DisplayTemplate { + DisplayTemplate::Detail + } + fn dolce_category_id(&self, _class: ClassId) -> u8 { + 0 + } +} +fn user_basis() -> UserBasis { + UserBasis(vec![ + FieldRef::new("dir:userPrincipalName", "UPN"), + FieldRef::new("dir:primarySmtp", "Primary SMTP"), + ]) +} + +/// The store, binding the users class and the licence class over `basis`. +fn store(basis: &LicenseBasis) -> (BindStore, RouteAt, RouteAt) { + let mut bs = BindStore::new(); + bs.register( + &user_basis(), + USER, + ClassSchema { + schema_rev: LANE_REV, + field_count: 2, + extent: Extent::DR64_CUBE, + }, + Vec::new(), + ) + .unwrap(); + bs.register( + basis, + LICENSE, + ClassSchema { + schema_rev: LICENSE_REV, + field_count: basis.len(), + extent: Extent::DR64_CUBE, + }, + Vec::new(), + ) + .unwrap(); + let uv = bs.route(USER_POS, USER).unwrap(); + let lv = bs.route(LICENSE_POS, LICENSE).unwrap(); + ( + bs, + RouteAt { + position: USER_POS, + version: uv, + }, + RouteAt { + position: LICENSE_POS, + version: lv, + }, + ) +} + +fn bind_codes( + bs: &BindStore, + basis: &LicenseBasis, + lic: &LicenseLanes<'_>, + route: RouteAt, + fields: &[u8], + scope: Scope, + selection: CoordSpace, +) -> Result { + let frame = lic.frames().seal(); + bs.bind_lanes( + basis, + lic.frames(), + lic, + LaneRequest { + route, + rev: LICENSE_REV, + fields: &WideFieldMask::from_positions(fields), + frame: &frame, + scope, + selection, + }, + ) +} + +/// The oracle: does user `u` hold the code `(sku, via, state)`? +fn oracle_holds(u: usize, s: usize, group_path: bool, st: usize) -> bool { + rule(u).is_some_and(|p| { + p.iter() + .any(|&(ps, pg, pst)| ps == s && pg.is_some() == group_path && pst == st) + }) +} + +/// The code index of `(sku, via, state)` in `planes`, found by content. +fn code(planes: &LicensePlanes, s: usize, group_path: bool, st: usize) -> usize { + let want = Guid128::parse(&sku(s)).unwrap(); + let state = match STATES[st] { + "Active" => PathState::Active, + "Disabled" => PathState::Disabled, + "Error" => PathState::Error, + other => PathState::Other(other.into()), + }; + let via = if group_path { Via::Group } else { Via::Direct }; + planes + .states() + .iter() + .position(|c| c.sku == want && c.via == via && c.state == state) + .unwrap() +} + +/// The version's row (user ordinal) of fixture user `u`. Ordinals follow the +/// directory's own order, not the fixture's numbering. +fn row(view: &lance_graph_dir_sim::View<'_>, u: usize) -> u32 { + u32::from(view.user_ordinal(&user(u)).unwrap().0) +} + +/// The oracle's users, as sorted rows of `view`. +fn rows_of(view: &lance_graph_dir_sim::View<'_>, users: impl Iterator) -> Vec { + let mut r: Vec = users.map(|u| row(view, u)).collect(); + r.sort_unstable(); + r +} + +// ---- Gate 2: native selection ----------------------------------------------- + +/// Select by licence state, intersect with a directory selection, resolve a +/// selected user's codes under the source frame, and keep holders apart from +/// paths. Every answer against the scalar oracle. +#[test] +fn licence_states_select_intersect_and_resolve_against_the_oracle() { + let mut st = VersionStore::new(); + let v = st.observe("ad", 0, observation()).unwrap(); + let view = st.view(v).unwrap(); + let planes = LicensePlanes::build(&view, v, pages([0, 1, 2, 3], false), Vec::new()).unwrap(); + assert_eq!( + planes.states().len(), + MAX_LICENSE_STATES, + "one full DR64 tile" + ); + assert_eq!(planes.coverage(), Coverage::Complete); + + let mut dir = DirLanes::new(&view, v, USER, READER); + let mut lic = LicenseLanes::over(&dir, &planes, LICENSE, READER).unwrap(); + let basis = LicenseBasis::of(&planes, LICENSE); + let (bs, user_route, lic_route) = store(&basis); + + // 1. Users with (sku 3, group, Disabled): select, bind, read. + let c = code(&planes, 3, true, 1); + let field = c as u8; + let picked = lic.select_state(c).unwrap(); + let b = bind_codes(&bs, &basis, &lic, lic_route, &[field], READER, dir.space()).unwrap(); + let (plane, rows) = b + .selected(&bs, &basis, lic.frames(), &lic, field, picked.sel) + .unwrap(); + let want = rows_of(&view, (0..USERS).filter(|&u| oracle_holds(u, 3, true, 1))); + assert_eq!(rows, want.as_slice()); + assert!(!want.is_empty() && want.len() * 3 < USERS, "a real filter"); + assert!(rows.iter().all(|&r| plane.contains(r))); + + // 2. The directory's five users ∩ users holding (sku 0, group, Active). + let ou = subtree(&view, TENANT, NodeKind::User, &inside_ou()).unwrap(); + assert_eq!(ou.len(), INSIDE); + let c0 = code(&planes, 0, true, 0); + let both = planes.with_state(c0).unwrap().and(&ou).unwrap(); + let in_dir = dir.select(&both).unwrap(); + let in_lic = lic.select(&both).unwrap(); + let want_both = rows_of(&view, (0..INSIDE).filter(|&u| oracle_holds(u, 0, true, 0))); + assert!( + !want_both.is_empty() && want_both.len() < INSIDE, + "a real intersection" + ); + let ub = bs + .bind_lanes( + &user_basis(), + dir.frames(), + &dir, + LaneRequest { + route: user_route, + rev: LANE_REV, + fields: &WideFieldMask::from_positions(&[F_UPN]), + frame: &dir.frames().seal(), + scope: READER, + selection: dir.space(), + }, + ) + .unwrap(); + let (upn, dir_rows) = ub + .selected(&bs, &user_basis(), dir.frames(), &dir, F_UPN, in_dir.sel) + .unwrap(); + assert_eq!(dir_rows, want_both.as_slice()); + for &r in dir_rows { + let g = view.user_guid(UserOrdinal(r as u16)).unwrap(); + assert_eq!( + upn.get(r), + view.attr(&g, ogar_dir_sim::Attribute::Upn).map(|x| x.0) + ); + } + let b0 = bind_codes( + &bs, + &basis, + &lic, + lic_route, + &[c0 as u8], + READER, + dir.space(), + ) + .unwrap(); + let (p0, lic_rows) = b0 + .selected(&bs, &basis, lic.frames(), &lic, c0 as u8, in_lic.sel) + .unwrap(); + assert_eq!(lic_rows, dir_rows, "one row order"); + assert!(lic_rows.iter().all(|&r| p0.contains(r))); + + // 3. One selected user's codes under the source frame, and the paths + // behind them from the evidence (u = 0: direct + two groups). + let all: Vec = (0..basis.len() as u8).collect(); + let ball = bind_codes(&bs, &basis, &lic, lic_route, &all, READER, dir.space()).unwrap(); + let u0 = row(&view, 0); + let mut held = 0; + for item in ball.borrow_all(&bs, &basis, lic.frames(), &lic).unwrap() { + let (f, plane) = item.unwrap(); + let c = &planes.states()[usize::from(f)]; + let s = (0..SKUS) + .find(|&i| Guid128::parse(&sku(i)).unwrap() == c.sku) + .unwrap(); + let st_i = STATES + .iter() + .position(|t| match &c.state { + PathState::Active => *t == "Active", + PathState::Disabled => *t == "Disabled", + PathState::Error => *t == "Error", + PathState::Other(x) => t == x, + }) + .unwrap(); + let want = oracle_holds(0, s, c.via == Via::Group, st_i); + assert_eq!(plane.contains(u0), want, "field {f}"); + held += usize::from(want); + } + assert_eq!(held, 2, "u0 holds the direct and the group code"); + let gc = code(&planes, 0, true, 0); + let groups: Vec = planes + .explain(UserOrdinal(u0 as u16), gc) + .unwrap() + .map(|p| p.assigned_by_group.unwrap()) + .collect(); + assert_eq!( + groups, + vec![ + Guid128::parse(&group(0)).unwrap(), + Guid128::parse(&group(1)).unwrap() + ], + "one bit, two assigning groups, both recovered" + ); + + // 4. Holders versus assignment paths for sku 0. + let sku0 = Guid128::parse(&sku(0)).unwrap(); + let want_holders = (0..USERS) + .filter(|&u| rule(u).is_some_and(|p| p.iter().any(|x| x.0 == 0))) + .count(); + let want_paths: usize = (0..USERS) + .filter_map(rule) + .map(|p| p.iter().filter(|x| x.0 == 0).count()) + .sum(); + assert_eq!(planes.holder_count(&sku0), want_holders); + assert_eq!(planes.path_count(&sku0), want_paths); + assert!( + want_paths > want_holders, + "the fixture has multi-path holders" + ); +} + +/// A 65th distinct code is refused; 64 fit (the fixture above). +#[test] +fn the_65th_licence_state_code_is_refused() { + let mut st = VersionStore::new(); + let v = st.observe("ad", 0, observation()).unwrap(); + let view = st.view(v).unwrap(); + let mut ps = pages([0, 1, 2, 3], false); + let extra = ingest_licenses_page(&format!( + r#"{{"value":[{{"id":"{}","licenseAssignmentStates":[{{"skuId":"{}","state":"Suspended"}}]}}]}}"#, + user(5), + sku(0) + )) + .unwrap(); + // u5's property was absent in the pages; list it in a page of its own. + ps.last_mut().unwrap().next_link = Some("https://graph.example/users?page=4".into()); + let mut ps2: Vec = ps + .into_iter() + .map(|mut p| { + p.users.retain(|x| x.user != user(5)); + p + }) + .collect(); + ps2.push(extra); + assert_eq!( + LicensePlanes::build(&view, v, ps2, Vec::new()), + Err(LicenseError::TooManyStates { + found: 65, + limit: 64 + }) + ); +} + +// ---- Gate 4: typed refusals ------------------------------------------------- + +#[test] +fn stale_foreign_and_mismatched_bindings_are_refused() { + let mut st = VersionStore::new(); + let v0 = st.observe("ad", 0, observation()).unwrap(); + // The later revision exists before any view borrows the store. + let v1 = st.reobserve("ad", 1, observation()).unwrap(); + let view0 = st.view(v0).unwrap(); + let planes0 = LicensePlanes::build(&view0, v0, pages([0, 1, 2, 3], false), Vec::new()).unwrap(); + let dir0 = DirLanes::new(&view0, v0, USER, READER); + let lic0 = LicenseLanes::over(&dir0, &planes0, LICENSE, READER).unwrap(); + let basis0 = LicenseBasis::of(&planes0, LICENSE); + let (bs, _, route) = store(&basis0); + let c = code(&planes0, 2, false, 2) as u8; + let b0 = bind_codes(&bs, &basis0, &lic0, route, &[c], READER, dir0.space()).unwrap(); + + // Reordered pages: the same code at the same index, a new source frame. + let planes_r = LicensePlanes::build(&view0, v0, pages([3, 1, 0, 2], true), Vec::new()).unwrap(); + assert_eq!(planes_r.states(), planes0.states()); + let lic_r = LicenseLanes::over(&dir0, &planes_r, LICENSE, READER).unwrap(); + assert_eq!( + b0.check(&bs, &basis0, lic_r.frames(), &lic_r).err(), + Some(LaneRefusal::Frame(FrameRefusal::ForeignFrame)), + "a binding is never read against another source's planes" + ); + let br = bind_codes(&bs, &basis0, &lic_r, route, &[c], READER, dir0.space()).unwrap(); + assert_eq!(br.addr(c).unwrap().lane, b0.addr(c).unwrap().lane); + + // A later observation revision: users 1..512 lose their direct paths + // except for sku 7, so codes vanish and indices move. + let view1 = st.view(v1).unwrap(); + let mut later = pages([0, 1, 2, 3], false); + for p in &mut later { + for u in &mut p.users { + if let Some(paths) = &mut u.paths { + paths.retain(|x| { + x.assigned_by_group.is_some() || x.sku == Guid128::parse(&sku(7)).unwrap() + }); + } + } + } + let planes1 = LicensePlanes::build(&view1, v1, later, Vec::new()).unwrap(); + assert!(planes1.states().len() < planes0.states().len()); + let dir1 = DirLanes::new(&view1, v1, USER, READER); + let lic1 = LicenseLanes::over(&dir1, &planes1, LICENSE, READER).unwrap(); + // Stale frame / source generation. + assert_eq!( + b0.check(&bs, &basis0, lic1.frames(), &lic1).err(), + Some(LaneRefusal::Frame(FrameRefusal::ForeignFrame)) + ); + // The old basis names a code the new planes do not have: unbound, never + // read at the slot that now holds another code. + let gone = code(&planes0, 2, false, 2) as u8; + assert_eq!( + bind_codes(&bs, &basis0, &lic1, route, &[gone], READER, dir1.space()).err(), + Some(LaneRefusal::Unbound { + class: LICENSE, + field: gone + }) + ); + assert_ne!( + planes1.predicate_iri(usize::from(gone)), + planes0.predicate_iri(usize::from(gone)), + "another code now sits at that index" + ); + // A code that survived resolves by identity to its NEW index. + let kept_code = code(&planes0, 7, false, 0) as u8; + let moved = bind_codes( + &bs, + &basis0, + &lic1, + route, + &[kept_code], + READER, + dir1.space(), + ) + .unwrap(); + assert_eq!( + usize::from(moved.addr(kept_code).unwrap().lane), + code(&planes1, 7, false, 0) + ); + assert_ne!( + usize::from(kept_code), + code(&planes1, 7, false, 0), + "it moved" + ); + // The new codebook cannot be checked against a store bound over the old. + let basis1 = LicenseBasis::of(&planes1, LICENSE); + assert!(matches!( + bind_codes(&bs, &basis1, &lic1, route, &[0], READER, dir1.space()), + Err(LaneRefusal::Bind(_)) + )); + + // Mismatched population: v0's planes under v1's directory lanes. + assert_eq!( + LicenseLanes::over(&dir1, &planes0, LICENSE, READER).err(), + Some(LicenseSourceRefusal::OtherVersion { + planes: v0, + lanes: v1 + }) + ); + // Foreign reader scope. + assert!(matches!( + bind_codes( + &bs, + &basis0, + &lic0, + route, + &[c], + Scope { id: 8 }, + dir0.space() + ), + Err(LaneRefusal::Scope { .. }) + )); + // Wrong user row order. + assert!(matches!( + bind_codes(&bs, &basis0, &lic0, route, &[c], READER, dir1.space()), + Err(LaneRefusal::CoordinateSpace { .. }) + )); + // A field outside the class basis. + assert!(matches!( + bind_codes(&bs, &basis0, &lic0, route, &[200], READER, dir0.space()), + Err(LaneRefusal::FieldNotInBasis { .. }) + )); + // An incomplete collection is not served. + let partial = LicensePlanes::build( + &view0, + v0, + pages([0, 1, 2, 2], false)[..3].to_vec(), + Vec::new(), + ) + .unwrap(); + assert_eq!(partial.coverage(), Coverage::Partial); + assert_eq!( + LicenseLanes::over(&dir0, &partial, LICENSE, READER).err(), + Some(LicenseSourceRefusal::Incomplete(Coverage::Partial)) + ); + // An exact path explanation for a user whose paths were not read. + assert_eq!( + planes0.explain(UserOrdinal(row(&view0, 5) as u16), 0).err(), + Some(ExplainRefusal::NotRead) + ); + // A selection of another source's row order is refused. + let mut lic0m = LicenseLanes::over(&dir0, &planes0, LICENSE, READER).unwrap(); + assert_eq!( + lic0m.select_state(64).err(), + Some(SelectRefusal::NoSuchCode(64)) + ); +} + +/// A licence property that is not collected as planes (`assignedLicenses`) +/// has no lane: a basis naming it is unbound, never read as empty. +#[test] +fn an_uncollected_licence_property_has_no_lane() { + struct Mixed(Vec); + impl ClassView for Mixed { + fn fields(&self, class: ClassId) -> &[FieldRef] { + if class == lance_graph_dt64::view_class(LICENSE) { + &self.0 + } else { + &[] + } + } + fn template(&self, _class: ClassId) -> DisplayTemplate { + DisplayTemplate::Detail + } + fn dolce_category_id(&self, _class: ClassId) -> u8 { + 0 + } + } + let mut st = VersionStore::new(); + let v = st.observe("ad", 0, observation()).unwrap(); + let view = st.view(v).unwrap(); + let planes = LicensePlanes::build(&view, v, pages([0, 1, 2, 3], false), Vec::new()).unwrap(); + let dir = DirLanes::new(&view, v, USER, READER); + let lic = LicenseLanes::over(&dir, &planes, LICENSE, READER).unwrap(); + let mixed = Mixed(vec![ + FieldRef::new(planes.predicate_iri(0).unwrap(), "code 0"), + FieldRef::new("urn:graph:assignedLicenses:skuId", "effective SKUs"), + ]); + let mut bs = BindStore::new(); + bs.register( + &mixed, + LICENSE, + ClassSchema { + schema_rev: LICENSE_REV, + field_count: 2, + extent: Extent::DR64_CUBE, + }, + Vec::new(), + ) + .unwrap(); + let version = bs.route(LICENSE_POS, LICENSE).unwrap(); + let route = RouteAt { + position: LICENSE_POS, + version, + }; + let req = |fields: &[u8]| { + let mask = WideFieldMask::from_positions(fields); + let frame = lic.frames().seal(); + bs.bind_lanes( + &mixed, + lic.frames(), + &lic, + LaneRequest { + route, + rev: LICENSE_REV, + fields: &mask, + frame: &frame, + scope: READER, + selection: dir.space(), + }, + ) + .map(|_| ()) + }; + assert_eq!(req(&[0]), Ok(()), "the code field binds"); + assert_eq!( + req(&[1]), + Err(LaneRefusal::Unbound { + class: LICENSE, + field: 1 + }) + ); +} + +// ---- Gate 3: no-explosion proof and measured projection ---------------------- + +fn median(mut xs: Vec) -> u128 { + xs.sort_unstable(); + xs[xs.len() / 2] +} + +/// The whole operation over 512 users, 64 codes, 5 groups and 5 selected +/// users: phase timings (reported, not gated), the bits examined, and the +/// allocations and bytes of each phase. The query phases allocate a few +/// hundred bytes; a user × code × group table would be 512 × 64 × 5 cells. +/// Falsifier: any per-user object or Cartesian table on the query path +/// moves the byte count past the bound. +#[test] +fn the_512_user_projection_builds_no_cartesian_table() { + const RUNS: usize = 21; + let mut st = VersionStore::new(); + let v = st.observe("ad", 0, observation()).unwrap(); + let view = st.view(v).unwrap(); + let source = pages([2, 0, 3, 1], true); + + let mut build_ns = Vec::new(); + let mut planes = None; + let (a, by) = allocs(); + for _ in 0..RUNS { + let input = source.clone(); + let t = Instant::now(); + planes = Some(LicensePlanes::build(&view, v, input, Vec::new()).unwrap()); + build_ns.push(t.elapsed().as_nanos()); + } + let planes = planes.unwrap(); + let (a2, by2) = allocs(); + let _ = (a2 - a, by2 - by); + + let mut dir = DirLanes::new(&view, v, USER, READER); + let ou = subtree(&view, TENANT, NodeKind::User, &inside_ou()).unwrap(); + let c = code(&planes, 0, true, 0); + + // Binding, cold: source, basis, store, one bind. + let (a0, b0) = allocs(); + let t = Instant::now(); + let mut lic = LicenseLanes::over(&dir, &planes, LICENSE, READER).unwrap(); + let basis = LicenseBasis::of(&planes, LICENSE); + let (bs, _, route) = store(&basis); + let binding = bind_codes(&bs, &basis, &lic, route, &[c as u8], READER, dir.space()).unwrap(); + let bind_ns = t.elapsed().as_nanos(); + let (a1, b1) = allocs(); + + // Selection positions: state ∩ directory, held by both sources. + let t = Instant::now(); + let both = planes.with_state(c).unwrap().and(&ou).unwrap(); + let in_lic = lic.select(&both).unwrap(); + let _in_dir = dir.select(&both).unwrap(); + let select_ns = t.elapsed().as_nanos(); + let (a2, b2) = allocs(); + + // Warm reads: check, borrow, read every selected user's bit. + let mut read_ns = Vec::with_capacity(RUNS); + let mut examined = 0usize; + let (a3, _) = allocs(); + for _ in 0..RUNS { + let t = Instant::now(); + let (plane, rows) = binding + .selected(&bs, &basis, lic.frames(), &lic, c as u8, in_lic.sel) + .unwrap(); + let mut held = 0usize; + for &r in rows { + held += usize::from(plane.contains(r)); + examined += 1; + } + read_ns.push(t.elapsed().as_nanos()); + assert_eq!(held, rows.len()); + } + let (a4, _) = allocs(); + + // Terminal materialization: the selected users' UPNs as owned strings. + let (a5, b5) = allocs(); + let t = Instant::now(); + let upns: Vec = both + .rows() + .into_iter() + .filter_map(|r| view.user_guid(UserOrdinal(r as u16))) + .filter_map(|g| view.attr(&g, ogar_dir_sim::Attribute::Upn)) + .filter_map(|id| view.dicts().value(id).map(str::to_string)) + .collect(); + let terminal_ns = t.elapsed().as_nanos(); + let (a6, b6) = allocs(); + + let want: Vec = (0..INSIDE) + .filter(|&u| oracle_holds(u, 0, true, 0)) + .map(|u| format!("u{u}@example.test")) + .collect(); + assert_eq!(upns, want, "the oracle"); + assert_eq!(a4 - a3, 0, "warm reads allocate nothing"); + + let plane_bytes = planes.states().len() * USERS.div_ceil(64) * 8; + let cartesian_bits = USERS * MAX_LICENSE_STATES * GROUPS; + let query_bytes = (b2 - b1) as usize; + eprintln!( + "D-DIRSIM-LICENSE-DT64-1 projection, {USERS} users, {} codes, {GROUPS} groups:", + planes.states().len() + ); + eprintln!( + " plane construction median {:>8} ns ({RUNS} runs)", + median(build_ns) + ); + eprintln!( + " binding (cold) {:>8} ns, {} allocs, {} B", + bind_ns, + a1 - a0, + b1 - b0 + ); + eprintln!( + " selection positions {:>8} ns, {} allocs, {} B", + select_ns, + a2 - a1, + query_bytes + ); + eprintln!( + " warm read median {:>8} ns, 0 allocs, {} bits examined in {RUNS} runs", + median(read_ns), + examined + ); + eprintln!( + " terminal (UPN strings) {:>8} ns, {} allocs, {} B", + terminal_ns, + a6 - a5, + b6 - b5 + ); + eprintln!( + " resident planes {plane_bytes} B; a user x code x group bit table would be {} B", + cartesian_bits / 8 + ); + // The query path holds two 8-word bitmaps and two position lists: far + // below even a bit-packed Cartesian table. + assert!( + query_bytes * 8 < cartesian_bits / 8, + "{query_bytes} B on the query path" + ); + assert_eq!(examined, RUNS * want.len()); +} diff --git a/crates/lance-graph-dir-sim/tests/license_planes.rs b/crates/lance-graph-dir-sim/tests/license_planes.rs index 3e5e89d8e..6eed8fdb1 100644 --- a/crates/lance-graph-dir-sim/tests/license_planes.rs +++ b/crates/lance-graph-dir-sim/tests/license_planes.rs @@ -1,7 +1,9 @@ //! Licences as DR64 planes over a version's users (`license::LicensePlanes`). -use lance_graph_dir_sim::license::{LicenseError, LicensePlanes, Via, MAX_LICENSE_STATES}; -use lance_graph_dir_sim::{Observation, ObservedNode, VersionStore}; +use lance_graph_dir_sim::license::{ + Coverage, Evidence, ExplainRefusal, LicenseError, LicensePlanes, Via, MAX_LICENSE_STATES, +}; +use lance_graph_dir_sim::{Observation, ObservedNode, UserOrdinal, VersionStore}; use ogar_az::license::{ingest_licenses_page, ingest_skus_page, LicensesPage, PathState}; use ogar_dir_core::{DirectoryScope, Guid128}; @@ -60,8 +62,9 @@ fn entry(u: u8, paths: Option<&[String]>) -> String { fn build(users: u8, entries: &[String]) -> Result { let st = store(users); - let v = st.view(st.tag("observed").unwrap()).unwrap(); - LicensePlanes::build(&v, &[page(entries)], &[]) + let ver = st.tag("observed").unwrap(); + let v = st.view(ver).unwrap(); + LicensePlanes::build(&v, ver, vec![page(entries)], Vec::new()) } /// Falsifier: a not-read user counted as read (or as holding nothing that was @@ -174,7 +177,8 @@ fn unknown_or_repeated_entries_are_refused() { Err(LicenseError::DuplicateUser(user(0))) ); let st = store(1); - let v = st.view(st.tag("observed").unwrap()).unwrap(); + let ver = st.tag("observed").unwrap(); + let v = st.view(ver).unwrap(); let skus = ingest_skus_page(&format!( r#"{{"value":[ {{"skuId":"{SKU}","consumedUnits":1,"prepaidUnits":{{"enabled":1,"suspended":0,"warning":0}}}}, @@ -182,7 +186,7 @@ fn unknown_or_repeated_entries_are_refused() { )) .unwrap(); assert_eq!( - LicensePlanes::build(&v, &[], &[skus]), + LicensePlanes::build(&v, ver, Vec::new(), vec![skus]), Err(LicenseError::DuplicateSku(g(SKU))) ); } @@ -190,12 +194,13 @@ fn unknown_or_repeated_entries_are_refused() { #[test] fn capacity_is_held_exact_beside_the_planes() { let st = store(1); - let v = st.view(st.tag("observed").unwrap()).unwrap(); + let ver = st.tag("observed").unwrap(); + let v = st.view(ver).unwrap(); let skus = ingest_skus_page(&format!( r#"{{"value":[{{"skuId":"{SKU}","consumedUnits":1200,"prepaidUnits":{{"enabled":1000,"suspended":0,"warning":0}}}}]}}"# )) .unwrap(); - let p = LicensePlanes::build(&v, &[], &[skus]).unwrap(); + let p = LicensePlanes::build(&v, ver, Vec::new(), vec![skus]).unwrap(); let c = p.capacity(&g(SKU)).unwrap(); assert_eq!((c.enabled, c.consumed, c.free()), (1000, 1200, -200)); assert!(p.capacity(&g(SKU2)).is_none()); @@ -227,7 +232,7 @@ fn a_deleted_user_is_not_unread() { let v = st.view(v1).unwrap(); assert_eq!(v.users_len(), 3, "the deleted user keeps its slot"); assert_eq!(v.user_guid(gone), None, "and is not a user of this version"); - let p = LicensePlanes::build(&v, &[page(&[entry(0, Some(&[]))])], &[]).unwrap(); + let p = LicensePlanes::build(&v, v1, vec![page(&[entry(0, Some(&[]))])], Vec::new()).unwrap(); assert_eq!(p.read().rows(), vec![0], "u0 read"); assert_eq!( p.not_read().rows(), @@ -257,3 +262,188 @@ fn a_repeated_user_is_refused_in_either_order() { // Silence half: one entry per user is admitted. assert!(build(2, &[unread, entry(1, None)]).is_ok()); } + +// ---- D-DIRSIM-LICENSE-DT64-1, Gate 0: the source contract -------------------- + +const GROUP2: &str = "9a1b2c3d-0000-4000-8000-00000000c0de"; + +fn build_pages(users: u8, pages: Vec) -> LicensePlanes { + let st = store(users); + let ver = st.tag("observed").unwrap(); + let v = st.view(ver).unwrap(); + LicensePlanes::build(&v, ver, pages, Vec::new()).unwrap() +} + +/// Reordering the pages, and the users inside them, keeps every code at the +/// same index with the same holders. Falsifier: codes in first-seen order +/// (the order before this correction) put SKU2/Disabled first in one build +/// and last in the other. +#[test] +fn reordered_pages_and_users_keep_every_code_in_place() { + let a = [ + entry(0, Some(&[path(SKU2, "Disabled", None)])), + entry(1, Some(&[path(SKU, "Active", Some(GROUP))])), + ]; + let b = [ + entry(2, Some(&[path(SKU, "Active", None)])), + entry( + 3, + Some(&[path(SKU, "Error", None), path(SKU2, "Disabled", None)]), + ), + ]; + let forward = build_pages(4, vec![page(&a), page(&b)]); + let mut b_rev = b.to_vec(); + b_rev.reverse(); + let mut a_rev = a.to_vec(); + a_rev.reverse(); + let backward = build_pages(4, vec![page(&b_rev), page(&a_rev)]); + assert_eq!(forward.states(), backward.states()); + assert_eq!(forward.states().len(), 4); + for code in 0..forward.states().len() { + assert_eq!( + forward.predicate_iri(code), + backward.predicate_iri(code), + "code {code}" + ); + assert_eq!( + forward.with_state(code).unwrap().rows(), + backward.with_state(code).unwrap().rows(), + "code {code}" + ); + } + // The order is the content's: SKU (c7df…) sorts after SKU2 (4b94…). + assert_eq!(forward.states()[0].sku, g(SKU2)); + // Identity resolves to the index, and an unknown identity to nothing. + let iri = forward.predicate_iri(0).unwrap().to_string(); + assert_eq!(forward.code_of(&iri), Some(0)); + assert_eq!( + forward.code_of("urn:graph:licenseAssignmentState:none"), + None + ); +} + +/// A user whose property is JSON `null` the first time and read the second +/// is still a duplicate. +#[test] +fn a_null_first_entry_is_still_a_duplicate() { + let null = format!(r#"{{"id":"{}","licenseAssignmentStates":null}}"#, user(0)); + let read = entry(0, Some(&[path(SKU, "Active", None)])); + assert_eq!( + build(2, &[null, read]).err(), + Some(LicenseError::DuplicateUser(user(0))) + ); +} + +/// Not listed, listed-not-read, read-empty and read-holding are four answers, +/// and the evidence keeps them apart. +#[test] +fn missing_empty_and_held_paths_stay_distinct() { + let p = build( + 4, + &[ + entry(0, None), + entry(1, Some(&[])), + entry(2, Some(&[path(SKU, "Active", None)])), + ], + ) + .unwrap(); + assert_eq!(p.paths(UserOrdinal(0)), Evidence::NotRead); + assert_eq!(p.paths(UserOrdinal(1)), Evidence::Read(&[][..])); + assert!(matches!(p.paths(UserOrdinal(2)), Evidence::Read(x) if x.len() == 1)); + assert_eq!(p.paths(UserOrdinal(3)), Evidence::NotListed); +} + +/// Two groups assigning one SKU in one state set one bit; the evidence still +/// names both groups. Holders count once, paths count every path. +/// Falsifier: an explanation read from the plane alone could not name either +/// group, and counting paths as holders makes u0 count three times. +#[test] +fn the_evidence_keeps_both_assigning_groups_behind_one_bit() { + let p = build( + 2, + &[ + entry( + 0, + Some(&[ + path(SKU, "Active", None), + path(SKU, "Active", Some(GROUP)), + path(SKU, "Active", Some(GROUP2)), + ]), + ), + entry(1, Some(&[path(SKU, "Active", Some(GROUP2))])), + ], + ) + .unwrap(); + assert_eq!( + p.states().len(), + 2, + "direct and group: two codes, not three" + ); + let group_code = p.states().iter().position(|s| s.via == Via::Group).unwrap(); + assert_eq!(p.with_state(group_code).unwrap().rows(), vec![0, 1]); + let groups: Vec = p + .explain(UserOrdinal(0), group_code) + .unwrap() + .map(|x| x.assigned_by_group.unwrap()) + .collect(); + assert_eq!(groups, vec![g(GROUP), g(GROUP2)]); + assert_eq!(p.holder_count(&g(SKU)), 2); + assert_eq!(p.path_count(&g(SKU)), 4); + assert_eq!( + p.explain(UserOrdinal(0), 9).err(), + Some(ExplainRefusal::NoSuchCode(9)) + ); +} + +/// `assignedLicenses` and `licenseAssignmentStates` are separate properties. +/// A user with effective SKUs and unread paths is not read for the planes, +/// and the effective SKUs are still there as decoded. +#[test] +fn effective_skus_are_not_assignment_paths() { + let only_effective = format!( + r#"{{"id":"{}","assignedLicenses":[{{"skuId":"{SKU2}"}}]}}"#, + user(0) + ); + let p = build(1, &[only_effective]).unwrap(); + assert_eq!(p.paths(UserOrdinal(0)), Evidence::NotRead); + assert!( + matches!(p.effective(UserOrdinal(0)), Evidence::Read(e) if e.len() == 1 && e[0].sku == g(SKU2)) + ); + assert_eq!(p.not_read().rows(), vec![0]); + assert!(p.holders(&g(SKU2)).rows().is_empty()); + assert_eq!( + p.explain(UserOrdinal(0), 0).err(), + Some(ExplainRefusal::NoSuchCode(0)) + ); +} + +fn linked(entries: &[String], next: Option<&str>) -> LicensesPage { + let mut p = page(entries); + p.next_link = next.map(str::to_string); + p +} + +/// Exactly one page ends a collection, in any page order. A link nobody +/// followed is partial; two ends are not one collection. +#[test] +fn coverage_reads_the_page_links_in_any_order() { + let first = || linked(&[entry(0, Some(&[]))], Some("https://graph.example/next")); + let last = || linked(&[entry(1, Some(&[]))], None); + assert_eq!( + build_pages(2, vec![first(), last()]).coverage(), + Coverage::Complete + ); + assert_eq!( + build_pages(2, vec![last(), first()]).coverage(), + Coverage::Complete + ); + assert_eq!(build_pages(2, vec![first()]).coverage(), Coverage::Partial); + assert_eq!( + build_pages(2, vec![last(), linked(&[entry(0, Some(&[]))], None)]).coverage(), + Coverage::Ambiguous + ); + assert_eq!( + build_pages(2, Vec::new()).coverage(), + Coverage::NotCollected + ); +}