Skip to content

python: fluree.doc.read reads a document with an HTTP reader (the CLI's own read) - #2219

Merged
aaj3f merged 8 commits into
mainfrom
feat/python-doc-read
Nov 3, 2026
Merged

aaj3f merged 8 commits into
mainfrom
feat/python-doc-read

Conversation

@aaj3f

@aaj3f aaj3f commented Oct 30, 2026

Copy link
Copy Markdown
Contributor

Stacked on #2209 (doc read), which is stacked on #2207 and #2206, so the diff reads best against that branch.

This gives the Python package the same reader fluree doc read uses:

reading = fluree.doc.read("invoice.pdf", ontology="invoices.ttl",
                          catalog="suppliers.ttl", model="reader-small")
reading.usage.note            # "1,032 tokens"
reading.mentions()            # rows: text, begin, end, class, entity, score, element
reading.claims()              # rows: subject, predicate, object, asserted, score
conn.create("invoices").insert(reading.to_jsonld())

Shared core, not a second implementation. The first commit moves the per-document read loop out of the CLI into fluree_db_doc::reader::Session, together with Read and Usage::note: the cut into calls, sending, resending, caching, rebasing, stamping and doc:sourceElement. The CLI's doc_reader keeps only where the reader, ontology and catalog come from. That commit doesn't change behaviour; the CLI suites are unchanged and green. The Python side (fluree-db-python/src/doc.rs plus python/fluree/doc.py) then calls Session::read, so a document read from Python is cut, sent, resent and kept exactly as the CLI does it. A catalog file is cut down to its records' names, short descriptions and types (request::catalog_records_of), mirroring the CLI's record queries.

Signing in, first one present wins:

  1. api_key with auth_header: that key, as is, in that header, to url (a reader with its own key);
  2. api_key alone: a Fluree.ai API key (flk_…), traded for an hour's token at <service>/v1/auth/token;
  3. this machine's fluree login (fluree login / logout: sign a machine in to a fluree.ai account #2205's account.toml), refreshed and saved back when it's about to expire, the way the CLI does;
  4. FLUREE_AI_API_KEY, as in 2.

With no url, a Fluree.ai credential reads through the account's <api base>/grounding. Every request sends a User-Agent, since the service's edge refuses requests without one.

I don't love that (3) re-implements a small slice of #2205's account module: reading the file, refreshing, and the 0600 atomic save. The Python crate can't depend on the CLI crate, and #2205 hasn't merged, so I kept it to the minimum and pointed at the CLI's rules in the comments. Once #2205 lands, moving the load/refresh into a crate both can use is a small change, and I'd rather do it here than leave it, if you'd prefer that order.

Wheel size. The wheel now carries the document parser (fluree-db-doc). Measured on macOS arm64 with a release build without LTO: 39.0 MB → 43.6 MB compressed (+4.7 MB, +12%), and the .so grows 96.6 → 106.5 MB. That's the cost of fluree.doc.read("invoice.pdf") parsing in-process exactly as the CLI does, rather than asking users to shell out to fluree doc parse.

Tests:

  • tests/test_doc_read.py (7) runs against an in-process stub reader: the request (headers, role graphs, a catalog record cut to its names), the reading and its rows, Turtle output, inserting into a ledger, text=, a class-scoped catalog, cache_dir answering a repeated request with no call, the fluree login file (posting to /v1/grounding with its Bearer), an API key traded for a token (and the User-Agent), and the "how to sign in" error with no credential.
  • The whole package suite (380 passed), mypy, and the strict API-reference build (sphinx -n -W) are clean. So are cargo clippy -p fluree-db-python --features extension, -p fluree-db-doc, -p fluree-db-cli, and cargo test -p fluree-db-cli (491).
  • I also ran it live against a sandbox deployment of the service: through a fluree login sign-in (964 tokens billed) and through an flk_ key (738 tokens, text=), with the reading inserted into a ledger.

docs/getting-started/python.md gets a "Reading documents" section, and the module docstring is the reference. Like the earlier PRs, this gets no CI while it's stacked; it'll run once the stack lands on main.

🤖 Generated with Claude Code

https://claude.ai/code/session_016CjYmSGfnxzJgMSzBESNee

aaj3f and others added 4 commits October 29, 2026 20:00
…ession)

So the Python package can read a document exactly as `fluree doc` does,
the read loop (cut into calls, send, resend, cache, rebase, stamp,
doc:sourceElement) moves from the CLI's doc_reader into
fluree_db_doc::reader::Session, with Read and Usage::note. The CLI keeps
where the reader, ontology and catalog come from. No behaviour change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016CjYmSGfnxzJgMSzBESNee
`fluree.doc.read(path | text=, ontology=, catalog=, model=, cache=, url=,
api_key=, auth_header=, cache_dir=)` parses the file as `fluree doc parse`
does and reads it with fluree_db_doc::reader::Session, the CLI's own read,
returning a Reading: its expanded JSON-LD nodes (to_jsonld() inserts into a
ledger as is), to_turtle(), mentions() and claims() as rows, counts, the
billed Usage (with the CLI's one-line note), calls and cache hits, and the
reader's ontology notes.

The credential, first present: api_key in auth_header (as is, to url); an
api_key alone, a Fluree.ai API key traded at <service>/v1/auth/token; this
machine's `fluree login` (account.toml, refreshed when about to expire and
saved back as the CLI does); FLUREE_AI_API_KEY. With no url a Fluree.ai
credential reads at the account's <api base>/grounding. Requests carry a
User-Agent (the service's edge refuses requests without one).

A catalog file is cut to its records' names, short descriptions and types
(reader::request::catalog_records_of), as the CLI's record queries do.

The wheel now carries the document parser (fluree-db-doc).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016CjYmSGfnxzJgMSzBESNee
…doc-read

# Conflicts:
#	fluree-db-doc/src/reader/client.rs
@aaj3f aaj3f added the enhancement New feature or request label Oct 30, 2026
@aaj3f aaj3f self-assigned this Oct 30, 2026
@aaj3f
aaj3f requested a review from bplatz October 30, 2026 16:49

@arnaud-fluree arnaud-fluree left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@aaj3f moving the per-document loop into fluree_db_doc::reader::Session is the right call, and I checked the claim that the first commit changes nothing: the diff is a move, the wait label is rebuilt inside Session::read so the CLI's stderr is unchanged, --cache is still validated in the CLI before any source loads, and the CLI's reader and read suites are green on this head. py.detach around the whole read (parse, HTTP, resends) with the tracing layer on Python::try_attach is also right: the GIL is free for up to five minutes of waiting. Two headline notes, both confirmed against the real Nakaya gateway.

(1) mentions(), claims()'s score, mention_count, entity_count and linked read a vocabulary no reader emits. doc.py keeps nodes typed doc:Mention and reads doc:mentionClass and doc:score; the first doesn't exist anywhere in the repo and the second only in this PR's Python stub. The only reader there is answers in nk:Occurrence / nk:class / nk:score / nk:refersTo, and reader::PROFILES is empty. Live: 604 tokens billed, two nk:Occurrence and one nk:LocalEntity in reading.nodes, and mentions() == [], mention_count == 0, linked == []; the SPARQL query from python.md on the ledger where to_jsonld() was inserted returns no rows. That's the headline example of the docs. The profile is #2207's to fill (flagged there); what this PR promises on top of it is the part I'd hold until one exists. Inline at doc.py:97.

(2) text= always reads under urn:fluree:doc:text.txt. The temporary file is named text.txt, document_iri is minted from the file name, and every node of the reading hangs under that IRI. Live: two different texts both get doc:sourceDocument urn:fluree:doc:text.txt and share …/text.txt/entity/1 and the nk:ExtractionRun node, so two readings inserted into one ledger merge silently. Inline at doc.py:180.

Full review below:


🔴 Request changes (two must-address items; the second is a one-liner).

The mechanics are good and well shared: a document read from Python is cut, sent, resent, cached and stamped by the same Session the CLI uses, catalog_records_of keeps the catalog small in every window, the toml::Table for account.toml preserves fields Python doesn't know, and the four load-bearing tests go red under their own bugs (cache key, catalog cut, class scope; the refresh one for the wrong reason, inline). The credential chain is where the Python side quietly diverges from the CLI, in ways that will bite a user porting a [doc.reader] to a call (inline at src/doc.rs:160 and :179).

By weight:

  • 🔴 doc.py:97: mentions() and friends read doc:Mention / doc:mentionClass / doc:score, which no reader writes (inline, live).
  • 🔴 doc.py:180: text= always mints urn:fluree:doc:text.txt (inline, live).
  • 🟠 src/doc.rs:160: a reader can't be called without a credential, and a fluree login token is sent to any url= (inline).
  • 🟠 src/doc.rs:179: api_key alone means Bearer in [doc.reader] and a token exchange here (inline).
  • 🟠 request.rs:528: a file catalog isn't "the CLI's own read": literals differ, so the request body and the cache key differ (inline).
  • 🟡 src/doc.rs:207: a token is minted on every read() with an API key (inline).
  • 🟡 src/doc.rs:271: the refresh-and-save path has no test; the mutation goes red for the wrong reason (inline).
  • 🟡 src/doc.rs:79: no vision escalation from Python, while the docs say the parse is the CLI's (inline).
  • 👍 session.rs:165: the wait label rebuilt inside the session is what keeps the move behaviour-preserving (inline).

Smaller notes with no good anchor:

  • The body's "the Python crate can't depend on the CLI crate" isn't quite it: fluree-db-cli/Cargo.toml:14 declares [lib] name = "fluree_db_cli", so it can, it's just undesirable (the whole CLI in the wheel). A small shared crate once #2205 lands is the right home, as you suggest; worth an issue so the copy doesn't outlive its reason.
  • src/doc.rs:92-99 maps errors by string sniffing: e.contains(" 4") && is redundant with the status checks, "no ontology" matches no message fluree-db-doc produces, and cache="bogus" becomes a FlureeError("configuration: …") rather than an InvalidRequestError. Keeping the DocError through the detach and matching its variants would be sturdier.
  • API edges: auth_header without api_key is ignored silently (src/doc.rs:165); catalog=[("a.ttl",)] raises IndexError (doc.py:163) and catalog=("a.ttl", "b.ttl") reads as (file, class); the capacity waits (up to five minutes) go to tracing::info! (src/doc.rs:88), which the fluree.engine logger drops by default, and the docstring doesn't say so; Session::catalog_records() (session.rs:75) has no caller.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ one Session for both consumers rather than a second loop; catalog_records_of mirrors the CLI's record queries. ⚠️ two copies of the record predicates (doc_sources.rs:353 and request.rs:500) with no test tying them, and a second copy of #2205's account loading (acknowledged in the body).
  • Performance (speed first, memory second): ✔ the GIL is released for the whole read; ⚠️ one /v1/auth/token round trip per read() with an API key (inline). Wheel size: not measured here (debug build only), so the +4.7 MB is yours.
  • Deployment targets: ✔ fluree-db-doc's dependencies are pure Rust (hayro, image), so the manylinux build shouldn't need a system library; not run.
  • Testing: ⚠️ the seven new tests run by name and pass, and three of four mutations go red for the right reason; nothing covers a successful refresh, the account.toml rewrite, class / score on a mention row (the test never asserts them, and they're always None), or two text= reads in one ledger.
  • Conventions: ✔ conventional commits with the why; docs/getting-started/python.md gets its section and the docstring is the reference. ⚠️ sphinx -n -W not run here.

Verified locally at f45d92374 (a private target dir): cargo test -p fluree-db-doc 100 passed; cargo test -p fluree-db-cli --test integration -- doc_ingest_reads_with_an_http_reader doc_read_ 3 passed; cargo test -p fluree-db-cli --lib 269 passed; cargo clippy on fluree-db-doc, fluree-db-cli and fluree-db-python --features extension clean; uv venv --python 3.12 + maturin develop, pytest tests/test_doc_read.py 7 passed, the whole suite 384 passed, mypy python/fluree clean. Mutations, each restored: cache stored under a different key than read (red), catalog file sent whole (red ×2), refresh margin inverted (red, but because the stub answers the wrong JSON), #Class filter removed (red). Live, through url + api_key + auth_header="X-Fluree-API-Key" against fluree-nakaya-small (release fluree-small-5.2.5, three billed calls): a file read with usage.note == "604 tokens", to_turtle() and to_jsonld() inserted into a ledger (?o a nk:Occurrence counts 2, the docs' doc:Mention query 0), the same call again served from cache_dir with no request, and two text= reads. Not exercised: the flk_ exchange, fluree login and FLUREE_AI_API_KEY paths beyond the stub (no proxy credential here), claims() on a real rdf:Statement (the memo produced none), the release wheel size, the Sphinx build.

Requesting changes for the two 🔴s. The text= one is a line; the first is really the same decision as #2207's profile, and whichever PR carries it, I'd rather the Python rows not ship ahead of it.

Comment thread fluree-db-python/python/fluree/doc.py Outdated
``entity`` (the record or entity it names), ``score``, ``element``."""
rows = []
for node in self.nodes:
if _DOC + "Mention" not in node.get("@type", []):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔴 Must address before merge: mentions(), linked, mention_count, entity_count and the class / score columns read a vocabulary no reader emits, so with the real reader they're all empty.

This keeps nodes typed doc:Mention; :104 reads doc:mentionClass and :106 / :124 read doc:score. doc:mentionClass appears nowhere else in the repo, and doc:score nowhere in the Rust code or vocab.rs, only in this PR's Python stub. The counts come from reading.rs:180-185 (doc:Mention / doc:Entity) and linked from nif:entity (:188-198). Nakaya writes nk:Occurrence, nk:class, nk:score, nk:refersTo and nk:LocalEntity under https://example.org/nakaya-proposal# (fluree-nakaya/src/nakaya/vocab.py:16, graph.py:60-95), and reading.rs:55's PROFILES is empty, so nothing translates.

Confirmed live against fluree-nakaya-small with the docs' own shape of call: 604 tokens billed; reading.nodes holds two nk:Occurrence ("Jane Doe" with nk:class schema:Person, "Acme" with nk:refersTo <https://example.org/org/acme>) and one nk:LocalEntity; and mention_count == 0, entity_count == 0, linked == [], mentions() == [], claims() == []. After conn.create("readings").insert(reading.to_jsonld()), ?o a nk:Occurrence counts 2 and the query python.md shows (?m a doc:Mention ; nif:entity ?e) returns no rows. Even with the stub, mention["class"] is always None, and the test doesn't assert it (test_doc_read.py:128-131).

The CLI has the same empty table but prints the raw nodes, so it promises nothing; this API promises semantic rows. Two ways out, to be settled with #2207: ship the Nakaya profile in PROFILES (nk:Occurrence → doc:Mention, nk:refersTo → nif:entity, nk:LocalEntity → doc:Entity, plus whatever nk:class and nk:score become) before exposing mentions(), or drop class and score from the rows, say in the docs that the rows assume a reader speaking doc:, and assert class / score in the Python test once they exist.

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.

Agreed, and the live check made it obvious: an API that promises rows and returns [] for a reading that plainly has mentions is worse than one that only hands you nodes.

I took your second way out, the same call I made on #2207, since the reader's vocabulary is still marked as placeholders and a profile row today would pin names that are expected to move:

  • 6ccc732 makes mentions() vocabulary-neutral. A row is any NIF occurrence of the text (doc:Mention, nif:RFC5147String or nif:String, with nif:beginIndex), reading nif:anchorOf, the offsets, nif:entity and doc:sourceElement. The class and score columns are gone, since nothing defines them yet. test_a_nif_occurrence_is_a_mention_row_whatever_else_it_is has the stub answer with a NIF string and nothing else, and checks the row's text, offset and entity.
  • On the Rust side, the counts and doc:sourceElement use the same rule now (reading::is_occurrence, doc ingest: read with an HTTP reader ([doc.reader], --model, --cache) #2207's 3ae66a7, merged up in 7250135). So mention_count agrees with mentions(), and the stub's own-vocabulary mention gets its element.
  • The module docstring ("Rows and terms") and python.md now say the rows read NIF offsets and the pipeline's doc: terms, and that a reader's own terms are kept as written in reading.nodes and to_jsonld(). The doc:Mention SPARQL example in python.md is gone.

When the vocabulary settles, the profile row on #2207's reader::profile is what turns a reader's own link property into nif:entity, and linked and entity fill in for that reader with no change here.

Comment thread fluree-db-python/python/fluree/doc.py Outdated
)
if text is not None:
with tempfile.TemporaryDirectory() as tmp:
file = Path(tmp) / "text.txt"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔴 Must address before merge: every text= read is minted under urn:fluree:doc:text.txt, so two readings inserted into one ledger merge.

The temporary file is always text.txt; src/doc.rs:73-77 takes file_name() and document_iri(base_iri, "text.txt") (fluree-db-doc/src/ingest.rs:104) is the same for every text= call without doc_iri. Every node of the reading hangs under it: <doc>/entity/1, <doc>/reading#r-0, doc:sourceDocument, the doc:sourceElement <doc>-element-N.

Confirmed live: read(text="Jane Doe … Acme …") and read(text="John Smith … Globex …") both come back with doc:sourceDocument urn:fluree:doc:text.txt and share urn:fluree:doc:text.txt/entity/1 (Jane Doe in one, John Smith in the other) and urn:fluree:doc:text.txt/extraction/fluree-nakaya-small. ledger.insert(a.to_jsonld()); ledger.insert(b.to_jsonld()) then puts both memos' claims on one entity, and a CLI re-ingest of that IRI would retract both. No error, a wrong graph.

Deriving the IRI from the content closes it:

doc_iri = doc_iri or f"{base_iri}text/{hashlib.sha256(text.encode()).hexdigest()[:16]}"

(or require doc_iri= with text= and say so in the docstring), plus a test that two different text= reads get two IRIs.

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.

Good catch, a silent merge of two documents is exactly the wrong failure. 6ccc732 does what you suggested: with text= and no doc_iri=, the document is read under <base_iri>text/<first 16 hex of the text's SHA-256>, so the same text is the same document and two different texts never share a node. The temporary file is named after the digest too. test_two_texts_are_two_documents reads two texts and checks two IRIs with no node @id in common, that the same text again comes back under the first IRI, and that doc_iri= still names one outright. The docstring says the rule.

graph.map_err(|e| format!("{}: {e}", path.display()))
}

fn resolve(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 Should address: a reader can't be called without a credential, and a fluree login token is sent to whatever url= is given.

With url= alone (no api_key, no fluree login, no FLUREE_AI_API_KEY) resolve returns Err("sign in with fluree login…"), while the CLI sends without a credential when [doc.reader] has no key (fluree-db-doc/src/reader/client.rs:40-41). So read("memo.md", …, model="fluree-small", url="http://127.0.0.1:8000/extract") against a local Nakaya worker is refused, and the test itself has to invent api_key="k", auth_header="X-Api-Key" to talk to its stub (test_doc_read.py:148). The corollary is the one I'd fix first: with an account.toml present and a third-party url=, the account's Bearer goes to that URL (:181-183), which the CLI never does.

When url is given and no key is passed, consulting the login and the environment only if url is the account's own API (same origin as api_base_url), and otherwise returning Ok((url, None)), keeps both the local-worker case and the credential where it belongs.

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.

Agreed on both, and especially the second. A sign-in going to a URL it wasn't issued for is the one I'd never want to ship. 6ccc732 changes the resolution:

  • api_key with auth_header: that key, as is, to url.
  • api_key alone: see the next thread.
  • No api_key: this machine's fluree login, else FLUREE_AI_API_KEY, each only to its own service. A url elsewhere is called with no credential, which is what the CLI does for a [doc.reader] with no key.

test_a_url_with_no_credential_is_called_without_one covers your local-worker case, and test_a_sign_in_is_never_sent_to_another_service signs in to a different service and checks that the stub's url sees no authorization header. The docstring's "Signing in" section lists the three cases.

Comment thread fluree-db-python/src/doc.rs Outdated
return Ok((url, Some(credential)));
}
if let Some(key) = api_key {
return exchange_key(url, &key);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 Should address: api_key without auth_header doesn't mean the same thing in [doc.reader] and here.

In the CLI, api_key alone is Authorization: Bearer <key> to url (client.rs:42-43). Here it's an exchange at <origin of url>/v1/auth/token. A user who copies their [doc.reader] (url = "https://reader.example/extract", api_key = "…") into read(url=…, api_key=…) gets POST https://reader.example/v1/auth/token → 404 → FlureeError: https://reader.example/v1/auth/token: 404 the API key was refused, and nothing says auth_header="Authorization" was the missing piece.

Deciding by the key's shape would make the two agree: exchange only when key.starts_with("flk_") (the proxy's format, solo-proxy/docs/architecture.md:68), otherwise Bearer as-is like the CLI. And a line in the docstring.

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.

Agreed, a copied [doc.reader] should mean the same thing here. In 6ccc732 the key's shape decides, as you suggested: a Fluree AI API key (flk_…) is traded for an access token, and any other key is sent as Authorization: Bearer, exactly like [doc.reader] api_key. test_an_api_key_that_isnt_a_service_key_is_a_bearer_token sends api_key="plain-key" and checks it arrives as Bearer plain-key with no token call. The docstring says it in its second case.

graph.iter().any(|t| {
t.subject() == s
&& t.predicate().as_iri() == Some(type_p.as_str())
&& t.object().as_iri() == class

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 Should address: a file catalog isn't "the CLI's own read": the literals differ, so the request body and the reading-cache key differ.

The CLI loads a catalog file into an in-memory ledger and re-emits each value as Term::string(v.trim()) (fluree-db-cli/src/commands/doc_sources.rs:403-410): language tag and datatype dropped, whitespace trimmed. catalog_records_of keeps the literals as they are. So skos:prefLabel "Acme"@en goes out as "Acme" from the CLI and "Acme"@en from Python; the xt:instances graph differs, the body differs, the cache key (session.rs:129-137, hashed on the body) differs: a cache_dir shared between the CLI and Python pays twice, and the reader may read differently. There are also two copies of the predicate list, doc_sources.rs:353 (compact) and request.rs:500 (IRIs), with no test tying them.

The CLI's file branch could call catalog_records_of directly (no in-memory ledger for a file), the ledger branch keeps its queries, and doc_sources::RECORD_PREDICATES derives from request::RECORD_PREDICATES.

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.

You're right, and the shared-cache-pays-twice consequence is a good reason to make them identical rather than just close. Two steps:

  • doc ingest: read with an HTTP reader ([doc.reader], --model, --cache) #2207's 9ba6c63 already stopped the CLI dropping language tags and datatypes on catalog labels (that came out of your review there).
  • 0291dcc makes the CLI's file branch call request::catalog_records_of directly, with no in-memory ledger for a file. A catalog file is now selected by the same function the Python package uses, literals included, so the two send the same xt:instances graph and share cache entries. The ledger branch keeps its queries, now over request::RECORD_PREDICATES itself, so there's one predicate list and nothing to keep in step. The CLI's integration suite, including the #Class and language-tag test, is green on it.

Comment thread fluree-db-python/src/doc.rs Outdated

/// A fluree.ai API key traded for an access token. The service is `url`'s
/// origin when given, else `FLUREE_AI_URL`, else fluree.ai.
fn exchange_key(url: Option<String>, key: &str) -> Result<(String, Option<Credential>), String> {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Optional: a token is minted on every read() with an API key.

:178 / :189 call exchange_key per read, and on the service side handleAuthToken (solo-proxy/src/handlers/v1/auth.ts) does a deployment, account, webhook-secret and capability lookup per mint, for a token that lasts an hour. for f in files: fluree.doc.read(f, api_key=key, …) over 2,000 invoices is 2,000 POST /v1/auth/token. A OnceLock<Mutex<HashMap<(service, key), (token, expires_at)>>> reused while more than 60 s remain (the response carries expiresAt) is enough.

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.

Agreed, 2,000 token mints for 2,000 invoices is silly. 6ccc732 adds a process-wide OnceLock<Mutex<HashMap<…>>> keyed on (service, key), holding the token and its expiresAt, reused while more than 60 s remain. test_an_api_key_is_traded_for_a_token_once_an_hour makes two reads with one flk_ key and checks the stub saw /v1/auth/token once and then two reads with the exchanged token.

Comment thread fluree-db-python/src/doc.rs Outdated
path.display()
));
};
if seconds_left(&token).is_some_and(|s| s > REFRESH_MARGIN_SECS) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Optional: the refresh-and-save path, the copy of #2205, has no test, and the one mutation I tried goes red for the wrong reason.

The only login test (test_doc_read.py:170-183) writes a JWT expiring in 2100, so the refresh never runs and save_account (0600, atomic rename) is never exercised. I inverted the refresh margin (refresh on every call): the test went red, but with 200: refresh rejected, because the stub doesn't know how to answer a refresh. The copy itself matches origin/feat/fluree-login:fluree-db-cli/src/account.rs (same TOML keys, same grant_type=refresh_token POST, same 60 s margin, same 0600 + rename); the differences are that account (AccountSummary) isn't updated and invalid_grant isn't distinguished.

A test with an expired JWT and a stub /v1/oauth/token answering access_token / refresh_token, asserting the rewritten file, its mode and the rotated refresh token, would cover the part that will outlive #2205's merge.

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.

Fair, and thanks for checking the copy against #2205 line by line. 6ccc732 adds test_an_expired_sign_in_is_refreshed_and_saved. It signs in with an expired JWT and has the stub answer /v1/oauth/token with a new access token, a rotated refresh token and an updated account. It checks the order of calls (refresh, then the read), the refresh body (grant_type=refresh_token), the new bearer on the read, and the rewritten account.toml: new access token, refresh_token = "flk_rotated", the updated org_name, and mode 0600 on POSIX.

It also folds in the two differences you found. The account summary is updated from the refresh answer, and invalid_grant is distinguished: test_a_revoked_sign_in_says_to_sign_in_again expects a PermissionDeniedError saying the sign-in is no longer valid, with no read sent.

.unwrap_or_default();
let iri = doc_iri.unwrap_or_else(|| fluree_db_doc::ingest::document_iri(&base_iri, &name));
let (meta, parsed) =
fluree_db_doc::parse_file(&path, &name, &iri, doc_cache.as_ref(), None)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Optional: no vision escalation from Python, while the docs say the parse is the CLI's.

parse_file(…, None) passes no VlmReader; doc read passes one from [doc.vlm] (doc.rs:1470+). docs/getting-started/python.md:103-107 and the docstring say the document is parsed "exactly as fluree doc read does", so a scanned PDF or a .png yields an empty or partial text and an empty reading with no note (the CLI prints parsed.notes). Either say it in the docs ("no vision escalation") or expose vlm= and surface parsed.notes on Reading.

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.

Agreed. I took the "say it" half and surfaced the notes, rather than exposing vlm= from Python in this PR. In 6ccc732 the docstring and python.md say "Python does no vision escalation", and Reading.notes carries the parser's notes (pages it couldn't read, an email's attachments, and the like), so a scanned PDF says what it left out instead of returning an empty reading with no word. The "exactly as fluree doc read does" wording now applies to the read, not the parse.

Comment thread fluree-db-doc/src/reader/session.rs Outdated
};
let answer =
self.client
.read(&body, &self.model, self.cache.as_deref(), &|wait| {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

👍 Rebuilding the "{label}: {wait}" prefix inside Session::read rather than in the CLI is what makes the first commit a true move: the CLI's stderr is byte-for-byte what it was, and a Python caller gets the same label through on_wait. I diffed the two sides and ran the CLI's reader and read suites on this head to confirm there's no behaviour change hiding in the move.

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.

Thanks for diffing the two sides. That label was the one place a move could have quietly changed the CLI's stderr. It's still built inside Session::read after the merge that ports #2207's request sizing and cache key into Session (7250135), and the CLI's reader and read suites are green on that head.

- text= reads under <base_iri>text/<sha256[:16]> unless doc_iri= names
  one, so two texts never share a document's nodes.
- mentions() reads any node typed doc:Mention, nif:RFC5147String or
  nif:String with offsets: id, text, begin, end, entity, element. The
  class and score columns are gone, and claims() drops score. A reader's
  own terms stay in nodes / to_jsonld().
- Credentials: api_key with auth_header is sent as is. api_key alone is
  traded for a token only when it is a flk_ key, and otherwise sent as
  Bearer. With no key, the fluree login sign-in or FLUREE_AI_API_KEY goes
  only to its own service's origin, and a url elsewhere is called with
  no credential. auth_header without api_key is an InvalidRequestError.
- Traded tokens are cached per (service, key) for the process and reused
  while more than 60 s remain.
- The sign-in refresh writes back the rotated refresh token and the
  account summary (0600, atomic). invalid_grant says to run fluree login
  again (PermissionDeniedError).
- Typed errors: 401/403 -> PermissionDeniedError; bad arguments, a bad
  cache mode and a missing sign-in -> InvalidRequestError; otherwise
  FlureeError.
- catalog: a one-item tuple is a TypeError, and a bare pair of RDF files
  is two catalogs.
- Capacity waits log at warn on fluree.engine. Reading.notes carries the
  parse's notes (Python does no vision escalation).

Tests cover each case against the local stub.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016CjYmSfiNVsRZmcpMicDfq
aaj3f and others added 2 commits November 3, 2026 13:46
# Conflicts:
#	fluree-db-cli/src/commands/doc.rs
#	fluree-db-cli/src/commands/doc_reader.rs
#	fluree-db-doc/src/reader/client.rs
- A catalog file is now read by `request::catalog_records_of`, the same
  selection the Python package makes, rather than loaded into an
  in-memory ledger and re-emitted: both send the same records with the
  same literals, so their request bodies (and reading-cache keys) agree.
  The ledger branch's queries use `request::RECORD_PREDICATES`, the one
  list of record predicates.
- Python maps a reader's refusal from `DocError::Endpoint`'s status
  instead of parsing the message.
- `Session::catalog_records`, which had no caller, is gone (with the
  merge that ports the request sizing, the endpoint in the cache key,
  the no-text guard and the dry-run plan into `Session`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016CjYmSfiNVsRZmcpMicDfq
@aaj3f

aaj3f commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

Thank you, @arnaud-fluree. Running it live through the account path was really valuable, and the two 🔴s were both right. Everything is pushed, with a reply and commits on each thread. In short:

  • 🔴 Rows a reader actually writes: mentions() reads any NIF occurrence, the class / score columns are gone, and the docs say what the rows read and that a reader's own terms are kept as written (6ccc732). The counts use the same rule on the Rust side (doc ingest: read with an HTTP reader ([doc.reader], --model, --cache) #2207's 3ae66a7, merged up in 7250135). As on doc ingest: read with an HTTP reader ([doc.reader], --model, --cache) #2207, I'd rather the profile row wait until the vocabulary isn't marked as placeholders any more.
  • 🔴 text= IRIs derived from the text's SHA-256, with a two-texts test (6ccc732).
  • 🟠 Credentials: a sign-in only goes to its own service, a url with no key is called with none, and flk_… keys are exchanged while any other key is Bearer, matching [doc.reader] (6ccc732).
  • 🟠 One catalog selection: the CLI's file branch now uses catalog_records_of, and there's one record-predicate list (0291dcc).
  • 🟡 Tokens cached for their hour; the refresh path tested end to end, including the saved file and its mode; invalid_grant handled (6ccc732).
  • 🟡 No vision escalation: said in the docs, and Reading.notes surfaces what the parse left out (6ccc732).

From the smaller notes:

Also merged #2209 (and so #2207) up, and ported #2207's request sizing, the endpoint in the cache key, the no-text guard and the dry-run plan into Session (7250135). Gate on the pushed head: cargo test -p fluree-db-doc -p fluree-db-cli green, clippy clean including fluree-db-python --features extension, and on a maturin develop build pytest 394 passed, mypy python/fluree clean, sphinx-build -n -W clean. Would you mind taking another look when you get a chance?

@aaj3f
aaj3f requested a review from arnaud-fluree November 3, 2026 18:52
Base automatically changed from feat/doc-read to main November 3, 2026 20:06
@aaj3f
aaj3f merged commit 569e600 into main Nov 3, 2026
8 checks passed
@aaj3f
aaj3f deleted the feat/python-doc-read branch November 3, 2026 20:08
bplatz added a commit that referenced this pull request Nov 4, 2026
Brings #2247, #2232, #2246, #2248, #2245, #2230, #2205, #2231, #2255,
#2219, #2209, #2207, #2190, #2216, #2186, #2215, #2213, #2184, #2210,
#2206, #2198, #2187, #2183, #2200, #2193, #2199, #2196 and #2145 into next.

Resolutions:
- Novelty: main's fact-state trim (a cutoff plus a bounded sweep) and the
  dictionary's coverage watermark sit on next's graph slots and per-graph
  OrdMaps. A commit's reification links count toward coverage. Planner
  stats from segment sums decline under annotations, whose link deltas
  only the walk counts, and otherwise carry the indexed link counts.
- Stats-view identity: the index root's id reaches the snapshot through
  next's root decoder (`decode` takes the id, as `take_snapshot_metadata`
  does). `LedgerState::load_record` has a decoding-root form beside
  `load_decoding_root`.
- Transact: #2184's parallel-relationship check runs in next's link
  cascade, counting the `rdf:reifies` links on the retracted edge that the
  transaction does not retract itself. Main's bundle `edge_reifiers` is
  dropped, and `subjects_with_prior_rows` and
  `enforce_single_target_reifiers` stay deleted. The upsert pre-check
  takes main's dictionary probe and bounded seek.
- Query: geo search resolves the graph's POST tree once at open (pooled
  graphs keep their filter), an empty manifest when there is none.
  `branch_or_none` reads the dedicated branch, and the batched joins keep
  next's pooled lanes. The stats-view key hashes the root id.
- Indexer: `apply_dict_novelty` and `compact_forward_streams` take the
  cycle's compaction budget, so the term dictionary keeps its reserved
  share. `Prefetched` holds `ContentBytes`. `relocalize_sorted_commit`
  rewrites next's 20-byte types records.
- Disk cache: main's in-flight write registration, with an empty entry
  still read as crash debris that a write replaces. The process-wide
  eviction walk stays removed.
- Graph import (#2232): fenced CAS and publishes, the seed carries the
  record's namespace and fence, 32-bit graph ids and next's loaders. An
  import into a graph of an existing ledger refuses triple terms and edge
  annotations: the splice merges no triple-term dictionary yet.
- Iceberg: `create_iceberg_graph_source` goes with main (a source needs a
  mapping); the R2RML path keeps next's `model_instance`.
- CLI: main's shared import flags without the leaflet flags; `graph
  import` routes through next's process-wide server routing, and
  `upload_source_import` serves next's `Destination`. Doc sources read a
  ledger through the command's open instance.
- Tests: sibling ledger ids become distinct names, `genesis_ledger` is
  awaited, Cypher state dumps include each relationship's `rdf:reifies`
  link, and the graph-import arena test checks the refusal instead.
q-qp-p pushed a commit to q-qp-p/fluree-db that referenced this pull request Nov 8, 2026
`Session::plan`'s signature, ported in the fluree#2219 merge without a format
pass, failed `cargo fmt --check` on main (the fmt and testsuite-sparql
jobs).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016CjYmSfiNVsRZmcpMicDfq
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