Repository navigation
fix(r2rml): class-targeted view policies are decided on every class a subject can hold - #2390
Conversation
…er the same policy Differentials, each ignored until the change that makes it pass: a class-targeted view policy over an R2RML graph source is checked against a native ledger holding the same triples under the same policy, on SPARQL and JSON-LD, fast paths on and off, over the Iceberg source and its SQL twin. The shapes: a governed source reached through GRAPH, as a dataset's named graph and from a query over one ledger; a combined class and property restriction over a map whose class comes from a column; a class derived through a reference to another map; a predicate a classed map and a column-typed map both mint; a schema class declared beside a data class; a subject two maps mint with different classes; and a subject several rows mint, each deriving a class.
…licy A scan reached through GRAPH runs in a context switched from another graph, which kept that graph's policy enforcer. The view-policy gate read the context's enforcer, so a governed source that was a named graph of a dataset was decided by the default graph's policy: with none, the gate was absent and the scan read the source unfiltered (a debug build stopped on an assertion instead); with a request policy, the source's own model was not applied. Its targets were also encoded against the default graph's namespaces, where the source's policy was built against its own. The gate now takes the enforcer and the snapshot of the source's own graph when the dataset has one, and the context's otherwise. Where filtering is required and no enforcer resolves for the source, the scan is refused rather than read unfiltered, in the scan lane and the SQL lane alike.
…s a gate decides by The view-policy gate listed the classes a restriction targets only from restrictions selected by class. A restriction on a property of a class (f:onProperty with f:onClass) is indexed by its property, so its class was missing from that list, and the SQL lane, which turns a column-derived class into a per-class verdict, decided such a restriction as if it applied to no row: a combined deny over a map whose class comes from a column allowed every row. The list now holds the classes of every class-targeted restriction.
…n every property A class-targeted view restriction is indexed by the properties its classes' subjects use, and skips the class check for a property only instances of those classes are known to use. Over an R2RML source those uses come from the mapping, which credits a property to static classes only: where a classed map and a map deriving its class from a row (or declaring none) both mint a property, the second map's rows were decided as if they held the first map's class. Every class-targeted entry now checks the subject's classes, which is what the restriction means; the skipped check was only a shortcut for stats that cover every instance.
… view policy A view policy deciding by class reads each row's derived classes from the map's rdf:type object maps. A reference to another map's subjects is one of them, but its parent was resolved only when the pattern read rdf:type, so for any other predicate the row had no derived class and a class-targeted restriction did not apply to it. When the gate needs a map's row classes, its rdf:type references now resolve their parents whatever the pattern reads, a reference's class is never rendered from the child's key (a dangling key mints none), and a reference whose parent cannot be read refuses the query.
The view-policy gate decided every rdf:type triple of a map on the map's first class, as the object a schema class is recognized by. A map declaring a schema class (owl:Class, rdfs:Class) beside a data class had every type triple decided as the schema class's, which is always viewable, so a restriction on the data class did not apply to them. A type triple is now decided on the class it states: the class the pattern selects, the row's projected ?type, or a wildcard row's object; a bare subject is decided on a placeholder no schema class matches. A map that can still yield is one with a viewable class among those the pattern reads, and the SQL lane declines a map whose classes' type triples are decided apart.
…set a subject could hold A row shows its map's classes and the classes it derives, but its subject can hold more: another map minting the same subjects can declare others, and where a map's subjects are not proven one row's, or another such map derives classes, other rows can derive them. The gate decided each row on its own classes, so a subject several maps or rows mint was decided on a subset of its classes, in either direction. A row is now shown only when the policy allows it for every class set its subject could hold: its own classes plus any of the classes a restriction applying to the predicate targets that an overlapping map declares or a deriving map's template could mint. Without f:required and f:query restrictions two evaluations settle it (the doc comment on the gate's decision gives the argument); with them every set is evaluated, up to 8 extra classes, beyond which the query is refused. Where the extra classes come from the mapping alone and the decision varies, the row is hidden, the map is named on the tracked response (policy_enforcement .undecidable_class_maps) and logged once. Where they depend on rows the scan does not read and the decision varies, the query is refused with err:db/InvalidQuery, naming the map and the remedies: declare the table's key, map a history table's current rows with an rr:sqlQuery and its key, or target the policy by property or subject. A key is trusted here as the deduplication that relies on it is. Nothing changes without a class-targeted restriction: no other map's classes are worked out and every decision is one evaluation, as before.
…ifferent classes A source registered with a model now reports, in model_warnings, each pair of triples maps whose subjects are not provably apart and that declare different classes, or where one derives classes from its row: a class-targeted view policy decides such maps' rows over every class set a subject could hold, and may hide rows a native ledger would show.
…r, and what it does otherwise The Iceberg access-policy section claimed native parity for f:onClass unconditionally. It now states the conditions (each row shows every class its subject holds), what happens otherwise (rows hidden on classes another map declares and surfaced on the tracked response, or the query refused where the classes depend on rows the scan does not read), the remedies, and that a declared key is trusted there as for set semantics. The SQL and R2RML pages point to it, R2RML says which subjects count as overlapping, and the policy reference lists the new tracked-response field.
…on; the class-set cap refuses Unit tests on the view-policy gate: without a class-targeted restriction no other map's classes are worked out and each (map, predicate) is one cached evaluation; with one, a map another differently classed map overlaps is decided over its class sets (two evaluations, then cached); and a decision needing more extra classes than the enumeration's cap refuses, naming the map and the count. The class-policy differentials name their fixture table type for clippy.
…licy-decisions # Conflicts: # fluree-db-query/src/r2rml/operator.rs
…class-policy-decisions # Conflicts: # fluree-db-api/tests/it_iceberg_policy.rs # fluree-db-query/src/r2rml/operator.rs # fluree-db-query/src/r2rml/policy.rs # fluree-db-query/src/r2rml/sql_lane/mod.rs
…e class-policy section
bplatz
left a comment
There was a problem hiding this comment.
Approving. The two-evaluation check holds up against the evaluator: deny overrides, and the rules that apply only grow as classes are added. I left feedback inline. The shift overflow in policy.rs and the SQL-lane coverage should be fixed before merge; the rest are suggestions, questions and nits.
| object, | ||
| &own, | ||
| &extra, | ||
| (1u32 << extra.len()) - 1, |
There was a problem hiding this comment.
With 32+ extra classes this shift (and 1 << i at line 982) overflows. Debug panics; release wraps, so the "every class" set loses classes (32 → none of them, 40 → 16 of 40), and the row is decided on its own classes again. Reachable with one f:onClass listing 32+ classes over an unkeyed map that types from an IRI column. Suggest passing the full set directly instead of as a mask, plus a unit test with 32+ classes.
There was a problem hiding this comment.
Really good catch -- and you're right that release would quietly decide the row on its own classes again, which on a deny is exactly the wrong direction to fail. Fixed in 5e2dd4f by getting rid of the mask rather than widening it: subsets now come from the class list itself (subsets() counts over a flag vector) and decide_with takes the chosen classes, so no integer width bounds how many classes there can be. The 8-class cap still bounds the actual enumeration -- every enumerating path calls check_extra_cap first -- and the two-point path passes the whole set in one evaluation, so it needs no bound at all.
Two tests pin it with 33 and 70 extra classes: a_decision_counts_every_extra_class_however_many (two-point path; the denied class sits past bit 32 and still hides the row) and an_enumeration_past_the_cap_is_refused_however_many_classes (enumerating path; refused). Both panic with "attempt to shift left with overflow" on the old code. I also swept policy.rs and the SQL lane for any other mask or shift over a class count -- none; the remaining shifts are fixed constants (set-semantics arena slot packing, statement_max_bytes).
| } | ||
|
|
||
| /// The lanes a case runs on: the Iceberg source and, with `sql`, its SQL twin. | ||
| async fn register(fluree: &Fluree, source: &Source) -> Vec<String> { |
There was a problem hiding this comment.
Nothing pins which SQL lane answered, so the SQL cases could all pass on the per-scan lane and never exercise the static_verdicts changes. One MustFire case (say, the class + property policy over the column-typed map), as in it_sql_pushdown_lane, plus a check that the refusal happens on both lanes, would cover it.
There was a problem hiding this comment.
Fair -- the rows matching native didn't prove the pushdown lane ever decided anything. 632b59c adds the_sql_cases_run_on_each_sql_lane:
- the class + property policy over the column-typed map: with fast paths on, the
sql_block_pushdownstamp isproceed(itsByClassverdicts decide), and with them off there's no stamp (per-scan) -- both match native; - the history map: refused on both lanes -- with fast paths on, the pushdown lane refuses while planning (pinned by a new debug event, "sql pushdown refused: policy"), and with them off the per-scan lane refuses.
And to confirm your point directly: with the lane forced to decline (static_verdicts → None), the rows still match native and only the stamp check fails -- so before this test the SQL cases genuinely could all have passed on the per-scan lane.
| let enumerate = view | ||
| .restrictions | ||
| .iter() | ||
| .any(|r| r.required || matches!(r.value, fluree_db_policy::PolicyValue::Query(_))); |
There was a problem hiding this comment.
Suggestion: an f:required/f:query restriction anywhere in the set turns on full enumeration for every decision, even on predicates it can't apply to. That's where the 8-class refusal and up to 256 evaluations per decision come from (uncached per row under a subject policy). Limiting this to restrictions that can apply to the predicate would avoid most of it.
There was a problem hiding this comment.
Agreed, and done here -- 2d2d12c. Only an f:required/f:query restriction that can apply to the predicate being decided turns on full enumeration now: one targeted by property applies to its own properties (subproperties included, since the set is expanded before indexing), and one targeted any other way still applies to every predicate. On an uncached per-subject shape with 3 extra classes, adding an unrelated f:required on another property took the query from 26.1 ms to 12.1 ms (instructions -59%), which is the same as the shape without it; the PR's original shapes are within noise, with identical rows.
| .decide_with(ctx, subject, pred, object, &own, &extra, subset) | ||
| .await? | ||
| { | ||
| return Err(QueryError::InvalidQuery(format!( |
There was a problem hiding this comment.
Minor: when only the other-map extras change the decision, this still refuses, naming derived classes that don't matter, where the other-map rule alone would hide the row. It fails closed, so not blocking.
There was a problem hiding this comment.
You're right that it was refusing more than it needed to -- 944be13 makes the rule exact. The row is now hidden when every choice of derived classes meets some choice of the other maps' declared classes that denies (the answer is "hidden" whatever the unread rows hold, and the map is recorded under undecidable_class_maps), and it's refused only when some choice of derived classes would show the row under every declared choice -- i.e. only when the derived classes actually change the verdict. derived_classes_that_change_nothing_do_not_refuse pins it and fails on the old refusal.
| <http://example.org/mapping#KindMapping> | ||
| a rr:TriplesMap ; | ||
| rr:logicalTable [ rr:tableName "silver.people" ] ; | ||
| rr:logicalTable [ rr:tableName "silver.people" ; <https://ns.flur.ee/db#key> ( "id" ) ] ; |
There was a problem hiding this comment.
This fixture needing f:key to keep passing is the breaking case for users: Iceberg tables often declare no identifier fields, so these setups start returning 400. Failing closed seems right; worth a prominent release note.
There was a problem hiding this comment.
Agreed it's the one users will hit, and that fail-closed is still right. The description now leads its breaking changes with a release note for it: what returns 400 and when, that Iceberg tables often declare no identifier fields, and the three remedies (declare f:key; map a history table's current rows with an rr:sqlQuery and its key; or target the policy by property or subject), plus what isn't affected.
| /// rows over every class set its subjects could hold, hiding rows a decision | ||
| /// on one row's classes would show (or, where the classes come from rows the | ||
| /// scan does not read, refusing the query). | ||
| pub fn class_overlap_warnings(mapping: &CompiledR2rmlMapping) -> Vec<String> { |
There was a problem hiding this comment.
Question: two tables sharing a template (e.g. customers_us/customers_eu on http://ex/c/{id}) under a class deny can lose the whole non-denied table, and the only fix offered is changing subject templates (i.e. IRIs). Worth a follow-up issue for declaring two maps' subjects disjoint, the way f:key is declared?
There was a problem hiding this comment.
Good question, and I think yes -- a declared disjointness, trusted the way f:key is, is the right shape for it, rather than asking people to change IRIs. It's new mapping vocabulary with its own trust question (and how it would interact with #2320's verification), so I'd rather it get its own design than land under this PR: filed as #2424. Until then this PR keeps failing closed for that case; the R2RML page spells out when two templates count as overlapping (templates whose constant text before the first placeholder can't be a prefix of the other's mint apart), which is today's way out.
| warnings | ||
| } | ||
|
|
||
| /// The prefixes a class `tm` derives from its row starts with (see/// The prefixes a class `tm` derives from its row starts with (see |
There was a problem hiding this comment.
Nit: this doc line is duplicated.
There was a problem hiding this comment.
Thanks -- removed in 64b08c6 (a doc comment that had come in from main onto static_verdicts is moved back onto needs_row_classes, where it belongs).
| } | ||
| } | ||
| ObjectMap::Column { term_type, .. } => { | ||
| derives = true; |
There was a problem hiding this comment.
Nit: a literal rdf:type (column or template) marks the map as deriving, so class_overlap_warnings warns about a map that can't mint a class.
There was a problem hiding this comment.
Good catch -- fixed in 64b08c6: only an IRI-typed template or column marks a map as deriving now, so a literal rdf:type gets no overlap warning and no key fetch (a_literal_type_derives_no_class). One sibling left as is, since it only costs time: derived_type_columns still projects a literal type column for row classes, which yields no class because row classes keep IRIs only.
| rows mint one subject; for a history table, map its current rows with an | ||
| `rr:sqlQuery` (`SELECT * FROM t WHERE <current-row condition>`) and declare | ||
| the key there; or target the policy by property or subject. | ||
| - A decision needing more than 8 such classes is refused the same way. |
There was a problem hiding this comment.
Nit: the cap applies whenever every class set is enumerated (an f:required/f:query restriction, or a refusal check), not only to classes other rows derive, and not to other-map extras otherwise.
There was a problem hiding this comment.
Right, that was too narrow -- corrected in 54e8697. The doc now says the cap applies wherever every class set is evaluated (a predicate an f:required/f:query restriction can apply to, or the check before a refusal), counting declared and derived extra classes, and that other decisions take two evaluations. It also mentions the new hide-instead-of-refuse case.
A decision over the classes a subject might also hold enumerated subsets as bits of a u32. With 32 or more extra classes the shift overflowed: debug builds panicked and release builds wrapped, so the "every class" set lost classes and a row could be decided on its own classes again. Subsets are now built from the class list itself, so no width bounds their count; the cap of 8 extra classes still bounds the enumeration. Unit tests decide over 33 and 70 extra classes, on the two-point check and against the cap.
An f:required or f:query restriction anywhere in the view set turned on full enumeration (and with it the 8-class cap) for every decision. A property-targeted restriction applies only to its properties (indexed by them, subproperties included), so a decision on another predicate is settled by the two-point check. Restrictions targeted any other way still enumerate on every predicate.
When the classes other maps declare deny a row whatever classes other rows derive, the other-map rule hides it (and records the map); the query is refused only when some choice of derived classes would show the row under every choice of declared ones.
A template or column minting a literal rdf:type object marked its map as deriving classes, so class_overlap_warnings warned about a map that cannot mint a class and the gate fetched its table's keys for nothing. Also drops a duplicated doc line and moves a misplaced doc comment back onto needs_row_classes.
The class-policy suite's SQL cases could all pass on the per-scan lane. A new case checks the routing stamp: the class and property policy over the column-typed map proceeds on the pushdown lane with fast paths on (its per-class verdicts decide) and takes the per-scan lane with them off, matching the native ledger on both. The history map's refusal comes from each lane; the pushdown lane now logs a debug event when its policy decision refuses the block, which the case checks.
The cap applies whenever every class set is evaluated (a predicate an f:required/f:query restriction can apply to, or the check before a refusal), counting declared and derived extra classes; other decisions take two evaluations. Also notes that a row the other map's classes deny whatever is derived is hidden, not refused.
|
Thanks @bplatz -- really careful review, and I appreciate you checking the two-evaluation argument against the evaluator itself. Everything you raised is in this PR (5e2dd4f..54e8697), with replies on each thread:
Main's latest is merged in too. The full CI-equivalent run on that head is green apart from two |
Brings #2409 and #2390. Query peers: main deletes the shared-storage peer's sync task, which wrote the transaction server's nameservice, and runs both storage modes through one event sink that follows records with `LedgerManager::follow`, a worker per ledger. next had taught both tasks new events; they now live on that sink: - A completed snapshot evicts cached ledgers the subscription covers but the snapshot did not name, through each ledger's worker as a retraction is, and retracts graph sources known before the connect. A snapshot that missed an erasure refresh refreshes every cached ledger. - A retraction carries the ledger instance it was for: one of an earlier ledger under the name leaves a newer watermark, and the ledger it is for stays cached while the nameservice still has it. A watermark of another instance counts as changed. - `LedgerRefresh` refreshes the ledger; records feed the retention watch; graph source updates and retractions reach the event bus, as the shared-storage task did. - The sync task's local mirroring, fences and resets are gone with it: a peer no longer writes a nameservice. The ledger manager: main's line (an index install planned before a reload or rebase is not made after it), `follow`, and the planned notify go onto next's notify, which takes the catch-up lock first; the line is read under that lock, before the record. A reload installs a state of another activation whatever its `t` (next) or any state when a follow says the line was replaced (main). `follow` evicts a ledger the nameservice no longer has, as next's notify does. `refresh` keeps next's lookup on every call, with main's line taken before it. A read-only client also takes no lock on the root, which next takes by default, and `get_local` (next's replacement for `resolve_local_path`) reports a miss without applying a writer's log. The CLI runs main's bounded runtime shutdown on next's larger driver thread. Peer `/info` loses next's simplified proxy form with main.
What was wrong
A class-targeted view policy (
f:onClass, alone or withf:onProperty) on an R2RML graph source (Iceberg or SQL)was decided from one row's classes. A subject minted by several triples maps or rows could be decided on a subset of
its classes, in either direction. Related gaps in the same view-policy gate:
f:onPropertywithf:onClass) was missing from the classes the SQL lanedecides by, so over a map whose class comes from a column it applied to no row there;
so the rows of a map deriving its class from a row, or declaring none, were decided as if they held another map's
class;
rdf:typeas anrr:parentTriplesMap) gave the row no class unless thepattern read
rdf:type;owl:Class) declared beside adata class decided all of them.
What changes
the subject's classes.
rdf:typereferences resolve their parents whenever the gate needs row classes; a reference whose parent cannot beread refuses the query.
?type, or awildcard row's object).
targeted class an overlapping map declares or a deriving map's template could mint. Without
f:requiredandf:queryrestrictions two evaluations settle it (the argument is in the doc comment); with them every set isevaluated, on the predicates such a restriction can apply to, up to 8 extra classes, beyond which the query is
refused. Class sets are built from the class list itself, so no integer width bounds how many classes a decision counts.
response (
policy_enforcement.undecidable_class_maps), logged once per map, and reported at registration inmodel_warnings(each pair of overlapping, differently classed maps).400 err:db/InvalidQuery, naming themap and the remedies (declare
f:keyif no two rows mint one subject; map a history table's current rows with anrr:sqlQueryand its key; or target the policy by property or subject).one evaluation (asserted by a unit test).
TriplesMap::with_subject_templaterecords the template's columns, as the mapping loader does.f:onClassmatches a native ledger and what happens otherwise;the R2RML page says which subjects count as overlapping; the SQL page and the policy reference point to it. A
declared key is trusted for this decision as it is for set semantics.
Breaking changes (for embedders)
rdf:typefrom its row, whose subjects no key proves unique,is refused with
400 err:db/InvalidQuerywhen the decision depends on another row's classes. Declaref:key.hidden where they were shown before (they are now decided over every class the subject could hold).
fluree_db_core::PolicyEnforcementgainsundecidable_class_maps(struct literals need it; it is serialized onlywhen non-empty).
fluree_db_query::r2rml::class_overlap_warningsis new (public).Tests
it_r2rml_class_policy(new binary): each shape against a native ledger holding the same triples under the samepolicy, on SPARQL and JSON-LD, fast paths on and off, over the Iceberg source and a SQL source with the same rows:
a combined class and property restriction over a column-typed map; a reference-derived class; a predicate a classed
map and a column-typed map both mint; a schema class beside a data class (
?s a <C>,?s a ?t, a wildcard); a subjecttwo maps mint with different classes (no row the native ledger hides is shown, the hidden row pinned, the tracked
response names the map); a history table deriving a class per row (refused; a class its template cannot mint keeps
parity); and an
f:requiredrestriction where only the every-set evaluation keeps out a row the native ledger hides.it_iceberg_policy:KINDS_R2RMLdeclares its key and keeps native parity; an unkeyed derived-class map is refused.Unit tests: the extra-class computation, the overlap warnings, one evaluation per decision without class policies,
and the cap refusal.
Each fix's differential failed before it. The subset rule's tests fail with the extra classes removed, and the
f:requiredtest fails with the two-evaluation check forced.Performance
Release build, quiet dedicated 32-vCPU cloud machine, 5 interleaved rounds × 100 queries,
?s ex:name ?nover a 3,000-row 5-file table,median ms/query (instructions for the whole run):
No measurable change.
Gates
At 31ba7ec (the review fixes with main merged in, through #2214 and #2227), on a cloud machine with CI's commands: fmt (workspace,
testsuite-sparql,fluree-sql-bridge);cargo clippy --all --all-features --all-targets -- -D warnings, plus thetestsuite-sparqlandfluree-sql-bridgeclippy; both wasm32 clippy lanes;fluree-db-serverwith no default features;harness_coverage2/2; doctests; the W3C suite (85);fluree-sql-bridgetests; the live bridge differential against SQLite, Postgres and MySQL (it_sql_pushdown_lane,it_sql_graph_source,it_sql_set_semantics).cargo nextest run --workspace --all-features --no-fail-fast: 16415 passed, 2 failed, 46 skipped; the two failures wereit_ill_typed_literalstests that failed identically on main at the time (since fixed on main by #2430). After merging main again (7940a77, with #2430), those pass locally (5/5), as doit_r2rml_class_policy8/8 andit_iceberg_policy24/24, and CI is the final check. Not run: the wasm Node smoke and the Python jobs (CI runs them).