Skip to content

feat(python): the fluree Python package - #2025

Merged
bplatz merged 48 commits into
mainfrom
feat/python-package
Oct 8, 2026
Merged

bplatz merged 48 commits into
mainfrom
feat/python-package

Conversation

@bplatz

@bplatz bplatz commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

fluree for Python: the engine embedded in-process through a PyO3 extension (fluree-db-python, built with maturin), with an API that feels native to Python.

What it covers

  • Connections and ledgers. fluree.connect(path | ":memory:" | config=); ledgers created, opened, listed and dropped; writes in JSON-LD, Turtle/TriG and files; sync to make a graph match a payload.
  • One query surface for three languages. query() takes SPARQL, Cypher or JSON-LD, told apart from the text; select() is typed to return a Result for tables. Results are Records that read by position, key or attribute, with single() (strict) / first(), value(), data(), to_pandas(), to_polars(), and a Jupyter table. RDF terms come back as Python values (int, Decimal, datetime, IRI, LangString, Literal, Vector) and the same values go back in as writes and parameters.
  • Transactions. ledger.transaction() as a context manager, and ledger.transact(fn) that re-runs read-then-write work on conflict. Cypher writes, SPARQL updates and JSON-LD stage together.
  • Time and history. Snapshots, at(t= | time= | commit=), history(), log(), changes(); branches with merge, rebase and revert, with previews.
  • Policy. with_policy(...) returns a governed handle; a query or write that names its own policy is refused, so a query passed in from elsewhere cannot widen it. What policy cannot filter (log(), info(), graphs(), and the maintenance, branch and export operations) is refused on a governed handle.
  • Search and graph data. Full-text configuration and fulltext(), embedding vectors (numpy arrays accepted), named graphs, edge annotations, reasoning and datalog rules through the existing query forms.
  • Graph sources. Iceberg, Delta and SQL (Trino protocol) tables mapped by R2RML, queried in place and materialized into ledgers.
  • Operations. validate, index, reindex, verify, sweep, export, archive / restore, query fuel limits, timeouts, profile(), explain(), streaming, Ctrl-C and asyncio cancellation, encryption at rest via connection config, structured errors (ShaclViolationError, UniqueConstraintError, conflict ts), and engine logs on Python's logging.
  • asyncio. fluree.aio mirrors the API; cancelling a task stops its query, and an async transaction cancelled mid-write rolls back, unless the write was its commit, which completes (txn.committed says so).
  • Processes. Each process runs its own engine. A child forked after the engine started refuses to use it, inherited objects included, and names the spawn and forkserver start methods: the engine's threads do not survive a fork, and the lock state they leave behind is unsafe to reuse. A child forked before the engine started uses it normally.

Packaging and CI

  • One abi3 wheel per platform for CPython 3.10+, versioned with the workspace. The wheel carries the repository LICENSE.
  • Documentation: an API reference at fluree.github.io/db/python (Sphinx with sphinx-autoapi, which reads the package source, so no engine build), with the README as its guide; docs.yml publishes it beside the book, and the CI python job builds it strictly, so a docstring reference that resolves nowhere fails the PR. The book gains a "Using Fluree from Python" page, and PyPI's Documentation link points at the reference.
  • The CI python job builds a debug wheel on Linux, macOS and Windows and runs the pytest suite on Python 3.10 and 3.14, plus mypy on the package.
  • .github/workflows/python-release.yml builds release wheels on the CLI's runners and platforms (Linux x86-64/arm64 as manylinux_2_28, macOS arm64, Windows x64) from the same version tags as the CLI, tests each in a fresh environment, and publishes to PyPI by trusted publishing from the pypi environment. Only a v* tag push publishes, and only when the tag names the version the wheels carry; the publish action is pinned to a commit. docs/contributing/releasing.md covers it.
  • The workspace version is bumped to 4.2.4-beta.1: tagging the merge commit v4.2.4-beta.1 publishes the first PyPI release, fluree 4.2.4b1 (superseded by 4.2.4), with the CLI's pre-release binaries. Before that tag: create the pypi environment with a deployment rule admitting only v* tags, and register the PyPI trusted publisher against it.

Engine

One addition: Fluree::sparql_dataset_within_ledger resolves a SPARQL query's FROM / FROM NAMED within a view's ledger, as query() does, for entries that take a DataSetDb. A ledger's stream() uses it, so it reads the graphs its FROM names, as query() of the same text does.

Known limits

  • stream() takes SPARQL and JSON-LD; Cypher results are read with query().
  • A JSON-LD query on a ledger, snapshot or transaction reads that ledger, so from, fromNamed or ledger naming anything else is refused; conn.query() reads across ledgers.
  • Local (file://) graph-source tables are not supported on Windows, as for the CLI.
  • An R2RML column without rr:datatype reads back as a string; the README tells mappings to set one.

Builds on #2022, #2023 and #2024.

Follow-up: #2034

@bplatz
bplatz added this pull request to stack #2026 October 6, 2026 03:23
@bplatz bplatz changed the title feat/python package feat(python): the fluree Python package Oct 6, 2026
@bplatz bplatz added the enhancement New feature or request label Oct 6, 2026
@bplatz
bplatz requested review from aaj3f and zonotope October 6, 2026 03:24
@bplatz
bplatz marked this pull request as ready for review October 6, 2026 03:24
@bplatz
bplatz force-pushed the feat/python-package branch from b4483cd to bc638d3 Compare October 6, 2026 10:13
@bplatz
bplatz force-pushed the feat/python-package branch from bc638d3 to 6a7154f Compare October 6, 2026 10:26

@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.

This is neat @bplatz. It's a nice design with very little overhead. The only thing that stands out to me and deserves a headline note is that, while I understand why start_stream runs a ledger-handle stream through the dataset streaming entry (e.g. because the single-view entry takes a LedgerState and w2ould drop the view's policy), the dataset entry point assumes the caller already resolved the dataset itself, so FROM/from in the query is ignored and ignored quietly. Some more detail below, but I don't think that element in particular should merge as-is


The native layer stays thin, the GIL comes off for every engine call, cancellation goes through the engine's checkpoints instead of racing a timer, and keeping extension-module out of the crate's features means the workspace jobs never link libpython (clippy checks the crate, nextest never builds it). I built the wheel from 84474096a, ran the suite on 3.14 and 3.10 (327 passed on each), and spent most of my time trying to get a query past with_policy — JSON-LD opts in every spelling, # PRAGMA variants, SERVICE, cross-ledger FROM — and couldn't. The three things that need to land first:

  1. stream(), and JSON-LD query(), on a ledger handle silently drop the dataset the query names (fluree-db-python/src/connection.rs:1297). stream("… FROM <urn:g1> …") answers from the default graph while query() of the same text answers from urn:g1, and {"from": "other"} answers from this ledger in both. One dataset guard next to jsonld_policy_free / sparql_policy_free covers it.
  2. log() and info() (and graphs()) read past a governed handle (fluree-db-python/python/fluree/_connection.py:795, :1101): on a deny-all handle, log() returns a commit message its own txn-meta query hides, and info() lists class and property counts. _require_unrestricted, as the other policy-bypassing operations already use, closes it.
  3. The release path needs its gate before the next tag (.github/workflows/python-release.yml:90): there's no pypi environment in the repo yet, so the first tag run creates one unprotected; nothing compares the tag with the published version; and a hand dispatch from a tag ref publishes. The environment is a settings change rather than code, but it has to exist before the next v* tag.

Beyond those, two readers on one RowStream hang the interpreter (stream.rs:88; the same shape e94583050 fixed in close()), and the inline comments carry three small optional notes (README cancellation and retry wording, the ci.yml comment that now sits above the wrong job, and a NullHandler question).

One broader note on the first item, not for this PR: it's the third time I've seen this shape, a query entry point that drops a dataset the request names instead of honoring or refusing it. 993b095c9 fixed the server's default-graph-uri being parsed and discarded; this is the stream path; and the view JSON-LD path's from predates this PR. The structural fix is engine-side (every entry handed a pre-built view or dataset refuses a query-borne dataset it won't apply), and once that exists the guard here becomes redundant.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ a thin layer over the fluree-db-api builders; policy through GovernanceOptions and the engine's own parsers; errors by typed variant, then status. ⚠️ The stream path takes the dataset entry, which skips the view path's dataset-clause handling (item 1).
  • Performance (speed first, memory second): ✔ No engine crate changes, and Cargo.lock only adds packages; no performance-degradation risk.
  • Deployment targets: ✔ A new host, a CPython extension in someone else's process: fork is refused after the engine starts on every platform (84474096a, after CI caught the Linux abort at 6a7154fc5), the GIL is released, engine threads get 8 MB stacks, and Ctrl-C cancels queries. CI covers debug wheels on Linux, macOS and Windows; the release workflow (manylinux_2_28, the release runners) has never run, so a hand dispatch on main before the first tag would be cheap insurance. Embedded, server, CLI and wasm32 are untouched.
  • Testing: ✔ 327 pytest cases against the real engine on three OSes and two Pythons, plus mypy. ⚠️ Nothing streams a dataset clause, reads metadata through a governed handle, or shares a stream between threads.
  • Conventions: ✔ fmt and clippy clean (CI and locally), thorough commit bodies, releasing.md and the README updated; the wheel carries LICENSE with License-Expression: BUSL-1.1.

Verified locally at 84474096a: debug wheel via maturin, pytest 327/327 on 3.14 and 3.10; short-circuiting the inline-policy refusal turned both policy-refusal tests red; a probe for each finding above; cargo clippy -p fluree-db-python --all-targets --all-features -- -D warnings and cargo fmt --check clean.

Before PyPI: One thing I think we need to settle before this goes to PyPI. tests/test_errors.py's shaped fixture inserts SHAPES into a :memory: ledger and expects ShaclViolationError, and the README describes it as "a write the ledger's SHACL shapes reject" without saying how SHACL gets turned on. That's the shapes-exist heuristic, and my #2009 makes SHACL explicit-only (enforced where config sets f:shaclEnabled), as a deliberate breaking change. It's a behavior change, not a persisted-format one, so it stays on main rather than going to next, and whichever of the two lands second adjusts. The fixture gains the config insert that turns SHACL on (the python job will flag it), and the README gains a line on how SHACL is enabled. I'd rather the package publish with the explicit model from day one than put the heuristic on PyPI and change it a release later.

Relatedly, since ledger.transaction(), ledger.transact(fn) and parameters sit directly on #2022–#2024, I'd hold this until the fixes raised on those land (the named-graph netting, the re-staged policy context and rollback_to, the blank-node parameter), with a pytest case for each, so the Python surface pins them too.

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

Comment thread fluree-db-python/src/connection.rs Outdated
Some(params) => options.with_params(params),
None => options,
};
// A single-ledger dataset keeps the view's policy with the producer.

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: stream(), and JSON-LD query(), on a ledger handle silently drop the dataset the query names, so they answer from the wrong graph.

start_stream hands the engine a pre-built DataSetDb::single(db) and plans with plan_stream_query_dataset_with_options, which treats the dataset as already resolved: a SPARQL FROM / FROM NAMED in the text is parsed and then ignored. The buffered path (query_with_options) resolves a within-ledger FROM (D-3) and refuses a cross-ledger one, so the two verbs disagree on the same text. Separately, the view JSON-LD path ignores from / fromNamed altogether — that part predates this PR, and the server's ledger-scoped route sidesteps it by routing a body with from onto the dataset path (pin_jsonld_dataset), which a ledger handle here doesn't do.

I ran each of these against the wheel built from 84474096a:

  • ledger.query("… SELECT ?s ?ssn FROM <urn:g1> WHERE { ?s schema:ssn ?ssn }") returns the urn:g1 row; ledger.stream(<same text>) returns the default graph's rows.
  • ledger.stream("… FROM <other> …") returns rows from ledger, where query() raises "references a graph that is not in this ledger".
  • ledger.query({"from": "other", …}) and ledger.stream({"from": "other", …}) both return rows from ledger.

Policy still applies in every case, so this isn't an escalation — but it is the same query giving a different answer through two verbs on one handle, with nothing telling the caller.

The fix I'd suggest is one dataset guard next to jsonld_policy_free / sparql_policy_free, run by every ledger, snapshot and transaction entry: refuse a JSON-LD from / fromNamed / from-named / ledger (top level or in opts) that names anything but this ledger, pointing at conn.query() and ["graph", iri, …]; and in start_stream, refuse a SPARQL dataset clause (fluree_db_sparql::resolve_dataset_clause(&ast) returning Some) or resolve it the way query() does. A test that streams FROM <named graph> and compares it with query() 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 28aad96. A SPARQL FROM / FROM NAMED is now read as query() reads it (within the ledger; anything else refused). A JSON-LD from / fromNamed / from-named / ledger that names anything but the handle's ledger is refused. The engine-side fix: Follow-up: #2034.

for row in rows
]

def log(self, limit: int | None = None) -> list[Commit]:

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: log() and info() (and graphs(), which reads info()) go around a governed handle's policy, though the with_policy docstring says every read through it is subject to policy.

The PR already refuses the operations that bypass policy with _require_unrestricted (export, archive, merge, validate, index, …), but log() calls native.log and info() (line 1101) calls native.info, and neither takes the policy.

I ran it on people.with_policy(identity=EX + "nobody"), an identity with no policies, so deny-all: query("SELECT ?m FROM <urn:fluree:people:main#txn-meta> WHERE { ?c f:message ?m }") returns [], while log() returns (1, "onboarded john, ssn 888-88-8888"). info()["stats"] lists http://schema.org/ssn with count: 1, and ex:User with count: 1 and ssn in its property list — the existence and cardinality of data the handle can't see.

Minimally, self._require_unrestricted("log") / ("info") / ("graphs"), matching the rest (index_status() and branches() are harmless but could follow for consistency). If the intent is parity with the server, whose log and info routes are scope-gated rather than policy-filtered, then the docstring should say which reads policy covers — but I'd lean toward refusing, since whoever holds a governed handle will reasonably take what it shows to be governed.

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 9f21f28

Comment thread .github/workflows/python-release.yml Outdated
publish:
name: publish to PyPI
needs: wheels
if: startsWith(github.ref, 'refs/tags/')

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: nothing stands between a pushed tag and an irreversible PyPI publish yet.

  • There's no pypi environment in fluree/db today (GET repos/fluree/db/environments/pypi is a 404; the only environment is github-pages), and there's no tag ruleset (the one ruleset protects main). A job that names a missing environment creates it with no protection rules, so once this merges and the PyPI trusted publisher is registered, any writer who pushes a tag matching **[0-9]+.[0-9]+.[0-9]+* publishes.
  • The wheels carry the workspace version from Cargo.toml, and nothing compares it with the tag. A tag on the wrong commit, or a stray foo-1.2.3, publishes whatever version that commit carries, and as releasing.md says, PyPI never takes a version twice, so the only remedy is a yank.
  • The header says a hand run builds and tests "without publishing", but workflow_dispatch on a tag ref sets github.ref to refs/tags/…, which satisfies this if:.

What I'd suggest: create the pypi environment with a deployment rule limited to v* tags (plus a required reviewer if you want a human gate) and register the PyPI trusted publisher against it before merging; tighten this line to if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v'); and check the tag against the built version in the wheels job, which already has setup-python. Illustrative, not a drop-in:

      - name: The tag names the version being built
        if: github.ref_type == 'tag'
        shell: bash
        run: |
          py="${{ steps.py314.outputs.python-path }}"
          "$py" -m pip install --quiet packaging
          "$py" -c 'import glob, os, sys; from packaging.version import Version as V; tag = V(os.environ["GITHUB_REF_NAME"].lstrip("v")); built = {V(os.path.basename(w).split("-")[1]) for w in glob.glob("dist/*.whl")}; sys.exit(0 if built == {tag} else f"tag {tag} does not match the wheel version {sorted(map(str, built))}")'

Optional while you're here: pypa/gh-action-pypi-publish@release/v1 is the one step holding the OIDC token, so it's the one I'd pin to a commit SHA.

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 24b00a2. The pypi environment with its v* tag rule, and the trusted publisher registration, are set up before the next tag.

Comment thread fluree-db-python/src/stream.rs Outdated
max: usize,
) -> PyResult<Option<Vec<Bound<'py, PyTuple>>>> {
let runtime = runtime()?;
let mut guard = self.records.lock().expect("stream lock");

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: two threads reading one RowStream hang the whole interpreter.

next_batch takes self.records with the GIL held and keeps it across py.detach while it waits for a record. That wait re-takes the GIL every 50 ms (Python::attach(|py| py.check_signals())), and detach needs it back on the way out. A second thread calling next_batch meanwhile blocks on self.records.lock() while holding the GIL, so neither moves, and no other Python thread runs either. e94583050 fixed this exact shape in finish() with try_lock; next_batch still has it.

I ran it with a stream whose first row is a few seconds out, its head record already read, and thread A in next_batch: alone, A returns in 2.3 s; start thread B on the same stream and the process hangs until an outer 150 s timeout kills it (the main thread can't even return from join(60)). The aio wrapper stays clear of it on cancellation, since it closes the stream, but two tasks awaiting anext() on one stream reach it the same way.

Either refuse the second reader the way Transaction::check_out does ("in use by another thread", via try_lock), or take the lock with the GIL released (py.detach(|| self.records.lock())). This is 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 f378f37

/// Policy belongs to the handle (`Ledger.with_policy`). A query or write
/// that selects its own — JSON-LD `opts`, SPARQL `# PRAGMA` — is refused:
/// on a view it would be ignored, and it must never widen a governed handle.
fn refuse_inline_policy(inline: GovernanceOptions) -> PyResult<()> {

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.

👍 Refusing inline policy with the engine's own parsers (GovernanceOptions::from_json / from_sparql) and its own has_any_policy_inputs() means the refusal covers exactly the options the engine honors, in every spelling, rather than a list kept here. I tried default-allow / policy-class: [] / lowercase # pragma / a pragma after PREFIX, and SERVICE and cross-ledger FROM on a governed handle, and none got through; with the check short-circuited, test_a_query_cannot_choose_its_own_policy and test_a_write_cannot_choose_its_own_policy both go red.

Each call runs on a worker thread while the event loop carries on.
Cancelling a task that awaits a query (`asyncio.timeout`, a client that
disconnects) stops the query in the engine; a write already under way still
completes. Cancelled inside `async with ledger.transaction()`, the block waits

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 / nit: two README sentences promise a little more than the engine does.

  • "Cancelled inside async with ledger.transaction(), the block waits for that write to finish, rolls the transaction back" — when the write in flight is commit() there's nothing to roll back. I cancelled a task mid-commit() on a 60,000-fact transaction and got CancelledError, with txn.committed set and all 60,000 facts in the ledger. A caller that reads CancelledError as "nothing happened" and retries non-idempotent work will apply it twice; a clause like "…unless that write was the commit itself, which completes; txn.committed says which" would cover it. The PR body's "rolls back cleanly" has the same gap.
  • Line 409, "a commit that loses a race to another process is retried against the new state" — retried a bounded number of times: two processes doing 40 insert()s each into one directory gave one ConflictError from a plain insert() (nothing lost, 79 commits). Pointing contended writers at transact() would set the expectation.

This is minor and non-blocking — but if you agree, I'd rather see it in this PR 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 c962a65, and the PR body no longer says "rolls back cleanly".

Comment thread .github/workflows/ci.yml
# which is the package's hosting contract.
# ubuntu-24.04 ships a matching Chrome + chromedriver pair. Same RUSTFLAGS
# restatement as the wasm32 job (an env RUSTFLAGS masks .cargo/config.toml).
python:

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 / nit: the python job landed between wasm-smoke's comment and its job. Lines 336-344 ("Executes the browser build … Same RUSTFLAGS restatement as the wasm32 job") now read as the python job's preamble, and wasm-smoke: (line 415) has none. Moving the python job above line 336, or below wasm-smoke, puts each comment back on its job.

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 46ee47e


The engine's log goes to Python's `logging` as the `fluree.engine` logger,
each record carrying the engine module that wrote it as `record.target`.
Warnings and errors are sent by default; `fluree.set_log_level("INFO")` (or

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.

❓ More of a question than a suggestion: should the package put a NullHandler on its logger? With nothing configured, Python's last-resort handler prints the forwarded WARNs to stderr. In the two-process probe above that was ~40 lines of "commit conflict under matching snapshot; reconciling and retrying" for 80 inserts the engine handled fine. The logging HOWTO's advice for libraries is a NullHandler on the package logger so the app opts in; if you'd rather keep warnings visible by default, that's a reasonable call too.

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 4bed191

@bplatz
bplatz force-pushed the feat/python-package branch from 8447409 to fc56a77 Compare October 7, 2026 17:18
@bplatz
bplatz force-pushed the feat/python-package branch 2 times, most recently from e7c5ede to 91a316a Compare October 7, 2026 18:48
@bplatz
bplatz force-pushed the feat/python-package branch 2 times, most recently from 9a953fa to 20bf223 Compare October 7, 2026 19:55
@bplatz
bplatz force-pushed the feat/python-package branch 2 times, most recently from 8a77339 to 34e9d0c Compare October 7, 2026 23:11
Base automatically changed from feat/engine-query-features to main October 7, 2026 23:29
bplatz added 4 commits October 7, 2026 19:29
A new workspace crate, fluree-db-python, builds the `fluree` Python package
with PyO3 and maturin: one abi3 wheel per platform for CPython 3.10+. The
engine runs in-process; a thin native module does the engine calls and the
public API is Python, following stdlib and pandas conventions.

- `fluree.connect(path | ":memory:" | config=...)`; the config is the
  JSON-LD connection document the server takes (S3, DynamoDB nameservice,
  encryption at rest, env-var values).
- Ledgers: create (optionally bulk-importing), open, list, drop, info,
  default context.
- Writes: insert/upsert (JSON-LD, Turtle, TriG, files), update (SPARQL
  UPDATE or JSON-LD), each returning a `Commit`.
- Queries: SPARQL and JSON-LD on a ledger, a frozen snapshot, a past state
  (`at(t=, time=, commit=)`), or across ledgers via FROM. SELECT rows are
  named tuples of native Python values in projection order, with
  `to_dicts()`/`to_pandas()`; `stream()` reads large results lazily.
- `max_fuel`, `timeout`, `profile()`, `explain()`. Timeouts and Ctrl-C
  cancel through the engine's cooperative cancellation, since query
  operators do not yield to an async timer.
- `with_policy(identity=, policy_class=, policy=, values=, default_allow=)`
  governs reads, writes, history and commit contents.
- `history()`, `log()`, `changes()`, `export()`, `archive()`, `restore()`.
- Errors derive from `FlureeError` and the matching builtin
  (`LookupError`, `ValueError`, `PermissionError`, `TimeoutError`).

The crate's lib is `test = false` so workspace builds never link libpython;
a new `python` CI job builds the wheel on Linux and macOS and runs the
pytest suite on Python 3.10 and 3.14.
…nd previews

Ledger.branch/branches/merge/merge_preview/rebase/revert/revert_preview,
Snapshot.branch for branching from a past state, and conn.drop on a
name:branch id. Merge-preview conflict keys are decoded to full IRIs.
Commit refs share one parser (t, canonical CID, or digest prefix).
ledger.transaction(message=...) is a context manager that commits on a
clean exit and rolls back on an exception; its insert/upsert/update stage
and its query/explain read the staged state. insert, upsert and update take
message=, recorded as the commit's f:message.
…the difference

Ledger.sync(data, graph=, allow_empty=, dry_run=, message=) over the
engine's graph sync, returning a full Commit.
bplatz added 5 commits October 7, 2026 19:29
…stderr

A 1e19-second timeout overflows a Unix deadline but fits Windows' clock,
so that case is Unix-only. A fork case that fails now shows what the
child printed as it died.
…very platform

Idle engine threads wait in a process-wide table of parked threads. A
forked child inherits the table but not the threads, and its own threads
reuse their stacks, so a lock taken in the child could follow a stale
entry into overwritten memory: intermittently, a forked child aborted or
a fork-start pool hung. The child now raises FlureeError naming the
spawn and forkserver start methods, as it already did on macOS; a child
forked before the engine started still uses it.
begin_transaction now takes a TransactionOptions; the binding passes its
policy as the governance and leaves tracking and the index config at
their defaults.
…ank node

The engine now takes an f:embeddingVector parameter as a JSON array, so
the package no longer re-encodes a Vector or numpy array as its JSON text.
A blank-node parameter must be a stored node's id, so a BlankNode a query
returned works and one built from any other label is refused; the README
says so, and a test pins both.
@bplatz
bplatz force-pushed the feat/python-package branch from 34e9d0c to 82b98df Compare October 7, 2026 23:29
bplatz added 8 commits October 7, 2026 19:45
…N-LD dataset must be the ledger

stream() on a ledger, snapshot or transaction handed the engine the view
as a one-graph dataset, which the engine treats as already resolved, so
a SPARQL FROM / FROM NAMED was parsed and then ignored: the stream
answered from the default graph where query() of the same text answered
from the graph it named, and a FROM naming another ledger streamed this
one's rows where query() refused it.

The stream now reads the dataset query() reads: the engine's
sparql_dataset_within_ledger resolves the clause's graphs within the
ledger, each keeping the view's policy, and refuses one outside it.

A JSON-LD query on a ledger handle ignored from, fromNamed, from-named
and ledger altogether, in query(), stream() and explain(), and answered
from this ledger. Naming anything but this ledger, at the top level or in
opts, is now refused, pointing at Connection.query() and a ["graph", iri,
pattern] pattern.
with_policy() says every read through the handle is subject to policy,
but log() returned commit messages its own txn-meta query hid, and info()
(and graphs(), which reads it) listed class and property counts for data
the handle could not see. Policy cannot filter either, so they are
refused there, as the maintenance, branch and export operations already
are, and the with_policy() docstring says which reads those are.
The publish job ran for any ref under refs/tags/, so a hand run from a
tag published although the header said a hand run does not, and the
trigger took any tag carrying a version, such as foo-1.2.3. Nothing
compared the tag with the version the wheels carry, and PyPI never takes
a version twice, so a tag on the wrong commit published that commit's
version for good.

The trigger and the publish job now take only v* tags, the job only on
a push, and each wheel job checks that the tag names the version it
built. The publish action, the step that holds the OIDC token PyPI
trusts, is pinned to a commit. releasing.md says what the pypi
environment's tag rule guards.
…ocked

next_batch took the stream's lock with the GIL held and kept it while it
waited for a record, taking the GIL back every 50 ms to check for
signals. A second thread calling it meanwhile blocked on the lock still
holding the GIL, so the first could not take it back, and the whole
interpreter stopped. close() had the same shape, fixed by taking the
lock with try_lock.

A second reader is now refused the same way ("the stream is being read
by another thread"), as a transaction in use by another thread is.
… bounded number of times

Cancelling an async transaction while it commits does not roll it back:
the commit completes, and txn.committed says so, so a caller that reads
the CancelledError as "nothing happened" and retries would apply the work
twice. And a write that loses a commit race to another process is retried
only so many times before it raises ConflictError; transact() is the
answer for writers that contend heavily.
With no logging configured, Python's last-resort handler printed every
engine warning the package forwarded to stderr: two processes sharing a
directory printed a line per commit retry the engine handled on its own.
The logging HOWTO's advice for a library is a NullHandler on its logger,
so the application decides what is shown; the README says so.
The python job had landed between wasm-smoke's preamble and its job, so the comment read as the python job's and wasm-smoke had none.
…DME shows how

The SHACL error tests relied on the shapes-exist heuristic: a ledger that
held shapes enforced them with no config. SHACL is moving to the explicit
model, enforced only where the ledger config sets f:shaclEnabled, so the
tests now write that config first, which enforces under either rule, and
the README shows the config write that turns SHACL on.
… and rollback fixes

ledger.transaction() runs on the engine's Transaction, whose fixes landed
with their Rust tests. The Python surface now pins them too:

- inserting and deleting a value a cold index holds in a named graph
  retracts it;
- a commit staged again over a newer head is checked against the policy
  that head has, so a deny rule committed while the transaction was open
  refuses it;
- a Cypher script that fails partway is rolled back, and the writes
  staged before it keep the blank-node ids the caller already read.
@bplatz

bplatz commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

bplatz added 3 commits October 7, 2026 20:05
The docs site had a page for embedding Fluree in Rust and none for
Python. The new getting-started page installs the package, runs a first
ledger, and maps this book's queries, transactions, time travel,
branching, policy, search, graph sources and configuration to the
Python calls that run them, with the few ways a ledger handle differs
from the server. It is linked from the summary, the landing page and the
getting-started index.

pyproject's Documentation URL points at it, so PyPI shows the link, and
the package README sends readers to the book for concepts and query
languages.
The fluree.aio methods had none, so help() and editors showed only a
signature in async code. Each now gives its sync twin's summary and
points to it, as the aio module's other methods already did. The few
sync members without one (Ledger.id, Snapshot.ledger, Record and Result
accessors, Path ends, VerifyReport.healthy, ShaclViolationError.violations,
GraphSource's attributes) have one too.
Python users expect a hosted reference linked from PyPI. The package's
docstrings are written for Sphinx (:meth:, :class:), so the reference is
Sphinx with sphinx-autoapi, which reads the package source rather than
importing it: building it needs no compiled engine. It has the README as
its guide, the API under the public names (fluree.Ledger, not
fluree._connection.Ledger, with signatures linking there), and a page
for the type aliases signatures name (Query, Data, CommitRef, ...).

docs.yml builds it into the published site under /python/ alongside the
book, and redeploys when the package source or README changes. The CI
python job builds it with -n -W, so a docstring reference that resolves
nowhere fails the PR rather than rendering as plain text.

pyproject's Documentation URL points at it; the README and the book's
Python page link to it.
@bplatz

bplatz commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

On holding PyPI for #2009: the Python API doesn't change when #2009 lands, only default behaviour, as for every other surface: SHACL becomes opt-in, plus #2009's JSON-LD graph-scoping and write-check changes. Every class, method, signature and error class stays as it is, and the one new engine error maps to InvalidRequestError through the status fallback. The tests already turn SHACL on in the ledger config, so they pass under either rule, and #2009 can land before or after this. So we'll publish without waiting for it.

bplatz added 3 commits October 7, 2026 21:46
The package could reach PyPI only with an engine release: a v* tag, which
also runs the CLI release. A hand run of the Python release workflow on
main that names a version now publishes the wheels under it: the version
is set in pyproject.toml, which maturin prefers to Cargo.toml's, so
Cargo.lock and --locked are untouched, and the check that a tag names the
built version covers the named version too. A hand run that names none,
or one off main, still only builds and tests.

fluree.__version__ reads the installed package's version, so it reports
a Python-only release's own rather than the workspace's.

releasing.md describes the path and the pypi environment's rules (v*
tags and main, with a required reviewer); the README and the book's
Python page say what a pre-release version means for the engine inside.
The first PyPI release goes out as an engine pre-release (v4.2.4-beta.1,
CLI and wheels together), which the tag path already covers, so the hand
run on main that published a Python-only release is gone and only a v*
tag push publishes, as before. fluree.__version__ keeps reading the
installed package's version, which is the engine's.
The first PyPI release of the fluree package goes out as this pre-release, with the CLI's pre-release binaries, from the v4.2.4-beta.1 tag; PyPI carries it as 4.2.4b1, which v4.2.4 supersedes.
@bplatz
bplatz merged commit 745736a into main Oct 8, 2026
19 checks passed
@bplatz
bplatz deleted the feat/python-package branch October 8, 2026 02:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants