Skip to content

Python reference worker for custom reasoning stages - #2127

Merged
bplatz merged 7 commits into
mainfrom
feat/datalog-reference-worker
Oct 20, 2026
Merged

bplatz merged 7 commits into
mainfrom
feat/datalog-reference-worker

Conversation

@bplatz

@bplatz bplatz commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

An example of a custom reasoning stage that runs in Python next to a ledger, using only the fluree package's ordinary query and transaction calls: fluree-db-python/examples/reference_worker, with a guide at docs/guides/custom-stages-python.md.

Some steps in a reasoning program are not rules: a model reads documents, or a versioned decision procedure weighs evidence. The pattern is to run such a step outside the engine and publish its complete result into a named graph it owns, which queries, datalog rules and later steps then read like any other data.

The example

A claims review in two stages:

  • extract runs a model over each document's text and publishes the vendor and amount. Each extraction records the model and a hash of the text, and a later run reuses it while both match, so the model runs only on new or changed text.
  • gate decides each case from the documents that had arrived by the evaluation time, their extractions and reference data: flagged with reasons, cleared, or indeterminate with the evidence that is missing. Gate v1 applies the threshold per document and v2 to the case total. The gate never calls the model, so a new gate version replays over the same pinned inputs.

Every run:

  • reads all its inputs from one pinned snapshot and evaluates at the manifest's clock, never the wall clock;
  • replaces the whole contents of the graph it owns in one transaction, which nets to the difference, together with a generation record: the input ledger and t, the evaluation time, the program, code, engine and gate versions, the model, and a hash and count of the output. The record keeps an empty result's graph in existence;
  • publishes nothing if it fails, leaving the previous generation in place;
  • publishes as a compare-and-swap on the generation number, so a run that finds a newer generation than it started from refuses.

Missing text, a missing extraction, fewer documents than a case expects, or evidence that is ambiguous (a document with two texts or two received times) or partial (an extraction with a vendor and no amount, or the reverse) makes a case indeterminate, never cleared. The manifest format is experimental.

The package does not connect to a running fluree server yet, so the guide describes how workers in several processes share a server over the HTTP API, publishing with one guarded update.

Tests

fluree-db-python/tests/test_reference_worker.py, against the example's data: each case's outcome and the generation record; a new gate version replays without the model and the earlier generation stays readable; retained extractions are reused until the text changes, and an unchanged rerun touches only the generation record; unavailable evidence is never a clearance; a document with two texts or received times, or a case with two expected counts, is undecided, and neither text is extracted; a partial extraction is undecided; the toy model gives no answer for an invoice it cannot read; the clock decides which documents had arrived; failed extract and gate runs leave the previous generation; an empty result still publishes a generation; a stale run refuses, and so does a run another publication overtakes between its generation read and its commit; a stored datalog rule reads the published graph; the command line runs the example manifest after the README's setup step, which the guide shows too; bad manifests are rejected.

Each was confirmed to fail with the worker code it pins broken: no compare-and-swap, the compare-and-swap read made outside the transaction, no missing-extraction gap, rows counted as documents, a partial extraction read as complete, the pin ignored, output churned on every run, the clock ignored, and the setup step passing the data file's name as a string.

@bplatz bplatz added documentation Improvements or additions to documentation area:datalog Reasoner, rules, reasoningDefaults labels Oct 15, 2026
@bplatz
bplatz requested a review from a team October 15, 2026 11:38
@bplatz
bplatz added this pull request to stack #2128 October 15, 2026 11:39
@bplatz
bplatz force-pushed the feat/datalog-reference-worker branch 3 times, most recently from 4dd9496 to a5d1257 Compare October 15, 2026 13:07
@bplatz
bplatz force-pushed the feat/datalog-reference-worker branch 2 times, most recently from 6c46696 to f57cd41 Compare October 15, 2026 21:25

@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 yes to the pattern here: a stage that owns one graph, replaces it in one commit next to its generation record, and guards the write with a read inside the transaction is the shape I'd want people to copy, and publish() held up under everything I threw at it. Two notes at a higher altitude than the review below.

