Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions crates/lance-graph-dir-sim/src/dt64.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,12 @@ pub const F_UPN: u8 = 0;
/// Field 1 of the user lanes: the primary SMTP value.
pub const F_SMTP: u8 = 1;

/// The predicate of the UPN lane: a basis field with this identity binds it,
/// at whatever position the basis puts it.
pub const UPN_IRI: &str = "dir:userPrincipalName";
/// The predicate of the primary SMTP lane.
pub const SMTP_IRI: &str = "dir:primarySmtp";

/// The schema revision these lanes serve.
pub const LANE_REV: SchemaRev = SchemaRev(1);

Expand Down Expand Up @@ -197,16 +203,23 @@ impl LaneSource for DirLanes<'_, '_> {
&self,
class: u32,
rev: SchemaRev,
field: u8,
_basis: &FieldRef,
_field: u8,
basis: &FieldRef,
_frame: &Frame,
) -> Option<LaneAddr> {
if class != self.class || rev != LANE_REV || field > F_SMTP {
if class != self.class || rev != LANE_REV {
return None;
}
// By identity, never by position: a basis may order its fields
// differently, and an unknown predicate has no lane.
let lane = match basis.predicate_iri.as_str() {
UPN_IRI => F_UPN,
SMTP_IRI => F_SMTP,
_ => return None,
};
Some(LaneAddr {
space: self.space(),
lane: u16::from(field),
lane: u16::from(lane),
scope: self.scope,
})
}
Expand Down
92 changes: 86 additions & 6 deletions crates/lance-graph-dir-sim/src/license.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,15 +126,25 @@ impl LicenseState {
pub enum Coverage {
/// No page was given.
NotCollected,
/// Exactly one page ends the collection and every other page links on.
/// One unbroken `@odata.nextLink` chain from the first page to the last,
/// covering every page once (or a single page that links nowhere).
Complete,
/// No page ends the collection: a `@odata.nextLink` was not followed.
/// A `@odata.nextLink` was not followed: no page ends the collection, or
/// a link names a page that is not here.
Partial,
/// More than one page ends a collection: the pages are not one run.
/// The pages are not one run: more than one end, more than one start, a
/// cycle, or a page outside the chain.
Ambiguous,
/// More than one page and no request URLs: the pages alone cannot show
/// that no page between them is missing (see
/// [`LicensePlanes::build_fetched`]).
Unverified,
}

impl Coverage {
/// From the pages' links alone. A missing middle page leaves the links
/// unchanged, so more than one page with exactly one end is
/// `Unverified`, never `Complete`.
fn of<'a>(links: impl Iterator<Item = &'a Option<String>>) -> Coverage {
let (mut pages, mut ends) = (0usize, 0usize);
for l in links {
Expand All @@ -145,11 +155,52 @@ impl Coverage {
}
match (pages, ends) {
(0, _) => Coverage::NotCollected,
(_, 1) => Coverage::Complete,
(1, 1) => Coverage::Complete,
(_, 0) => Coverage::Partial,
(_, 1) => Coverage::Unverified,
_ => Coverage::Ambiguous,
}
}

/// From the chain: page `k + 1` is the page whose request URL is page
/// `k`'s `@odata.nextLink`, in any delivery order.
fn chain(requested: &[String], links: &[&Option<String>]) -> Coverage {
let n = requested.len();
if n == 0 {
return Coverage::NotCollected;
}
let page_of = |url: &str| requested.iter().position(|r| r == url);
if (0..n).any(|i| page_of(&requested[i]) != Some(i)) {
return Coverage::Ambiguous; // one URL requested twice
}
// The first page: the one no other page links to.
let mut starts = (0..n).filter(|&i| {
!links
.iter()
.any(|l| l.as_deref() == Some(requested[i].as_str()))
});
let (Some(first), None) = (starts.next(), starts.next()) else {
return Coverage::Ambiguous;
};
let mut seen = vec![false; n];
let mut at = first;
loop {
seen[at] = true;
match links[at] {
None => break,
Some(next) => match page_of(next) {
None => return Coverage::Partial,
Some(j) if seen[j] => return Coverage::Ambiguous,
Some(j) => at = j,
},
}
}
if seen.iter().all(|&s| s) {
Coverage::Complete
} else {
Coverage::Ambiguous
}
}
}

/// What the source holds for one user's licence property.
Expand Down Expand Up @@ -212,6 +263,8 @@ pub struct LicensePlanes {
sku_pages: Vec<SkuPage>,
/// Per user ordinal: `(page, entry)` of its listing, if listed.
listed: Vec<Option<(u32, u32)>>,
/// Parallel to `pages`: each page's request URL, when the caller kept it.
requested: Option<Vec<String>>,
}

impl LicensePlanes {
Expand Down Expand Up @@ -321,6 +374,7 @@ impl LicensePlanes {
pages: licenses,
sku_pages: skus,
listed,
requested: None,
})
}

Expand Down Expand Up @@ -357,9 +411,35 @@ impl LicensePlanes {
self.planes.get(code).map(Vec::as_slice)
}

/// Whether the licence pages are one whole collection.
/// [`Self::build`] over pages fetched with their request URLs: `(url,
/// page)` in any order. The URLs let [`Self::coverage`] follow the
/// `@odata.nextLink` chain and see a missing page.
///
/// # Errors
///
/// As for [`Self::build`].
pub fn build_fetched(
v: &View<'_>,
version: VersionId,
licenses: Vec<(String, LicensesPage)>,
skus: Vec<SkuPage>,
) -> Result<Self, LicenseError> {
let (requested, pages): (Vec<String>, Vec<LicensesPage>) = licenses.into_iter().unzip();
let mut planes = Self::build(v, version, pages, skus)?;
planes.requested = Some(requested);
Ok(planes)
}

/// Whether the licence pages are one whole collection. Without request
/// URLs more than one page is at best [`Coverage::Unverified`].
pub fn coverage(&self) -> Coverage {
Coverage::of(self.pages.iter().map(|p| &p.next_link))
match &self.requested {
Some(urls) => {
let links: Vec<&Option<String>> = self.pages.iter().map(|p| &p.next_link).collect();
Coverage::chain(urls, &links)
}
None => Coverage::of(self.pages.iter().map(|p| &p.next_link)),
}
}

/// Whether the capacity pages are one whole collection.
Expand Down
82 changes: 82 additions & 0 deletions crates/lance-graph-dir-sim/tests/dt64_lanes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -274,3 +274,85 @@ fn a_result_over_another_population_is_refused() {
let users = subtree(&view, SCOPE, NodeKind::User, &inside_ou()).unwrap();
assert!(lanes.select(&users).is_ok());
}

/// A basis that lists SMTP before UPN reads each field's own attribute, and a
/// predicate the directory has no lane for is unbound. Falsifier: lanes taken
/// by field position, which reads UPN values under the SMTP field.
#[test]
fn directory_lanes_bind_by_predicate_not_position() {
struct Swapped(Vec<FieldRef>);
impl ClassView for Swapped {
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
}
}
let swapped = Swapped(vec![
FieldRef::new("dir:primarySmtp", "Primary SMTP"),
FieldRef::new("dir:userPrincipalName", "UPN"),
FieldRef::new("dir:department", "Department"),
]);
let mut st = VersionStore::new();
let v = st.observe("ad", 0, observation(3, 0)).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();
let picked = lanes.select(&kept).unwrap();
let mut bs = BindStore::new();
bs.register(
&swapped,
USER,
ClassSchema {
schema_rev: LANE_REV,
field_count: 3,
extent: Extent::DR64_CUBE,
},
Vec::new(),
)
.unwrap();
let version = bs.route(POSITION, USER).unwrap();
let route = RouteAt {
position: POSITION,
version,
};
let frame = lanes.frames().seal();
let req = |fields: &[u8]| LaneRequest {
route,
rev: LANE_REV,
fields: Box::leak(Box::new(WideFieldMask::from_positions(fields))),
frame: Box::leak(Box::new(frame.clone())),
scope: READER,
selection: lanes.space(),
};
let b = bs
.bind_lanes(&swapped, lanes.frames(), &lanes, req(&[0, 1]))
.unwrap();
let (smtp, rows) = b
.selected(&bs, &swapped, lanes.frames(), &lanes, 0, picked.sel)
.unwrap();
for &r in rows {
let g = view.user_guid(UserOrdinal(r as u16)).unwrap();
assert_eq!(
smtp.get(r),
view.attr(&g, Attribute::PrimarySmtp).map(|x| x.0)
);
assert_ne!(smtp.get(r), view.attr(&g, Attribute::Upn).map(|x| x.0));
}
assert_eq!(
bs.bind_lanes(&swapped, lanes.frames(), &lanes, req(&[2]))
.err(),
Some(LaneRefusal::Unbound {
class: USER,
field: 2
})
);
}
39 changes: 22 additions & 17 deletions crates/lance-graph-dir-sim/tests/license_dt64.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,8 +127,9 @@ fn entry(u: usize) -> String {
}
}

/// The users in four pages of 128, linked except the last, in `order`.
fn pages(order: [usize; 4], reverse_users: bool) -> Vec<LicensesPage> {
/// The users in four pages of 128, linked except the last, in `order`, each
/// with the URL it was requested at (page `p + 1`'s URL is page `p`'s link).
fn pages(order: [usize; 4], reverse_users: bool) -> Vec<(String, LicensesPage)> {
order
.iter()
.map(|&p| {
Expand All @@ -140,7 +141,7 @@ fn pages(order: [usize; 4], reverse_users: bool) -> Vec<LicensesPage> {
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
(format!("https://graph.example/users?page={p}"), page)
})
.collect()
}
Expand Down Expand Up @@ -300,7 +301,8 @@ 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();
let planes =
LicensePlanes::build_fetched(&view, v, pages([0, 1, 2, 3], false), Vec::new()).unwrap();
assert_eq!(
planes.states().len(),
MAX_LICENSE_STATES,
Expand Down Expand Up @@ -452,17 +454,17 @@ fn the_65th_licence_state_code_is_refused() {
))
.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<LicensesPage> = ps
ps.last_mut().unwrap().1.next_link = Some("https://graph.example/users?page=4".into());
let mut ps2: Vec<(String, LicensesPage)> = ps
.into_iter()
.map(|mut p| {
.map(|(url, mut p)| {
p.users.retain(|x| x.user != user(5));
p
(url, p)
})
.collect();
ps2.push(extra);
ps2.push(("https://graph.example/users?page=4".into(), extra));
assert_eq!(
LicensePlanes::build(&view, v, ps2, Vec::new()),
LicensePlanes::build_fetched(&view, v, ps2, Vec::new()),
Err(LicenseError::TooManyStates {
found: 65,
limit: 64
Expand All @@ -479,7 +481,8 @@ fn stale_foreign_and_mismatched_bindings_are_refused() {
// 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 planes0 =
LicensePlanes::build_fetched(&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);
Expand All @@ -488,7 +491,8 @@ fn stale_foreign_and_mismatched_bindings_are_refused() {
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();
let planes_r =
LicensePlanes::build_fetched(&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!(
Expand All @@ -503,7 +507,7 @@ fn stale_foreign_and_mismatched_bindings_are_refused() {
// 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 (_, p) in &mut later {
for u in &mut p.users {
if let Some(paths) = &mut u.paths {
paths.retain(|x| {
Expand All @@ -512,7 +516,7 @@ fn stale_foreign_and_mismatched_bindings_are_refused() {
}
}
}
let planes1 = LicensePlanes::build(&view1, v1, later, Vec::new()).unwrap();
let planes1 = LicensePlanes::build_fetched(&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();
Expand Down Expand Up @@ -596,7 +600,7 @@ fn stale_foreign_and_mismatched_bindings_are_refused() {
Err(LaneRefusal::FieldNotInBasis { .. })
));
// An incomplete collection is not served.
let partial = LicensePlanes::build(
let partial = LicensePlanes::build_fetched(
&view0,
v0,
pages([0, 1, 2, 2], false)[..3].to_vec(),
Expand Down Expand Up @@ -644,7 +648,8 @@ fn an_uncollected_licence_property_has_no_lane() {
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 planes =
LicensePlanes::build_fetched(&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![
Expand Down Expand Up @@ -723,7 +728,7 @@ fn the_512_user_projection_builds_no_cartesian_table() {
for _ in 0..RUNS {
let input = source.clone();
let t = Instant::now();
planes = Some(LicensePlanes::build(&view, v, input, Vec::new()).unwrap());
planes = Some(LicensePlanes::build_fetched(&view, v, input, Vec::new()).unwrap());
build_ns.push(t.elapsed().as_nanos());
}
let planes = planes.unwrap();
Expand Down
Loading