Repository navigation
fix(api): key cross-ledger governance by the model ledger's head commit - #2052
Conversation
The governance cache keyed resolved policies, shapes, rules and schema by (kind, model ledger, graph, t), relying on new commits to produce new keys. `t` is not a model ledger's identity: one dropped and created again under its name restarts at t 1, so after the same number of commits it landed on a key the dropped ledger had filled, and every data ledger it governs was served the dropped ledger's artifacts until the server restarted. A model whose new policies deny what the old ones allowed kept allowing it. The key now carries the model's head commit id beside its t. The per-request pin (`ResolveCtx::resolved_heads`, carried across `wrap_policy` and `query` on the view) holds the two together, so a later stage that opens the model at the pinned t keys under the same commit rather than a newer one. The compiled-SHACL cache on the data ledger had the same blind spot: it is keyed by the shapes wire's origin and checked before translation, so a recreated model at the same t reused the shapes compiled from the dropped one. `WireOrigin` (both the API and policy crates' copies) now carries the commit id, and the compile cache keys on it.
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz the head commit is the right identity for M, and I like that it's exactly right even in the corner where a recreate reproduces the same commit: an equal content address means an equal chain, so serving the cached artifact there is correct, not a collision. My one reservation is where the identity stops. The key names the commit, but the materializers still open M by t through the cached-handle fast path in load_graph_db_at_t, so a second instance that cached the dropped M fills the new key with the dropped M's policies (I reproduced it with two instances over one store; details below).
That fast path is also a third instance of the class #1980's review is chasing, t used as if it named the ledger: this PR fixes two (the governance cache and the compiled-SHACL cache), and refresh's min_t fast path, the GraphQL shape cache and #1962's list are the rest. I think the point fix for the fast path belongs here, since it's this PR's bug on another host and the materializers already hold the ModelHead, and the sweep belongs with #1962. Landing this ahead of #1980 still looks right to me.
Full review below:
✅ Approving to unblock you — with 1 thing that needs to be addressed before this merges.
This is a clean fix, @bplatz, and the mutation claims in the body hold: with commit_id: None in the resolver all three new tests fail, and with it dropped from CachedShapeSource only the shapes test does. In one process it fixes both caches, in both directions and for every artifact kind: all five materializers stamp the commit into WireOrigin and share one ResolutionKey, datalog rules are content-hashed in the reasoning cache anyway, and the cross-ledger schema closure is re-translated per request. It also costs nothing extra: resolve_graph_ref already looks M up in the nameservice on every call (resolver.rs:117) to check retracted, and the commit id comes from that same record.
Must address before merge:
fluree-db-api/src/cross_ledger/policy_materializer.rs:87(and the same line in the other four materializers): open M at the key's commit, not only itst.load_graph_db_at_t(view/fluree_ext.rs:345-355) returns the cached handle on a matchingt, so a second instance that cached the dropped M stores the dropped M's policies under the new M's key. Reproduced with two instances over one store; the fix is one head-commit comparison inopen_model_db. Details inline.
Also worth folding in:
- The flipped test direction (allow, then a stricter recreate), inline.
- The rebase case in the body ("
publish_commitignores a head that doesn't advancet… to be filed on its own"): I agree it's separate (a different subsystem and a CAS-semantics call), but I couldn't find an issue for it yet, so filing and linking it before this merges keeps it from depending on anyone's memory.
Adherence to repo commitments:
- Patterns/abstractions: ✔ extends the existing key and origin types (
ResolutionKey, bothWireOrigins) instead of adding an invalidation channel. - Performance (speed first, memory second): ✔ no performance-degradation risk: no new I/O, one inline
ContentIdin the key hash per resolution (per request, not per row); the proposed fix adds one comparison. - Deployment targets: 🔴 the change is in
fluree-db-api(embedded in solo's Lambdas and the standalone binary, and in the server), the evidence is single-instance, and the multi-process fence (an in-process cache coordinates nothing across instances) is exactly where it still fails; reproduced with two instances over one store. - Testing: ✔ three new tests, wired (
grp_policy,grp_graphsourcetwice), passing and red under the body's mutations; the shapes test needsshacl, which CI's--all-featurescovers.⚠️ no two-instance case. - Conventions: ✔ multi-line commit body;
docs/design/cross-ledger-model-enforcement.mdanddocs/security/cross-ledger-policy.mdupdated.
Verified locally at d635e96de: the cross-ledger tests in grp_policy, grp_graphsource (with --features shacl) and grp_reasoning, the body's two mutations (restored), a one-process flipped-direction probe, and a two-instance probe with and without the historical loader in open_model_db.
Approving now so you can merge without waiting on another pass from me. Just be sure the open_model_db check is in before you do.
| head: &ModelHead, | ||
| ctx: &ResolveCtx<'_>, | ||
| ) -> Result<PolicyArtifactWire, CrossLedgerError> { | ||
| let resolved_t = head.t; |
There was a problem hiding this comment.
🔴 Must address before merge: the key now names M's head commit, but every materializer still opens M by t alone, through a fast path that returns whatever ledger the cache holds at that t (fluree-db-api/src/view/fluree_ext.rs:345-355). A second instance that cached the dropped M fills the new M's key with the dropped M's artifact.
This line (and its twin in the other four materializers) hands head.t to ctx.open_model_db (cross_ledger/types.rs:634-658), which goes to load_graph_db_at_t. That takes self.ledger_cached(M) and returns its snapshot whenever target_t == snap.t, without comparing the snapshot's head commit to the one the key was built from. In one process that's fine, because the drop clears the ledger cache, which is why the new tests pass. Across instances that share storage and the nameservice but not memory (two Lambdas, or two servers over S3 and a DynamoDB nameservice), nothing clears the other instance's handle.
I ran it with a scratch test: two FlureeBuilder::file(dir) instances over one directory, A and B. A creates M allowing users and D governed by M; B queries D and gets ["ex:alice"]. A drops M and recreates it denying users, at the same t (head commit …cfn754… → …p2xk6d…, and B's nameservice lookup sees the new one). A now answers []. B still answers ["ex:alice"]: its resolver keys under the new head (a miss, as intended) and then fills the miss from its cached handle of the dropped M. With load_graph_db_historical in place of load_graph_db_at_t in open_model_db, B answers []. The compiled-SHACL cache inherits the same content, since its key comes from the wire's origin. B was stale before this PR too, so this isn't a regression; it's that the fix doesn't yet reach the deployment shape where a drop on one node and enforcement on another is the normal case.
The narrow fix: pass the &ModelHead the materializers already hold into open_model_db instead of head.t, and accept the cached snapshot only when its head commit equals head.commit_id, falling back to load_graph_db_historical (or a refresh) otherwise. That's one comparison on the hit path, it ties the content to the key, and a two-instance version of recreated_model_ledger_policies_replace_the_dropped_ones would pin it.
Commenting here because types.rs:634-658 and fluree_ext.rs are not in this diff.
There was a problem hiding this comment.
Fixed in 86828b4. open_model_db now takes the &ModelHead, and a new Fluree::load_graph_db_at_commit serves the cached handle only when both its t and its head commit match, falling back to load_graph_db_historical otherwise. load_graph_db_at_t keeps its t-only fast path for time-travel queries. The two self-reference branches (the caller's data_state and the uncached load) check the commit too.
There was a sixth caller with the same gap: open_cross_ledger_shapes_model in tx.rs opens M by t for the sh:class value-set probe, after the shapes wire is resolved. ResolvedGraph now carries commit_id, so the probe opens M at the same head. Every staging and validate path goes through that function.
The tests run two instances over one MemoryStorage and one MemoryNameService (support::instances_sharing_storage()), each with its own ledger cache. That stands in for servers sharing S3 and DynamoDB; two processes on one file directory isn't a supported deployment.
model_ledger_recreated_by_another_instance_replaces_the_dropped_policies: your repro, allow → deny. The reader must answer[].sh_class_membership_follows_a_model_recreated_by_another_instance: the recreated M no longer lists a value-set member. The reader's write must be rejected.
Restoring the t-only fast path in open_model_db fails both; reverting only the tx.rs open fails only the sh:class one. The design and security docs now say the artifact is read at the key's commit.
The rebase case from the body is filed as #2111 and linked there.
| let model = genesis_ledger(&fluree, model_id); | ||
| fluree | ||
| .stage_owned(model) | ||
| .upsert_turtle(&seed_model(false)) |
There was a problem hiding this comment.
🟡 Optional: the new end-to-end tests pin the direction that over-denies, not the one that over-allows.
Both go strict → permissive (here M denies and the recreated M allows; in the shapes test a shape rejects and the recreated one is deactivated), so a regression would show up as a wrong denial. The failure that matters for security is the reverse: a cached permissive artifact still enforced after M was recreated stricter. The key is symmetric, so it holds today (I ran the flipped version in one process: M allows, the recreated M denies, D answers []), but flipping this test, or adding the flipped twin, pins the fail-open direction. I recognize this is minor, but if you agree it's right I'd rather see it in this PR than lost in the backlog.
There was a problem hiding this comment.
Agreed, both directions are pinned now. For policy, the new two-instance test (model_ledger_recreated_by_another_instance_replaces_the_dropped_policies) goes allow → deny, and it fails with no commit id captured in the resolver.
For the compiled-SHACL cache, ac289c7 adds recreated_model_ledger_shapes_reject_what_the_cached_compile_passed: a deactivated shape lets a nameless Person through and is compiled and cached, M is recreated at the same t with the shape active, and the same write must be rejected. It fails with the commit id dropped from CachedShapeSource.
The governance cache keys an artifact by the model ledger's head commit, but every materializer still opened the model by t, through a fast path that returns the cached handle whenever its t matches. An instance sharing storage and the nameservice with the one that dropped and recreated the model still held a handle of the dropped ledger at that t, and filled the new model's key with the dropped one's policies, shapes, rules, constraints or schema. The sh:class value-set probe read the model the same way. `open_model_db` now takes the `ModelHead`. The cached handle, or the data ledger's own state when the model is the data ledger, serves it only when its head is that commit; otherwise the model is loaded through the historical loader, which reads the nameservice. `ResolvedGraph` carries the commit id, so the value-set probe opens the model at the same head. Tests run two instances over one storage and nameservice: the reader caches a model that allows users, the writer drops it and recreates it denying them at the same t, and the reader must deny them; likewise for an sh:class member the recreated model no longer lists.
… compile passed The recreate tests went from a strict model to a permissive one, so a regression in the compiled-SHACL cache key would show up as a wrong rejection. This one pins the direction that fails open: a deactivated shape lets a nameless Person through and is compiled and cached, then the model is dropped and recreated at the same t with the shape active, and the same write must be rejected. The data ledger's shapes-source config is now one helper, shared by the person-shape seed and the two-instance sh:class test.
Conflict resolutions: - Cross-ledger governance: the cache key keeps both protections, main's model head (t and commit, #2052) inside next's instance-scoped key (#1980); docs describe both. - Numeric threshold fast paths: `threshold_key_interval` keeps main's interval and NaN semantics and covers next's order-preserving families (all inline integer subtypes, double and float, inline decimals) through `encode_numeric_threshold_for_otype`, which is infallible now that every double has a key. The overlay count and the star top-k dispatch rows by family on those intervals. - `rdf_term_equal` keeps next's triple-term equality; main's NaN handling replaces the early NaN return. Bound-object encoding keeps next's triple-term arm and main's every-double key. Main's new tests adapted to next's lifecycle APIs: `genesis_ledger` is awaited, ledgers once named as branches of one name (`mq:users`, `special-doubles:write`, ...) are separate ledgers (`mq-users:main`), and helpers read the content store by storage namespace and publish fenced. The recreated-model-ledger tests are main's, which also cover two instances sharing storage; next's same-scenario copies are dropped.
Brings in #2019, #2044, #2048, #2049 and #2052 (main at 58b5323). #2052 keys cross-ledger governance by the model ledger's head commit and opens the model at that commit. Two files conflicted: - tx.rs: this branch moved the stored-shapes pass into its own block (`stored_cache`), which #2052 edited in its old place. The block keeps this branch's shape, and its compiled-SHACL cache key carries #2052's commit id beside the model's t, as main's does. The shapes model opener and the cache key type merged without conflict. - it_policy_cross_ledger.rs: both sides appended tests; both are kept.
A multi-operation request is governed by the state before it: each operation reads the config, the shapes and the uniqueness constraints from the ledger as the request found it. A cross-ledger model ledger was the exception: each operation resolved its own context, so one that ran after the model committed read the model's newer head. #2052 pins a model's head (its `t` and commit) within one resolution context; the request now carries those pins across its operations, so every operation reads a model ledger at the head the request's first lookup of it found, and a model that is the data ledger itself from the state before the request. A `Transaction` staged again from its own base (after a failed operation, or to roll back to a savepoint) keeps them; staged again over a newer head, it is governed as that head is. The SPARQL, Rust API and compatibility pages say so. Test: a_transaction_reads_a_model_ledger_at_one_head (a shape the model activates while a transaction is open, before and after a rollback, and in a transaction begun after it).
…2068) into fix/write-fidelity-part2 Two conflicts, both with #2056, which fixed the same debug assertion this branch fixed in 9b7cc1a (the resolver's reserved-namespace guard rejected f:message, f:author and f:reverts in txn-meta): - fluree-db-indexer/src/run_index/resolve/resolver.rs: took main's version, the guard deciding through fluree_vocab::txn_meta::may_hold. This branch's widened is_system_txn_meta_entry admitted the same five names and goes; the file now equals main's. - fluree-db-api/tests/it_txn_meta.rs: kept both sides' tests, this branch's an_index_build_keeps_the_user_message_and_author (a file ledger through a full rebuild) beside #2056's. template_sink.rs, trig_meta.rs, txn_meta.rs, admin.rs and fluree-vocab merged cleanly: #2056's predicate check in the txn-meta path sits beside this branch's statement hashing and does not touch it.
Problem
A model ledger dropped and created again under its name kept enforcing its predecessor's policies and shapes on every data ledger it governs, until the server restarted. No error: a new model whose policies deny what the old ones allowed kept allowing it.
The governance cache keys resolved artifacts by
(kind, model ledger, graph, t). A recreated ledger restarts att1, so after the same number of commits it lands on a key the dropped ledger already filled. Dropping a ledger already clears its cached ledger state; the governance cache was the only stale layer.The compiled-SHACL cache on the data ledger has the same blind spot. It is keyed by the shapes wire's origin
(model, graph, t)and checked before translation, so even with a fresh wire, a recreated model at the sametreused the shapes compiled from the dropped one.Across instances that share storage and the nameservice, a correct key is not enough. The materializers opened the model by
t, through a fast path that returns the cached ledger handle whenever itstmatches. An instance that cached the dropped model, and whose cache the drop on another instance never cleared, filled the new model's key with the dropped model's artifacts. Thesh:classvalue-set probe read the model the same way.Change
ModelHead { t, commit_id }replaces the baretin the resolution key. The commit id comes from the nameservice record the resolver already reads, so there is no extra I/O.ResolveCtx::resolved_heads(andGraphDb::cross_ledger_resolved_heads, carried fromwrap_policytoquery) pinstand commit together, so a later stage opening the model at the pinnedtkeys under the same commit rather than a newer one.WireOrigincarries the commit id (the API and policy crates' copies), and the compiled-SHACL cache keys on it.open_model_dbtakes theModelHead; the cached handle (or the data ledger's own state, when the model is the data ledger) serves it only when its head is that commit, and otherwise the model is loaded through the historical loader, which reads the nameservice.ResolvedGraphcarries the commit id, so thesh:classvalue-set probe opens the model at the same head.(kind, ledger, graph, t); its public type is unchanged.Cost is negligible: a
ContentIdis 96 bytes inline, no allocation; one extra hash per resolution, and the 4,096-entry cache grows by at most ~384 KB. Opening at the commit adds one comparison, and only on a governance-cache miss. Hit rate is unchanged in steady state, sincetand head commit move together on every commit.Tests
recreated_model_ledger_policies_replace_the_dropped_ones(it_policy_cross_ledger): end to end throughdb_with_policy. M denies users; M is dropped and recreated allowing them at the samet; the query must return them.recreated_model_ledger_is_not_served_the_dropped_ones_artifact(it_cross_ledger_resolver): the resolver returns a fresh artifact, not the dropped M's cachedArc.recreated_model_ledger_shapes_replace_the_cached_compile(it_shapes_cross_ledger): a write rejected by M's shape (compiled and cached), then M recreated at the sametwith the shape deactivated; the same write must pass.recreated_model_ledger_shapes_reject_what_the_cached_compile_passed(it_shapes_cross_ledger): the reverse, which fails open if the key regresses. A deactivated shape lets a write through and is compiled and cached; M is recreated at the sametwith the shape active; the same write must be rejected.model_ledger_recreated_by_another_instance_replaces_the_dropped_policies(it_policy_cross_ledger): two instances over one storage and nameservice. The reader caches an M that allows users; the writer drops M and recreates it denying them at the samet; the reader must deny them.sh_class_membership_follows_a_model_recreated_by_another_instance(it_shapes_cross_ledger): the same setup, with the recreated M no longer listing ansh:classmember; the reader's write must be rejected.Mutation checks:
talone inopen_model_dbfails both two-instance tests; doing so only for the value-set probe fails only thesh:classone.Related
Partially addresses #1962 (caches keyed by ledger id and
tthat collide on drop/recreate). This one was not on its list.Follow-up: #2111
#1980, merged into
next, keys the same cache by the model ledger's instance, butnextstill opens the model byt, so the open-at-commit change here is needed there too. It arrives with the next merge ofmainintonext, which conflicts with #1980 in the cache key,tx.rs, the two cross-ledger docs and the two test files. With the commit id in the key, the instance in it is redundant.This also keys correctly a branch whose head returns to an earlier
twith other commits, as aSkiprebase can produce. That case isn't pinned here: today such a rebase never moves the branch's head at all, becausepublish_commitignores a head that doesn't advancet. That is #2111.