The Python path and the HTTP path publish differently. publish() stages the delete and the insert as two operations, so unchanged facts net to nothing, while the guide's single guarded DELETE … INSERT … WHERE re-asserts every unchanged result each generation. Ledger.sync (and POST /sync) already mean "make this graph hold exactly this". I wonder if a sync that takes a precondition (or a Transaction.sync) would make both paths one primitive and shrink publish() to the generation read plus one call. More a question than a recommendation, and not for this PR.

Also not this PR, but the HTTP pattern sits next to a defect class we keep meeting: netting by counting cancelling pairs gets set semantics wrong. The guide's shape is on the safe side (its constant INSERT outnumbers the retract), which is why it only shows up here as re-asserts, and #2129 tracks that direction. The opposite direction loses a fact, and #2129 doesn't mention it: the update accumulator (fluree-db-transact/src/generate/accumulator.rs) keeps whichever of retract and assert a fact was produced more often, so a DELETE … INSERT … WHERE that deletes a triple on more solutions than it re-inserts it retracts it, where SPARQL Update says it stays. The set-semantics cancellation #2129 proposes would fix both, so this case may be worth adding there as its test. Same class as #1818, #2022, and the equal-t tie that #2120 fixed before it merged:

DELETE { ex:r1 ex:p "v" } INSERT { ?keep ex:p "v" } WHERE { VALUES (?x ?keep) { (1 ex:r1) (2 UNDEF) (3 UNDEF) } } retracts ex:r1 ex:p "v", in the default graph or a named one (run at this head; the accumulator is unchanged from main).

Full review below:


✅ Approving to unblock you — with 2 things that need to be addressed before this merges.

@bplatz this is a really nice example, and its core holds up: I couldn't break publish()'s netting or its compare-and-swap, the clock and the pin are honored everywhere I looked, and a failed run leaves the previous generation in place. What I could break is the evidence side of the gate, which is the guarantee the guide leads with, and the setup step.

Must address before merge:

  1. fluree-db-python/examples/reference_worker/worker.py:148 — a document with two texts counts as two documents, so case4 (one of its two documents) goes cleared, and the two texts' extractions merge into one node that pairs one text's vendor with the other's amount. Group the rows by document, count distinct documents, and make a multi-valued text or received time a gap.
  2. docs/guides/custom-stages-python.md:86 (and the example's README.md:17) — insert("claims.ttl") reads the string as Turtle and raises a parse error; pass a Path.

Should address:

  • fluree-db-python/tests/test_reference_worker.py:225 — the race test stays green with the compare-and-swap read moved out of the transaction; inject the competing publication between that read and the commit.
  • worker.py:243 — a partial extraction clears a case: a missing vendor passes the approved-vendor check and a missing amount counts as zero, and the toy model returns {} for any text its regex misses.

Optional: the first publication's FILTER NOT EXISTS guard needs its own example (custom-stages-python.md:153), and a sentence that the HTTP update re-asserts unchanged results (:134).

Adherence to repo commitments:

  • Patterns/abstractions: ✔ built only on the package's public transact/query/at; ⚠️ Ledger.sync already means "make this graph hold exactly this" (see the note above).
  • Performance (speed first, memory second): ✔ no engine code changes; a publication scans the stage's graph once and commits only the difference (verified). No performance-degradation risk.
  • Deployment targets: ✔ the worker runs on the embedded engine, and CI's python job ran the new tests on Linux, macOS and Windows under Python 3.10 and 3.14. The server-over-HTTP section is prose: I checked its endpoint and time-pin syntax against docs/api/endpoints.md and ran its guarded update through the engine's update path (4 threads × 30 rounds, one winner each), not against a running server.
  • Testing: ⚠️ 12 tests, all run in CI and here; the race test doesn't pin the in-transaction read, and nothing covers multi-valued evidence, partial extractions or the documented setup line.
  • Conventions: ✔ multi-line conventional commit, no AI attribution; the guide is linked from SUMMARY.md, the guides index and the datalog page, mdbook build is clean and the page's links resolve. The sample domain and names are generic.

Verified locally at branch HEAD (f57cd415f): built the package with maturin (debug) and ran pytest tests/test_reference_worker.py (12 passed); probed netting over eight generations, the compare-and-swap (a race after the read, and 4 threads × 20 rounds of run_gate), stale, multi-valued and partial evidence, the docs' setup line and the guide's guarded update; moved the CAS read out of the transaction, saw the PR's tests stay green and a race-after-read probe publish over the winner, and restored it.

Approving now so you can merge without waiting on another pass from me — just be sure the two musts are in before you do.

expected[case] = count
found = docs.setdefault(case, [])
if doc is not None:
found.append(Document(doc, received, text))

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.

🔴 Must address before merge — a document with two texts counts as two documents, so a case that is missing a document can be cleared, and the two texts' extractions mix their vendor and amount.

cases() appends one Document per result row, and the query returns a row per ex:text × ex:receivedAt value. Nothing keeps those single-valued: an insert of a corrected text adds a second value, and test_a_failed_run_leaves_the_previous_generation does exactly that to ex:doc6a (test_reference_worker.py:175). gaps() then counts rows against expectedDocuments (:198), and run_extract names the extraction node by document and model only (:332), so both texts land on one subject with two textHash, two vendor and two amount values, which retained_extractions reads back as a cross product where the last row wins.

I ran both against the example data at this head. INSERT DATA { ex:doc4a ex:text "Invoice from Acme for 20.00" } (case4 expects two documents and has only doc4a) makes case4 cleared, not indeterminate. Giving doc3a a second text, "Invoice from Acme for 5000.00", makes both of doc3a's retained extractions read {vendor: Initech, amount: 5000.00}, a pair neither text states, and the gate flags the case on it. (expected[case] = count at :145 has the same last-row-wins shape for a case with two expectedDocuments.)

Fix: group the rows by document, count distinct documents against expectedDocuments, and make a document with more than one text or received time a gap (e.g. ambiguous-text:<doc>) rather than two documents, the same refusal reference_data() already makes for the threshold at :189. Then either key the extraction node by the text hash as well or skip ambiguous documents in run_extract. I prototyped the grouping locally: case4 goes indeterminate with incomplete-coverage:1/2, and the suite passes except test_a_failed_run_leaves_the_previous_generation, which would need to replace doc6a's text (as test_retained_extractions_are_reused_until_the_text_changes does) rather than add a second one. A test that inserts a second text onto doc4a would pin it.

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 32c0041

Comment thread docs/guides/custom-stages-python.md Outdated
```python
import fluree
with fluree.connect("./data") as conn:
conn.create("claims").insert("claims.ttl")

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.

🔴 Must address before merge — insert("claims.ttl") reads the string as Turtle, so the guide's setup step fails on its first line.

Ledger.insert reads a file only when it's given an os.PathLike (_rdf_payload, fluree-db-python/python/fluree/_connection.py:1784-1803); a str is the data itself. Run from the example directory at this head, the line raises InvalidRequestError: Turtle parse error: Lexer error at position 0: unexpected character 'c'. The tests pass a Path (EXAMPLE / "claims.ttl"), so nothing runs the documented line, and the example's README.md:17 has the same one.

Fix, here and in the README (illustrative):

from pathlib import Path
import fluree

with fluree.connect("./data") as conn:
    conn.create("claims").insert(Path("claims.ttl"))

It might be worth having test_the_command_line_runs_the_example_manifest run the README's setup snippet from the example directory, so the docs and the test can't drift apart again.

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 484f107

def first_attempt_races(txn, *a, **kw):
if not raced:
raced.append(True)
worker.run_gate(ledger, with_(gate_version="v2"))

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.

🟠 Should address — this race test passes with the compare-and-swap read moved out of the transaction, which is the one change that would break the guarantee.

The competing publication lands before fn runs, so write's read already sees generation 1 and raises without the commit conflict ever mattering; a read from the ledger head sees generation 1 too. I changed worker.py:290 to current_generation(ledger, graph) and all 12 tests stayed green. With the race moved to between that read and the commit (I wrapped worker.current_generation so its first call inside publish() publishes v2 right after reading), the mutated worker publishes generation 1 over the winner's generation 1 and the v2 record is gone, a lost update, while the code as written raises StaleRun on the retry.

Since this is the example people will copy and "simplify", I'd pin it: inject the competing publication after the read inside publish() rather than before fn. I recognize it's a test-only change, 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 fad816d

for doc in received_by(case, clock):
extraction = extraction_of(doc) or {}
vendor = extraction.get("vendor")
if vendor is not None and vendor not in reference.approved_vendors:

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.

🟠 Should address — a partial extraction reads as a clean one: a missing vendor passes the approved-vendor check and a missing amount counts as zero.

decide checks the vendor only if vendor is not None, and adds an amount only when there is one, so the gate can't tell "this document has no vendor" from "the model couldn't read the vendor". With a model that returns {"amount": Decimal("50.00")} for doc3a (its vendor line unreadable), case3 goes from flagged (unapproved Initech) to cleared. The toy model does the same one level up: it returns {} for any text its regex misses, so toy_model("Invoice from Initech for $50.00") is {} and case3 is cleared. It never returns None, so with the shipped model "unavailable" only happens when the model raises.

That seems like the case the guide's "Missing evidence is not an answer" means to rule out, so I wonder if a partial extraction (one of vendor/amount without the other) should be a gap, e.g. partial-extraction:<doc>. That keeps case6's {} ("nothing to extract") cleared, which I read as deliberate. toy_model could also return None for text that reads like an invoice but doesn't match, so the example exercises the ask-again path with its own model. If the per-document granularity is deliberate, it's probably worth a sentence in the guide's contract that a missing field counts as "found nothing".

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 32c0041

Comment thread docs/guides/custom-stages-python.md Outdated
The server applies the update atomically. A run that lost the race matches
nothing and commits nothing; it confirms its own publication by reading the
generation record back and finding its generation and output hash there. The
first publication guards with `FILTER NOT EXISTS` on any generation record

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 — the first publication's guard needs its own example: read literally, "FILTER NOT EXISTS … instead" keeps ?s ?p ?o, and on an empty graph that matches nothing.

If I swap the generation triple for FILTER NOT EXISTS { ?gen w:generation ?any } and keep ?s ?p ?o, the WHERE has no solutions on an empty graph, so nothing is inserted and the run's read-back reports a lost race on every first publication (run through ledger.update at this head: no generation record, empty graph). What works is dropping the DELETE and the ?s ?p ?o; four threads racing this on 30 fresh ledgers always left exactly one winner:

PREFIX w: <http://example.org/worker#>
INSERT { GRAPH <http://example.org/claims-review/decisions> {
  # … the new results …
  <http://example.org/claims-review/decisions#generation> w:generation 1 .
} }
WHERE { FILTER NOT EXISTS { GRAPH <http://example.org/claims-review/decisions> {
  ?gen w:generation ?any } } }

I recognize this is minor, but if you agree I'd rather see the block in the guide now than have the first reader who tries it rediscover it.

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 ecb52f1

one uses the [HTTP API](../api/endpoints.md). Its pinned reads are queries
`from` `claims:main@t:<t>`. It publishes with one guarded update: the
`WHERE` requires the generation the run started from, and the update deletes
the graph's contents and inserts the new ones and the next generation

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 — over HTTP the guarded update re-asserts every unchanged result each generation, so its commits hold the whole result rather than the difference.

In publish() the delete and the insert are two staged operations, and the transaction nets an unchanged fact to nothing. A single DELETE … INSERT … WHERE doesn't: its constant INSERT template is instantiated once per WHERE solution, and the engine's per-fact counting keeps the surplus assertion. Going from {r1, generation 1} to {r1, generation 2} through this update commits assert r1 although r1 was already there (run through ledger.update at this head). The graph ends up right; each commit just carries every unchanged result again.

Maybe worth a sentence here so nobody expects the Python path's commit sizes over HTTP; #2129 tracks the engine side. The same counting is what makes the opposite shape lose a fact (in the note at the top).

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 ecb52f1

current = current_generation(txn, graph)
if current != started_from:
raise StaleRun(f"{graph} is at generation {current}; this run started from {started_from}")
txn.update(f"DELETE {{ GRAPH <{graph}> {{ ?s ?p ?o }} }} WHERE {{ GRAPH <{graph}> {{ ?s ?p ?o }} }}")

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.

👍 Clearing the graph and inserting the new contents as two staged operations in one transaction, with the generation read inside it, is right on both counts. I ran eight generations against one graph (a fact dropped and re-published, duplicates in one output, an empty result, and the same fact also stored in the default graph and in another named graph): the graph held exactly the expected set each time, unchanged facts produced no flakes, and the copies outside the stage's graph never moved. Four threads racing run_gate on one connection for 20 rounds always produced one publication per round and StaleRun for the rest.

Base automatically changed from feat/reasoning-limits-explanations to main October 20, 2026 03:13
An example in fluree-db-python/examples/reference_worker of a custom
stage that runs in Python next to a ledger, using only the package's
ordinary query and transaction calls. A claims review in two stages: an
extract stage runs a model over documents and keeps its outputs, and a
versioned gate stage decides each case from the documents, their retained
extractions and reference data.

Each run reads every input from one pinned snapshot and evaluates at the
manifest's clock, never the wall clock. It replaces the whole contents of
the named graph the stage owns in one transaction, which nets to the
difference, together with a generation record: the input ledger and t,
the evaluation time, the program, code, engine and gate versions, the
model, and a hash and count of the output. The record keeps an empty
result's graph in existence. A run that fails publishes nothing, and
publication is a compare-and-swap on the generation number, so a run that
finds a newer generation than it started from refuses to publish.
Missing text, a missing extraction, or fewer documents than a case expects
makes the case indeterminate rather than cleared. A new gate version
replays over the same pinned inputs without calling the model.

The manifest format is experimental. The tests run the worker against its
example data, including a race between two publications, a stored datalog
rule that reads the published graph, and the command line.
@bplatz
bplatz force-pushed the feat/datalog-reference-worker branch from f57cd41 to d822579 Compare October 20, 2026 03:14
The reference worker built one document per row of its case query, which
returns a row for each combination of a document's texts and received
times. A document given a second text counted as two documents, so a case
missing one of its expected documents could be cleared, and both texts'
extractions landed on one node whose vendor and amount came from different
texts.

Rows are now grouped by case and by document. A document with two texts or
two received times, or a case with two expected counts, is a gap
(ambiguous-text, ambiguous-received-time, ambiguous-expected-documents),
and extract skips a document whose text is ambiguous.

An extraction with a vendor and no amount, or an amount and no vendor, is
also a gap (partial-extraction): the gate read a missing vendor as an
approved one and a missing amount as zero. An extraction with neither
still means the document had nothing to extract. The toy model now gives
no answer for an invoice it cannot read, rather than reporting it found
nothing.
Ledger.insert reads a file only from a path object and treats a string as
Turtle text, so the setup step in the example's README and in the guide
failed on its first line with a Turtle parse error.

The command-line test now runs the README's setup block from a copy of the
example's data and checks that the guide shows the same block.
The race test published the competing generation before the transaction
function ran, so the generation read saw it directly and refused, and the
test passed with that read moved out of the transaction. The competing
publication now lands right after the read inside publish(): the
transaction was read, so its commit conflicts and the re-read refuses. A
transaction that was only written to is staged again on top of the other
commit, which publishes over it.
The guide said the first publication guards with FILTER NOT EXISTS
"instead", which read literally keeps ?s ?p ?o and so matches nothing on
an empty graph. It now shows the first publication's update, with no
DELETE. It also says that the single guarded update asserts every
unchanged result again in each commit, unlike publish(), whose two staged
writes net to the difference.
@bplatz
bplatz merged commit d9a1d20 into main Oct 20, 2026
19 checks passed
@bplatz
bplatz deleted the feat/datalog-reference-worker branch October 20, 2026 03:32
aaj3f added a commit that referenced this pull request Oct 20, 2026
…ferences

Brings in #2122, #2126, #2127, #2131 and #2133. The one conflict is in
fluree-db-api's re-exports, where #2131's `SharedFluree` / `SharedOptions`
and this branch's `target_dataset` items both land.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:datalog Reasoner, rules, reasoningDefaults documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants