Skip to content

fix(policy): class policies apply by reasoned classes in reasoning queries - #2392

Merged
bplatz merged 11 commits into
mainfrom
fix/class-policy-reasoned-classes
Nov 18, 2026
Merged

bplatz merged 11 commits into
mainfrom
fix/class-policy-reasoned-classes

Conversation

@bplatz

@bplatz bplatz commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Under OWL 2 RL and datalog, an f:onClass view policy now applies by the classes the query reasons to, and to every property of the class's members, including properties that reasoning adds. View-side class targeting now works the way write-side targeting already does, by the subject's classes.

This brings the class-policy changes from #2292 (on next) to main.

Changes

  • Class policies in reasoning queries. A query that reads derived facts is judged by a view set that selects f:onClass policies by the subject's classes, instead of by the properties the class statistics list for the class. The statistics describe asserted data, so they know neither a member that holds the class only by derivation nor a property that reasoning adds to an asserted member. Queries without reasoning keep the statistics-based index. Dataset graphs that read derived facts switch the same way.
  • Class cache keyed by state. One policy-wrapped view shares its class cache across queries. Entries are now keyed by graph, t and the overlay's content version, so a plain query and a reasoning query on the same view don't answer each other's class lookups. The enforcer resolves the subjects its checks read itself, so the callers' batch prefetches are gone; staging keeps its prefetch for single-flake checks, which also records untyped subjects. An overlay with no content version resolves classes into a map that lives for the call, not the shared cache.
  • Class check on every property (all queries under a class policy). A view set skipped the class check on a property the class statistics credit to the target classes alone. Statistics count typed subjects only, so an untyped subject carrying that property was let through by an f:onClass allow under default-allow: false, and hidden by a deny though it is no member. Every class-policy entry now checks the subject's classes. Cypher's and GraphQL's schema pruning no longer drops a property for an f:onClass deny.
  • Docs. docs/query/reasoning.md, docs/security/policy-in-queries.md and docs/security/policy-in-transactions.md describe class targeting in a reasoning query, including that a derived fact can grant access as well as deny it, and that a plain query is judged on stored facts (f:OverrideNone makes reasoning unavoidable).

Performance

Reasoning queries under a non-root policy that has f:onClass restrictions treat every predicate as covered and take the filtered scan path, with a per-subject class lookup. Plain queries under such a policy add one set lookup per fact for the class check; the classes were already resolved. The reasoned view set is built only when a reasoning query first reads it. Queries without a policy and root queries are unchanged.

Tests

  • it_reasoning_policy_contract:

    • datalog: a derived member and an asserted member's derived property, across scan, aggregate, join and SPARQL;

    • OWL 2 RL: a subPropertyOf-derived property under a required f:query class policy, in JSON-LD and SPARQL;

    • a plain and a reasoning query sharing one view, in either order.

    • a rule-derived class granting an f:onClass allow in a reasoning query only.

    Each case runs on novelty-only and indexed storage.

  • it_policy_allow: an untyped subject on a property statistics credit to one class, under an f:onClass allow and a deny, on novelty-only and indexed storage.

  • Unit tests for the reasoned view set, cache keys across overlays, and an overlay with no content version.

…ses by state

Two defects in view policy over materialized reasoning, both at query
time:

- An f:onClass view policy was expanded into the properties class
  statistics list for the class's asserted members. Statistics know
  neither a member only by derivation nor a derived property of an
  asserted member, so a class policy did not reach either. A query
  with derived facts now uses a view set that selects class policies
  by the subject's reasoned classes on every property, as write sets
  do; fast paths see every predicate as covered. Datasets switch the
  graphs that read derived facts.

- One policy-wrapped view shares its class cache across queries, keyed
  (graph, t, subject). A plain and a reasoning query at the same t read
  different memberships, and each answered the other's lookups.
  Entries are now keyed by the overlay's content version, or its epoch
  where it has none.

(cherry picked from commit 5fb7832)
… version

An overlay's epoch is unique only within its own lineage, so two unrelated
overlays at the same graph and `t` could share cached classes. A state of
an overlay with no content version now gets an identity of its own each time
it is taken. The enforcer caches, under the state it reads with, every
subject a check reads, rather than relying on a caller's prefetch: a miss
reads as no classes.

(cherry picked from commit ed74d85)
@bplatz bplatz added the bug Something isn't working as expected label Nov 14, 2026
@bplatz
bplatz requested a review from a team November 14, 2026 04:48

@aaj3f aaj3f left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bplatz this is D5 on main done the way write-side policy already works, and keying the class cache by read state is the right primitive. Approving to unblock, with two small musts below.

My reading is that this ships D5 on main, so a rule can now grant a class's access on every property in a reasoning query, not just deny it; I think that's right, but I'd like your confirmation that main is the intended line.

Unlike next, a crawl here still renders and judges stored classes, so a derived-class deny reaches the rows but not the crawl; that's no worse than main today and the docs say so, but I'd like confirmation that it's deliberate.

The one I'd hold the merge for: the enforcer now fills the class cache itself, but every caller still prefetches, so plain queries under a class policy do the work twice per batch (Claude measured up to +44% on a box). Deleting the scan's now-redundant prefetch brought it back within noise.

Full review below:


✅ Approving to unblock: please get the redundant class-cache prefetches out and the D5 docs paragraph in before merging. Selecting class policies by subject in a reasoning query, and keying the class cache by graph, t and overlay version, closes both leaks cleanly, and the mutation checks show the new tests pin both; the two musts are each a few lines.

Before merging:

  1. fluree-db-query/src/policy/enforcer.rs:130: drop the batch callers' prefetches (binary_scan.rs:1142-1150 first) now the enforcer populates; plain class-policy queries regress up to +44% otherwise.
  2. docs/query/reasoning.md:449: port next's "Policy reads what the query reads" (grant-by-rule, the plain-query escape and its f:OverrideNone mitigation), here and in policy-in-queries.md.

Decisions on the record: D5 (ratified on #2292) holds on both halves here: a reasoning query is judged by reasoned classes (runner.rs:989, dataset.rs:376), and a query that does not reason keeps the stats-based set and is judged on stored classes (pinned by one_view_judges_classes_by_each_query_s_reasoning). Caller-supplied rules are still stripped under a non-root policy (fluree-db-api/src/view/query.rs:1690), so grant-by-rule needs someone who can write stored rules or their inputs, which is the consequence we accepted.

Notes:

  • This is another instance of "class membership for an f:onClass policy decided from a source other than the state the read sees": modify sets through statistics (d0b6d8868), reasoning views through statistics (this PR), R2RML from one row's classes (#2390), a reasoning query's crawl on stored classes (#2287). The class fix would be selecting class policies by subject for every view set, with statistics kept only as a coverage hint for fast paths. Not this PR: the point fixes are right here.
  • Merge order: this merges cleanly with #2214 and #2201 (git merge-tree), in either order, with no rebase. #2214's new lanes ask classify_view_predicate, which this PR routes through view_set(), so a reasoning query's lanes get the reasoned set with no change on either side.
  • The reasoned set covers every predicate, so a reasoning query under any class policy loses its fast lanes, by design. On the box, an indexed OWL 2 RL query under a class policy whose class no subject holds went from 12.9 ms to 70.9 ms (dev-fast build), while one whose class members do hold the scanned property (so statistics already covered it) moved +5.6% (release build). D5's "roughly +10%" was the second case; policy-in-queries.md "Performance under a policy" (:110-112) may want a sentence that the first one exists.
Adherence: Patterns ✔ · Performance ✖ CRITICAL · Deployment ✔ · Testing ✔ · Conventions ⚠️ · verification
  • Patterns/abstractions: ✔ extends PolicySet::by_class (the modify-set mechanism from d0b6d8868) and OverlayProvider::content_version; no parallel construct, and it applies to SPARQL and JSON-LD alike through the shared IR.
  • Performance (speed first, memory second): ✖ CRITICAL: non-reasoning queries under a class policy populate the class cache twice per batch and re-read untyped subjects (release build: +28.9% novelty-only and +44.0% indexed over untyped subjects, +13.3% indexed over typed ones); deleting the scan's prefetch recovers it. Reasoning queries under a class policy take the filtered path by design.
  • Deployment targets: ✔ shared code every host runs; the new state is per policy context, not process-lifetime, and wasm32/wasm-smoke are green on the head SHA.
  • Testing: ✔ nine contract tests in grp_reasoning on novelty-only and indexed storage ran by name in CI; Claude's mutation checks turn three (no reasoned-view swap) and one plus the unit test (overlay dropped from the key) red. ⚠️ nothing pins the grant half.
  • Conventions: ⚠️ multi-line bodies on both fix commits (the test commit is subject-only, which is fine); the docs carry D5's deny half but not its consequences.

Verified at f81e44d4b: CI run 43558434291 green, including all nine it_reasoning_policy_contract tests by name; on a c7i.4xlarge, Claude re-ran the contract tests (9/9), ran both mutation checks (red, restored), and ran a base/head probe on release and dev-fast builds plus three fix variants (5 interleaved rounds × 15 reps each); git merge-tree against #2214 and #2201 is clean.

Approving so you can merge once those two are in, but maybe worth considering the optional items first.

Comment thread fluree-db-query/src/policy/enforcer.rs Outdated
// Create executor using the GRAPH's snapshot/overlay/to_t (not ctx-level!)
let executor = QueryPolicyExecutor::with_overlay(snapshot, overlay, to_t);
let state = ClassState::new(g_id, overlay, to_t);
self.cache_subject_classes(state, snapshot, g_id, overlay, to_t, &flakes)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking, CRITICAL (performance).

Plain queries under a class policy now populate the class cache twice per batch, and pay up to +44% for it.

Since c5e61b1bf, filter_flakes_for_graph and allow_flake_for_graph populate the cache themselves, under the state they read with (here and :200-208, via cache_subject_classes at :234-253). That's the right owner for it. But every caller still prefetches first: binary_scan.rs:1142-1150 on the scan path, and hydration.rs:2792, block_fetch.rs:423, cypher_typed.rs:525, graph_commit_builder.rs:324 and stage.rs:2699. So each batch collects, clones, sorts and dedups its subjects twice, and takes the cache lock twice with a key clone per subject. Worse, populate_class_cache_in stores only what lookup_subject_classes returns, which leaves out every subject with no rdf:type (class_lookup.rs:27, :141-143), so an untyped subject's rdf:type is read twice per batch. None of this depends on reasoning: it runs for every non-root query whose policy has an f:onClass restriction, which is the case the body says is unchanged.

Claude measured it on a c7i.4xlarge with a release (fat LTO) build: base f42ea3784 vs this head, 20,000 subjects with ex:name, a plain ("reasoning": "none") ?s ex:name ?n under a required f:onClass ex:Secret deny with default-allow: true, median of 5 interleaved rounds × 15 reps:

storage other 90% of subjects base ms head ms Δ
novelty-only untyped 92.1 118.7 +28.9%
indexed untyped 26.8 38.5 +44.0%
indexed ex:Person 39.1 44.3 +13.3%
novelty-only ex:Person 158.8 161.8 +1.9% (noise)

The controls in the same run (no policy, and a property-only policy) moved between −3.4% and +1.1%. (The untyped rows return 0 rows on both sides; the filter still evaluates every flake.)

Since the enforcer now owns population, the callers' prefetches are just redundant. Claude deleted the scan's (the eight lines at binary_scan.rs:1142-1150, keeping the db it builds) on this head, and every row came back within noise on a dev-fast build: novelty-only untyped +25.1% → +0.4%, indexed untyped +38.2% → +1.4%, indexed ex:Person +9.9% → +4.0% (run spread about 3%), with all nine contract tests still passing. The other batch callers (hydration.rs, block_fetch.rs, cypher_typed.rs, graph_commit_builder.rs) are the same deletion. stage.rs:2699 is the exception: it feeds the single-flake allow_flake_for_graph, so its batch prefetch is worth keeping, and that's the one place caching an empty lookup pays, since otherwise each untyped retraction re-reads its rdf:type one subject at a time. For what it's worth, next's 20196e8b0 takes the empty-lookup route everywhere, and on this probe that's worse for a scan: with the prefetch also gone, the indexed untyped row stayed at +19.3%, presumably because a scan sees each subject once and the empty entries are pure inserts. Commenting here because binary_scan.rs is not in this diff.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 15fcaad

Comment thread docs/query/reasoning.md
- The two approaches can therefore answer the same query differently under the same policy. With `ex:ssn rdfs:subPropertyOf ex:identifier` and `ex:ssn` hidden, a query for `ex:identifier` returns nothing under `"rdfs"`, because the rewritten query scans the hidden `ex:ssn`. Under `"owl2rl"` it returns the value, because the derived `ex:identifier` fact is itself viewable.

**If you run reasoning under a non-root policy, your policy must cover the derived properties and classes** — deny them, or use `default-allow: false` so anything not explicitly allowed (including reasoning-introduced predicates) stays hidden.
**If you run reasoning under a non-root policy, your policy must cover the derived properties and classes** — deny them, or use `default-allow: false` so anything not explicitly allowed (including reasoning-introduced predicates) stays hidden. Under OWL 2 RL and datalog, an `f:onClass` policy applies by the classes the query reasons to: denying a derived class hides every fact of its members, including asserted ones, and every derived fact of an asserted member. A graph crawl (`select {"?s": ["*"]}`) does not reason yet, and judges class policies on stored classes only.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking (docs for an access change).

This ports the deny half of D5's contract to main's docs, but not the grant half or the plain-query escape, which are the two consequences we ratified for #2292.

With this PR, a reasoning query selects f:onClass policies by the subject's reasoned classes on every property (types.rs:382-403, runner.rs:989). That closes the deny leak, and it also widens an allow: under default-allow: false, a subject a stored rule places in an allowed class now gets all of its properties shown, not only the ones class statistics list for that class. Meanwhile a query that doesn't reason is still judged on stored classes, so a deny on a derived class doesn't reach a caller who sends "reasoning": "none".

next says both plainly (docs/query/reasoning.md, "Policy reads what the query reads", and the class-membership paragraph at the end of docs/security/policy-in-queries.md §Reasoning). On main after this PR, an admin learns that a derived-class deny now works, but not that data a rule reads is now security data, or that f:reasoningDefaults with f:overrideControl f:OverrideNone is how to make that deny unavoidable (both exist on main: docs/ledger-config/override-control.md:22).

next's paragraph minus the reasoning-index links should cover it:

**Policy reads what the query reads.** In a reasoning query, class policies and `f:query` conditions see derived facts; a query without reasoning is judged on stored facts. Two consequences follow:

- Data a rule or axiom reads is security data. A derived fact can grant access as well as deny it: a rule can place a subject in a class an `f:onClass` policy allows, or satisfy an `f:query` condition, so whoever can write a rule's inputs can open access through it.
- A caller who does not ask for reasoning is judged on stored facts, so a deny on a derived class does not reach their plain queries. Where that matters, set the ledger's reasoning defaults (`f:reasoningDefaults`) with `f:overrideControl` `f:OverrideNone`, so a query cannot turn reasoning off; see [Override control](../ledger-config/override-control.md).

…plus the one-paragraph equivalent at the end of docs/security/policy-in-queries.md §Reasoning (:95-108). Commenting here because docs/security/policy-in-queries.md is not in this diff.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 623eaa0

Comment thread fluree-db-policy/src/types.rs Outdated
) -> Self {
Self {
inner: Arc::new(PolicyWrapperInner {
reasoned_view: view.selecting_classes_by_subject(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional (performance, per query).

This is more of a suggestion than a must. reasoned_view is built eagerly in PolicyWrapper::new, and the policy builder builds a wrapper per governed query, so every query whose policy has an f:onClass restriction clones the whole view set (restrictions, by_property, by_subject) whether or not it reasons. It's per query, not per flake, so I don't think it shows up next to stats assembly, but it's new work for exactly the queries the body says are unchanged. A OnceLock fills it on first use and keeps plain queries at zero:

reasoned_view: std::sync::OnceLock<Option<PolicySet>>,
// …
pub fn reasoned_view(&self) -> &PolicySet {
    self.inner
        .reasoned_view
        .get_or_init(|| self.inner.view.selecting_classes_by_subject())
        .as_ref()
        .unwrap_or(&self.inner.view)
}

Minor and non-blocking, but if you agree it's right, I'd rather see it folded in now than lost in the backlog.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in c1e2a78

pub fn new(g_id: GraphId, overlay: &dyn OverlayProvider, t: i64) -> Self {
let overlay = match overlay.content_version() {
Some(version) => OverlayState::Version(version),
None => OverlayState::Unshared(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional (memory).

Giving an overlay with no content version a fresh Unshared id each time is the right call for correctness. The side effect is that a caller's prefetch (populate_class_cache_for_graph → ClassState::of(db), class_lookup.rs:101-113) writes entries under an id nobody reads, and each filter_flakes_for_graph call adds another set under its own id. On such an overlay, every subject is looked up twice and the shared cache grows by each batch's subjects for the life of the policy context. Deleting the prefetches (the blocking comment on enforcer.rs:130) removes the first half; the growth stays. As far as Claude could find, no in-tree query passes one today (GraphDb::from_historical hands the novelty itself to the query), but the public PolicyWrappedView::from_historical (fluree-db-api/src/policy_view.rs:118) uses HistoricalLedgerView as the overlay, which has no content_version, and an embedder's own overlay may not either. The enforcer could resolve an Unshared state into a local map for the call instead of the shared cache (and populate_class_cache could return early for one, for any prefetch that stays). Minor, but if you agree I'd rather see it in this PR than tracked-and-forgotten.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in e4205e1

}

#[tokio::test]
async fn a_class_policy_covers_what_owl2rl_derives_for_its_members() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional (testing).

The new tests all pin the deny side (a required deny, or a required f:query condition). D5's other half, that a rule can grant, has no test, and it's the half most likely to surprise an admin later. Something like a stored rule that types ex:alice as ex:Visible (with no asserted ex:Visible member, so statistics list nothing for the class), an f:onClass ex:Visible allow under default-allow: false, and two assertions: a datalog query shows alice's asserted salary, and the same query with "reasoning": "none" shows nothing. Minor, but it puts the decision on the record in code; if you agree, I'd rather see it here than in the backlog.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in f56a51c

Comment thread fluree-db-policy/src/types.rs Outdated
}

/// Collect the deduplicated class-bucket restriction indices for a
/// subject's classes, in insertion order. Empty unless this is a modify

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit. "Empty unless this is a modify set with f:onClass policies" is now also non-empty for the reasoned view set, and the struct comment at :326-327 ("View-set class policies are indexed INTO by_property") is now true only for the stats-based set. So minor, but cheap to fix while you're here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in e715094

The enforcer resolves the classes of a batch's subjects under the state it
reads with, so the scan, hydration, block fetch, Cypher and commit-detail
callers' prefetches did the same work a second time: each batch collected,
sorted and deduplicated its subjects twice and took the cache lock twice.
A subject with no rdf:type is never cached, so its type was read twice per
batch. This ran for every non-root query under an f:onClass policy,
reasoning or not.

Those prefetches are gone. The enforcer's own lookup skips schema flakes'
subjects, as hydration's prefetch did, since a schema flake is allowed
without a class check.

Staging keeps its prefetch: it feeds single-flake checks that otherwise look
up one subject at a time. The explicit prefetch now caches an empty entry for
an untyped subject, so each of those checks finds it. The batch lookup still
caches only what it finds: a filter meets most subjects once, and an entry
for an untyped one would be an insert nobody reads.
A reasoning query judges class policies and f:query conditions on derived
facts, and a plain query on stored ones. The docs said only that a derived
class deny now applies. They now also say that a derived fact can grant
access as well (a rule can place a subject in a class a policy allows), so
data a rule reads is security data, and that a caller who skips reasoning is
judged on stored facts, which f:reasoningDefaults with f:OverrideNone closes.
PolicyWrapper::new derived the reasoned view set eagerly, so every query
under an f:onClass policy cloned its whole view set (restrictions and both
indexes) whether it reasoned or not, and a policy context is built per
governed query. The set is now built on first read, which only a reasoning
query makes.
… shared cache

An overlay with no content version takes a fresh class state each time, so
nothing reads an entry cached under it again. The enforcer still cached its
lookups for such an overlay in the policy context's shared cache, which grew
by each batch's subjects for the life of the context. The public
PolicyWrappedView::from_historical builds a view over such an overlay, and
an embedder's own overlay may have no content version either.

The enforcer now resolves those classes into a map that lives for the call,
and the explicit prefetch returns early for such an overlay, since no check
could take the state it would cache under. Overlays with a content version
use the shared cache as before.
…soning query

Under default-allow: false, an f:onClass allow reaches a subject that is a
member only by stored rule, on its asserted facts, in a reasoning query;
a plain query judges stored classes and grants nothing. The contract tests
pinned only the deny side.
…class too

The PolicySet comments said class-keyed selection (by_class) was for modify
sets only, and that a view set's class policies always sit in by_property.
A reasoning query's view set now takes the by_class route as well.
@bplatz

bplatz commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Before merging 1: drop the batch callers' prefetches now the enforcer populates.

Addressed in 15fcaad

Before merging 2: port next's "Policy reads what the query reads", here and in policy-in-queries.md.

Addressed in 623eaa0

I'd like your confirmation that main is the intended line.

Yes, intended. Policy is judged on what the query reads: stored facts for a plain or rewriting (RDFS, OWL 2 QL) query, derived facts for a materializing one. A policy can be written to cover both. The grant half is pinned in f56a51c.

@bplatz

bplatz commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Unlike next, a crawl here still renders and judges stored classes; I'd like confirmation that it's deliberate.

Deliberate for main. It's documented in docs/query/reasoning.md, and the fix (rendering through the query's reasoned state, with multi-graph crawls refused) comes with next under #2287.

…y property

A view set indexes an f:onClass policy under the properties class
statistics list for its classes, and skipped the class check on a property
statistics credit to the target classes alone. Statistics count typed
subjects only, so an untyped subject carrying such a property was no
counterexample: under default-allow false an f:onClass allow showed its
values, and under default-allow true a deny hid them though it is no
member. Every class policy entry now checks the subject's classes, as the
modify set and a reasoning query's view set already do.

The enforcer resolves a batch's classes whenever a class policy exists, so
the check costs a set lookup per flake. Cypher's and GraphQL's schema
pruning no longer drops a property for an f:onClass deny: the deny hides
only its members' facts, and the rows are judged per subject.
@bplatz
bplatz merged commit 4c160a8 into main Nov 18, 2026
21 checks passed
@bplatz
bplatz deleted the fix/class-policy-reasoned-classes branch November 18, 2026 03:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants