Repository navigation
doc ingest: read with an HTTP reader ([doc.reader], --model, --cache) - #2207
Conversation
`--model <ID>` names the extraction model. An id a `[doc.reader]` lists in `models` reads each document whole with that reader; any other id names the language model `[doc.llm]` runs (default `doc.model`, then `[doc.llm] model`). A reader takes one RDF dataset per request (TriG; role graphs under https://ns.flur.ee/extract#: document, ontology, instances, request) and answers with JSON-LD. The request is built from what ingest already has: the parser's text and structure graph (elements with their offsets), the `--ontology` source as RDF, and each `--catalog` record's types, labels and short description. A document over 48,000 characters is read in several requests cut between elements; a request whose text would not fit one window beside the ontology and catalog is tiled into up to 16 windows between leaf elements. The answer's echoed document graph is dropped; the reading goes into the document's commit with offsets moved back into the document's text, IRIs minted per request kept apart across requests, every node stamped `doc:sourceDocument`, and reified statements typed `doc:Relation` (and `doc:asserted` when the reading states the triple with an IRI object). Re-ingest now also retracts every triple on nodes a reader minted under the document's IRI. A per-reader vocabulary table (none yet) can map a reader's terms onto the doc: vocabulary in one place. Billing is reported per document and per run (input tokens, prompt-cache reads/writes, fuel when metered), with the reader's ontology notes. A request is resent only on a 503 carrying Retry-After, at most four attempts and five minutes of waiting; answers are cached by request body. Also: JSON numbers and booleans in the structure graph keep their RDF types in the request (the JSON-LD adapter labels a native `@value` with no `@type` as xsd:string). Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016CjYmSGfnxzJgMSzBESNee
…ceElement) Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016CjYmSGfnxzJgMSzBESNee
… into feat/doc-http-reader # Conflicts: # fluree-db-cli/tests/integration.rs
…gy?" --model named the ontology from v4.2.0 until it named the extraction model, so an unchanged script passes an ontology there. A --model value that is an RDF file (.ttl, .nt, .jsonld, .json) or the name of a ledger in the project is now refused before it reaches any model: "--model x.ttl looks like an ontology (an RDF file); did you mean `--ontology x.ttl`?". Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016CjYmSGfnxzJgMSzBESNee
An endpoint that answers `{"error": {"error": "...", "message": "..."}}`
was printed as its raw JSON in the wait and failure messages. The nested
envelope is now read like the flat one: "unavailable: model is
temporarily unavailable".
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016CjYmSGfnxzJgMSzBESNee
arnaud-fluree
left a comment
There was a problem hiding this comment.
@aaj3f this is a solid piece of work, and at a design level no pushback from me: one TriG dataset per call with the xt: roles, cuts between elements and never inside one, a resend rule that only fires when the endpoint says nothing ran, answers cached by request body, and IRIs and offsets rebased per call all read as the right calls. I also ran the whole path against the real Nakaya gateway (details below), and the mechanics hold: the tokens the CLI reports equal the x-fluree-serialized-tokens header, the echoed graphs are dropped, --force is served from the cache with no call, and a --no-cache re-read replaces the previous reading without piling up. Two headline notes.
(1) What actually lands in the ledger with the only reader that exists today is Nakaya's placeholder vocabulary, untranslated. reader::profile's table is empty, so the reading is committed as nk:Occurrence / nk:LocalEntity / nk:refersTo under https://example.org/nakaya-proposal#, the result line says 0 mention(s) of 0 entities, the document node gets mentionCount 0, and nothing downstream (doc:Mention, nif:entity, doc:sourceElement, the gazetteer of a later LLM pass) sees it. The integration test's stub answers in doc: terms directly, which is why it can't show this. The hook the PR built is the right one; I think it needs its first row before this merges, or the docs need to say that a reader with no profile is stored as-is and feeds nothing. Details inline at reading.rs:55.
(2) The reader path doesn't yet honour everything ingest's surface promises. A --catalog file#Class loses its rdf:type in the request (a query-building slip), fluree config set doc.reader.models … writes a string that then breaks every doc command of the project, and --relations off|reified is silently ignored with a reader. Each is small and inline. Related but not blocking: the whole catalog travels in every call and the endpoint's 2,000,000-byte limit isn't modelled, so a large catalog gets a 413 on every document and is never read.
Full review below:
🔴 Request changes (three must-address items, each a few lines).
The core is careful and well tested. request.rs keeps blank nodes apart across role graphs, the clipping rule drops a container's text copies so nothing mismatches, client.rs sends nothing twice unless a 503 carries Retry-After (capped at four attempts and five minutes), and reading.rs drops the echo, stamps every node, and moves offsets and minted IRIs for a later call. I checked the load-bearing tests the body names: with a 429 added to the resend rule the non-resend test goes red; with doc:asserted never set two reading tests go red; and with the unbounded branch of retract_update replaced by FILTER(false) the integration test fails exactly as the body says (left: 2, right: 1, the old score surviving the re-read). The one test that doesn't hold its claim is the cut test (inline at request.rs:260).
By weight:
- 🔴
reading.rs:55: the profile table is empty, so Nakaya's reading is committed in its placeholder vocabulary and counts as zero mentions (inline, with a live run). - 🔴
doc_sources.rs:405: a#Class-scoped catalog is sent withoutrdf:type(inline, reproduced with a stub and--out-dir). - 🔴
config.rs:162:fluree config set doc.reader.models xwrites a string, and everydoccommand of the project then fails withexpected a sequence(inline, reproduced). - 🟠
request.rs:41: the 2 MB request limit isn't modelled; the catalog goes whole into every call (inline). - 🟠
doc.rs:537:--relations off|reifiedis ignored on the reader path (inline, reproduced). - 🟠
request.rs:260: the "never inside an element" test stays green when the rule is removed (inline, with the missing case). - 🟠
graph.rs:261: the unbounded sweep also takes a human annotation on a reader-minted node, and the docs' step 6 still describes the bounded rule (inline). - 🟡
request.rs:432: a formatting error becomessha256("")in the fingerprint (inline). - 🟡
doc_reader.rs:168: the reading cache key doesn't include the reader URL (inline). - 👍
client.rs:220: the resend rule is exactly what the gateway and the proxy contracts permit (inline, with two small riders).
Smaller notes with no good anchor:
docs/cli/doc.md"Caches" still describes the reading cache as "keyed on the crop's pixels, the prompt and the model"; it now also holds reader answers keyed on the request body.--cache offis accepted (doc_reader.rs:21) and useful to canceldoc.reader.cache, butcli.rsand the docs only nameontology|catalog.--dry-runwith--model <reader>still reads, and bills:doc.rs:657-668setsfluree = Nonebutread_documentruns. Same as the LLM path today, but a GPU call costs more, and the doc says "nothing is written", which a reader will take as "nothing is billed".doc_sources.rs:395-399drops the catalog labels' language tags (Term::string(v.trim())); solo's Nakaya client keeps them. No known effect on linking, but it's a difference between the two clients of the same service.request.rs:238-247: a document over 48,000 characters whose structure graph has no element with offsets fails with "an element is longer than a reader call takes", which names a thing that doesn't exist.client.rs:188-191:read_to_string()in ureq 3.4 caps the body at 10 MiB. The answer echoes the whole structure graph as expanded JSON-LD plus the reading, so a very structured 48,000-character document could approach it. No measured case;with_config().limit(..)would remove the doubt.
Adherence to repo commitments:
- Patterns/abstractions: ✔ the reader is a second extractor beside
[doc.llm]rather than a special case inside it, the request/answer/client split inreader/is clean, andreader::profileis the right seam for vocabularies;⚠️ it's empty for the only reader there is (inline). - Performance (speed first, memory second): ✔ no hot path touched; the reader path is network-bound.
⚠️ The catalog is re-serialized into every call and every window of a document (inline atrequest.rs:41). - Deployment targets: ✔ n/a for hosts; the CLI is the only consumer. The reader contract was cross-checked against
fluree-nakaya/docs/runpod-api.md,docs/gateway.md,solo-proxy/docs/grounding.mdand solo'sfluree-ner-grounded/src/nakaya.rs(headers, model ids, limits, error envelope): the headers and the resend rule match; the 2 MB limit and the vocabulary are the two gaps. - Testing:
⚠️ reader::{request,client,reading}and the integration test are good and non-vacuous for resend,doc:assertedand the retract (mutation-checked); the cut rule and#Classon the reader path aren't pinned, and the stub answers indoc:terms rather than in a reader's own (inline). - Conventions: ✔ conventional commits with the why in the body; fmt and clippy clean.
Verified locally at a20558dfa (a private target dir, cargo test -p fluree-db-doc 97 passed; cargo test -p fluree-db-cli --test integration -- reader doc_ingest 15 passed; --lib 2 passed; docs_coverage 5 passed; cargo clippy -p fluree-db-doc -p fluree-db-cli --all-targets --no-deps clean). Mutations, each restored afterwards: resend on 429 (red), doc:asserted never set (red), cut allowed inside an element (green, inline), unbounded retract branch disabled (red). Stub probes: #Class without types, config set models, --relations off, and a 74,214-character Markdown read in two calls with rebased offsets and part-1/part-2 IRIs. Live, against the Nakaya gateway with fluree-nakaya-small (release fluree-small-5.2.5, three billed calls): ingest of a four-line invoice with an ontology and a one-record catalog, 842 tokens reported by the CLI and by the header; 83 triples on the stamped nodes; --force served from the cache; --force --no-cache re-read with 83 triples after, not 166; next run unchanged. Not exercised: the solo-proxy path (Bearer, grounding_unavailable), --cache catalog on Large, a real 503 with Retry-After, and a request over 2 MB.
Requesting changes for the three 🔴s. The profile one is a decision about what the first reader's reading should look like in the ledger more than a bug; happy to talk it through, including whether nk:class / nk:value / nk:status get mapped or kept under doc: by namespace.
| pub vocabulary: Vocabulary, | ||
| } | ||
|
|
||
| const PROFILES: &[Profile] = &[]; |
There was a problem hiding this comment.
🔴 Must address before merge: with the only reader that exists, the reading is committed in a placeholder vocabulary that nothing in the pipeline reads, and the run reports zero mentions.
read_answer counts a mention only on doc:Mention (reading.rs:184) and a link only on nif:entity (:191-204), and doc_reader.rs:243-271 sets doc:sourceElement only on a doc:Mention. Nakaya writes none of those: its answer is nk:Occurrence, nk:LocalEntity, nk:refersTo, nk:localEntity, nk:class, nk:score, nk:value / nk:unit, nk:status / nk:accepted and nk:ExtractionRun under https://example.org/nakaya-proposal# (fluree-nakaya/src/nakaya/graph.py:69-93; vocab.py:16 calls them placeholders pending a maintainer decision). solo's client decodes exactly that vocabulary (fluree-ner-grounded/src/nakaya.rs, the NK_* constants). With PROFILES empty, nothing here translates.
I ran it: doc ingest docs -l inv --ontology ont/ex.ttl --catalog ont/daxin.ttl --model fluree-nakaya-small on a four-line invoice. Nakaya returned four occurrences (the invoice number, "Daxin Scientific Supply Co., Ltd." with nk:refersTo ex:daxin, a date, an amount), one local entity and two claims. The CLI printed 0 mention(s) of 0 entities (0 new), 2 relation(s), 842 tokens; the document node got doc:mentionCount 0, doc:entityCount 0; in the ledger, 14 nodes typed nk:Occurrence / nif:RFC5147String / nk:LocalEntity / nk:ExtractionRun, and SELECT ?m WHERE { ?m a doc:Mention }, nif:entity and doc:sourceElement all answer zero. The rdf:Statement half works (both are doc:Relation, the one with an IRI object is doc:asserted, and the ex:supplier edge is there), so the body's "reading committed" is true, but in nk: terms. The integration test answers in doc:Mention + r:refersTo and pins "1 mention(s) of 0 entities", so it can't see the gap.
I'd fill the hook for the ids this PR targets, and make the stub answer in that vocabulary so the test proves the translation. Illustrative:
const PROFILES: &[Profile] = &[Profile {
models: &["fluree-nakaya-small", "fluree-nakaya-large"],
vocabulary: Vocabulary {
terms: &[
("https://example.org/nakaya-proposal#Occurrence", "https://ns.flur.ee/doc#Mention"),
("https://example.org/nakaya-proposal#LocalEntity", "https://ns.flur.ee/doc#Entity"),
("https://example.org/nakaya-proposal#refersTo", "http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#entity"),
("https://example.org/nakaya-proposal#localEntity", "http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#entity"),
("https://example.org/nakaya-proposal#score", "https://ns.flur.ee/doc#score"),
],
namespaces: &[("https://example.org/nakaya-proposal#", "https://ns.flur.ee/doc#")],
},
}];What nk:class, nk:entityType, nk:value / nk:unit / nk:qualifier and nk:status / nk:accepted become is a decision I'd rather see made here than deferred. If the team prefers to wait for Nakaya to publish a stable vocabulary, then docs/cli/doc.md should say that a model with no profile is stored as-is and feeds neither the counts nor the mention graph; today it promises the opposite.
There was a problem hiding this comment.
You're right that this was the real problem, and thanks for running it live: a run reporting 0 mention(s) over a reading full of mentions is precisely the thing nobody would trust.
I went at it from the generic side rather than adding the first table row. 3ae66a7 makes "is this a mention" vocabulary-neutral (reading::is_occurrence): a node is a mention when it's typed doc:Mention or when it's a NIF string (nif:RFC5147String, nif:String, nif:Phrase, nif:Word) that carries nif:beginIndex. Both the counts and doc:sourceElement use that one test now, so a reading in a reader's own classes still reports its mentions and gets them placed in the structure. The stub in the integration test now answers in its own vocabulary (r:Occurrence + nif:RFC5147String, r:refersTo, r:score) rather than in doc: terms, which is the gap you pointed at, and a_nif_occurrence_in_a_readers_own_terms_counts_as_a_mention pins the rule in the crate.
Why not the table row: the reader's terms are still marked as placeholders by their owner, so a row today would pin names that are expected to move, in a public crate. I'd rather the hook stay empty for now and the docs say plainly what happens without one. That's the new "A reader's own terms" bullet in docs/cli/doc.md: the reading is stored as the reader wrote it, mentions are read by NIF type, and a link through a property of the reader's own is stored but isn't seen by the entity counts or nif:entity queries. When the vocabulary settles, the row is a small change against reader::profile, and the nk:class / nk:value / nk:status mapping-vs-namespace question you raised is the right one to settle then. Happy to talk it through if you'd rather see the row land before merge anyway.
| } | ||
| let query = serde_json::json!({ | ||
| "@context": fluree_db_doc::model::query_context(), | ||
| "where": [anchor(("@type", "?t"))], |
There was a problem hiding this comment.
🔴 Must address before merge: a #Class-scoped catalog is sent without any rdf:type, so the reader never sees the records' classes.
anchor (:373-379) builds { "@id": "?s", <extra> } and then, when source.class is set, overwrites "@type" with the class. For the types query that extra is ("@type", "?t"), so with #Class the pattern becomes { "@id": "?s", "@type": "<Class>" }: ?t is never bound, row_cell(&row, 1) is None, and the continue at :409-411 drops every row silently.
Reproduced with the PR's binary, a stub reader and --out-dir: with --catalog ont/entities.ttl the xt:instances graph in the request carries <acme> rdf:type schema:Organization; with --catalog ont/entities.ttl#schema:Organization it carries Acme's two labels and no rdf:type at all. Nakaya links by class (nk:class, nk:entityType), and the body says each record is sent with "types, labels and short description", which stops being true as soon as the catalog is scoped. The integration test doesn't cover #Class on the reader path.
The subjects are already scoped by the label queries, so the types query doesn't need the scope:
let query = json!({
"@context": fluree_db_doc::model::query_context(),
"where": [{ "@id": "?s", "@type": "?t" }],
"select": ["?s", "?t"]
});with the existing subjects.contains(&s) keeping the filtering. A --catalog ont/entities.ttl#schema:Organization case in the integration test, asserting rdf:type in the captured body, would pin it.
There was a problem hiding this comment.
Good catch, and the --out-dir repro made it obvious: the #Class scope written into anchor replaced the ?t binding, so every row fell through the continue.
Fixed in 9ba6c63. The types query is now unscoped ({ "@id": "?s", "@type": "?t" }), since the label queries have already chosen the subjects, and only types of those subjects are kept. While I was in there I also picked up your note about doc_sources.rs:395-399: labels now keep their language tag and datatype (row_literal) rather than being flattened through Term::string. doc_ingest_reader_sends_a_scoped_catalog_with_types_and_language_tags reads the request body and checks both, with --catalog ont/entities.ttl#schema:Organization.
| /// The model ids this endpoint serves, as `--model` names them. Sent | ||
| /// with each request as `X-Fluree-Model`. | ||
| #[serde(default, skip_serializing_if = "Vec::is_empty")] | ||
| pub models: Vec<String>, |
There was a problem hiding this comment.
🔴 Must address before merge: the one configuration tool the docs name can't set models, and using it breaks every doc command of the project.
docs/cli/doc.md says the [doc] table is "set with fluree config set", and models is a Vec<String>. config set only writes a bool, an integer, a float or a string (config_cmd.rs:155-157), so fluree config set doc.reader.models stub writes models = "stub". Reproduced: the command answers Set 'doc.reader.models' = 'stub', and the next fluree doc ingest … --model stub fails with error: …/.fluree/config.toml: [doc] section: invalid type: string "stub", expected a sequence in reader.models, exit 1. Every doc subcommand loads DocConfig, so the project is unusable until the file is edited by hand. The error is at least loud, but the documented path leads straight into it.
The environment variable already accepts a comma-separated list (FLUREE_DOC_READER_MODELS), so a deserialize_with that takes a string or a sequence would make the two agree:
#[serde(default, deserialize_with = "string_or_list")]
pub models: Vec<String>,plus a test that goes through config set and then doc ingest. Commenting here because config_cmd.rs is outside this diff's hunks.
There was a problem hiding this comment.
Agreed, a documented path that leaves the project unusable is the worst kind of error, even if it's a loud one.
007879c makes models take either a list or a string, split on commas, the same as FLUREE_DOC_READER_MODELS already does (string_or_list in config.rs). So fluree config set doc.reader.models "a,b" writes a string that now reads back as two models, and files written as a TOML list keep working. Pinned by reader_models_take_a_list_or_a_comma_separated_string, and end to end by doc_reader_configured_with_config_set_reads, which runs config set and then reads through the stub.
| impl Default for Limits { | ||
| fn default() -> Self { | ||
| Self { | ||
| request_chars: 48_000, |
There was a problem hiding this comment.
🟠 Should address: the endpoint's 2,000,000-byte request limit isn't modelled, and the whole catalog goes into every call, so a large catalog gets a 413 on every document after the upload.
Limits knows request_chars (48,000), windows (16) and window_tokens, but not the byte limit the contract states (fluree-nakaya/docs/runpod-api.md, the limits section; solo-proxy/docs/grounding.md answers 413 payload_too_large). solo refuses before sending (nakaya.rs:180, check_limits). Here the xt:instances graph is serialized whole into each request-N.trig, beside the structure graph (I measured 212 KB of structure for 48,000 characters of Markdown). Back-of-the-envelope, not measured against the gateway: a catalog of ~3,000 records (Nakaya's own linking pilot goes to 3,250) at about three N-Triples per record is 1.4-2 MB on its own, in every call. The result is a 413 on each document, the document not stamped, and the same failure on every later run, with nothing naming the cause.
Measuring body.len() in read_document and refusing before sending with a message that says why ("catalog of N records is X MB, the reader takes 2 MB; scope it with #Class") would turn this into a one-line diagnosis. Cutting parts by bytes as well as by characters is the fuller fix.
There was a problem hiding this comment.
Agreed, and I took the fuller fix since the diagnosis alone would still leave a large document stuck. In c8f642c:
Limitshasrequest_bytes(2,000,000), andStructure::requestsbuilds and sizes every body before the first call is sent, so a document never gets halfway and then fails.- A body over the limit gets re-planned in smaller parts, in proportion to how much of the body the document text takes up (a few rounds at most).
- When the ontology and catalog alone leave less than a tenth of a call for the document, nothing is sent and the document fails with the one-line diagnosis you suggested:
<file>: a request would exceed the reader's 2000000 bytes: the ontology is N bytes and the catalog M bytes (K records), and both are sent with every call. Scope the catalog to the classes this document needs (FILE#Class, ledger#Class), or split it.
a_request_over_the_byte_limit_is_cut_smaller and a_catalog_too_large_for_any_request_is_refused_with_its_size cover the two branches, and the docs have a "Request size" bullet. I didn't do anything smarter about the catalog travelling whole in every call. Trimming it per part would change what the reader is given to link against, and I think that deserves its own conversation.
|
|
||
| /// A reader's account of a document in the shape the language-model path | ||
| /// reports and commits: its nodes, and counts in the same columns. | ||
| fn read_extracted(mut read: doc_reader::Read) -> Extracted { |
There was a problem hiding this comment.
🟠 Should address: --relations off|reified is silently ignored on the reader path.
doc.rs:260-263 copies the mode into policy.relations, but read_extracted puts every node of the reading into graph.nodes without filtering, and nothing in doc_reader.rs reads relations. Reproduced with a stub answering one entity, one rdf:Statement and its asserted edge: doc ingest … --model stub --relations off, then SELECT ?s WHERE { ?s schema:worksFor <acme> } returns one row and ?r a doc:Relation returns one row. The option's help ("off: entities alone") is false for a reader.
Either apply it here (drop the rdf:Statement nodes and the asserted edges from reading.nodes by mode) or refuse --relations other than direct with a reader, the way --cache is refused without one.
There was a problem hiding this comment.
Confirmed, and thanks for the repro. I went with applying it rather than refusing it, since off and reified are both meaningful for a reader.
1ff7697 adds reading::apply_relations: direct leaves the reading as is, reified drops the asserted IRI edges and doc:asserted but keeps the doc:Relation nodes, and off drops those too. read_extracted now gets the policy's mode. It's pinned in the crate (relations_off_or_reified_take_away_what_they_should) and end to end by doc_ingest_reader_honours_relations_off_and_reified, which runs all three modes against the stub and counts both the edge and the relation.
| let splits = |c: usize| { | ||
| self.spans | ||
| .values() | ||
| .any(|s| (!leaves_only || s.leaf) && s.begin < c && c < s.end) |
There was a problem hiding this comment.
🟠 Should address: the cut tests don't pin "never inside an element"; with the rule removed they stay green.
I replaced this predicate with false (so splits refuses nothing) and ran cargo test --lib reader::request: 9 passed. The three cut tests only use flat leaves, or a container longer than one call, which are the cases where the rule and its absence produce the same cut. The missing case is two sections of 10 characters with two leaves each and max = 15: the rule cuts at 10 (the section boundary), the mutation at 15 (clipping the second section although a clean cut existed). One test with that shape would make the body's claim hold.
There was a problem hiding this comment.
Fair, the test claimed more than it checked. 2cba81b adds exactly the shape you described, a_cut_backs_off_to_a_container_boundary_when_there_is_one: two 10-character sections with two leaves each and a limit of 15, expecting [(0,10), (10,20)]. With the predicate replaced by false it goes red (the mutation cuts at 15), so the "never inside an element" claim is pinned now.
| UNION\n \ | ||
| {{\n \ | ||
| ?s doc:sourceDocument <{iri}> . ?s ?p ?o\n \ | ||
| FILTER ( STRSTARTS(STR(?s), \"{iri}/\") || STRSTARTS(STR(?s), \"{iri}#\") )\n \ |
There was a problem hiding this comment.
🟠 Should address: the unbounded sweep also takes a human annotation on a reader-minted node, and the docs still describe the bounded rule.
The LLM path mints <doc>-relation-N, <chunk>-mention-N and urn:fluree:doc:entity/<hash> (extract.rs:743, :874, :893), so it stays under the predicate-bounded sweep and #1868's concern is kept there. But a reviewer's note on a relation, which was #1868's motivating case, placed on <doc>/extraction/fluree-nakaya-small#r-0 now disappears on the next re-ingest, with no warning. The code comment owns that; docs/cli/doc.md step 6 ("What a run does") still says only what the pipeline wrote is retracted.
I'd at least say it in the docs. If it's worth bounding, one option is to keep the sweep by subject but exclude predicates outside the reader's, nif:, rdf:, doc: and the requested ontology's namespaces, so a human predicate on a minted node survives. The mutation check on this branch (replacing it with FILTER(false)) does turn the integration test red, so the behaviour is pinned either way.
There was a problem hiding this comment.
I think you're right that this was the one place the reader path quietly gave back what the bounded sweep bought us, and a reviewer's note on a relation is exactly #1868's case.
c8f642c bounds it the way you suggested, but by recording instead of guessing namespaces. The document node now lists the predicates the reader wrote outside the pipeline's own as doc:readerPredicate (graph::reader_predicates), and the sweep's second branch only retracts those from reader-minted nodes (<doc> doc:readerPredicate ?p . ?s doc:sourceDocument <doc> . ?s ?p ?o, plus the <doc>/… / <doc>#… subject filter). The pipeline's own predicates on those nodes still go through the first branch as before. So a predicate someone adds to a minted node survives unless the reader itself writes that same predicate, and I think that's the right line.
The integration test now adds an rdfs:comment to a reader-minted mention between the reads and checks it's still there after --force --no-cache. With the old unbounded branch put back, that assertion goes red (left: 0, right: 1), and the existing "old score is gone" assertion still holds. The docs' step 6 and the vocabulary table say all of this now.
| let mut g = graph.clone(); | ||
| g.sort(); | ||
| g.dedupe(); | ||
| fluree_graph_format::format_ntriples(&g).unwrap_or_default() |
There was a problem hiding this comment.
🟡 Optional: a formatting error here becomes a fingerprint of the empty string.
format_ntriples(&g).unwrap_or_default() feeds fingerprint (doc_reader.rs:81-89). Two different ontologies that both fail to format are "unchanged" to each other, and the document is skipped on the next run. Returning the Result and propagating it keeps this on the loud side.
There was a problem hiding this comment.
Agreed, quiet is the wrong side to fail on here. In c8f642c canonical_ntriples returns a Result and doc_reader::setup propagates it, so a graph that can't be written fails the setup rather than hashing as sha256("").
| } | ||
| let key = DocCache::reading_key( | ||
| &format!( | ||
| "reader|{}|{}", |
There was a problem hiding this comment.
🟡 Optional: the reading cache key has the model and the cache mode but not the reader URL.
Two endpoints serving the same id, say fluree-nakaya-small through the gateway and through solo-proxy, or a dev and a prod host, share answers under .fluree/cache/doc/. Adding setup.client.url() to the key closes it.
There was a problem hiding this comment.
Yes, two endpoints serving one id are two readers. In c8f642c the key is reader|<url>|<model>|<cache> plus the body (answer_key). The docs' "Caching" bullet and the "Caches" section now say what the reading cache holds for a reader.
| }); | ||
| } | ||
| let message = error_message(&text); | ||
| let retry_after = (status == 503) |
There was a problem hiding this comment.
👍 This is exactly the rule the contracts allow: a 503 with Retry-After is the gateway (fluree-nakaya/docs/gateway.md) and the proxy (grounding.md, grounding_unavailable) saying nothing ran, and everything else may have been billed. With the cap at four attempts and 300 s and the clamp at 60 s, two attempts cover a cold Large start. Adding a 429 to the rule turns a_503_without_retry_after_and_any_other_error_are_not_resent red, so it's pinned.
Two riders, neither blocking. Retry-After in its HTTP-date form (RFC 9110 allows it) doesn't parse here and is treated as absent, so the comment is really "a numeric Retry-After"; Nakaya and the proxy only send integers today. And the test's reason for not resending a 429, "the read may have run", isn't true through solo-proxy, where 429 rate_limit_exceeded is explicitly "nothing ran, Retry-After passed through" (grounding.md); the choice is still safe, but a resend on 429 + Retry-After would be legitimate on that transport.
There was a problem hiding this comment.
Thanks, and both riders were fair.
07ed2df reads Retry-After as either delay-seconds or an HTTP-date, counted from now with a one-second floor (retry_after_secs, tested with both forms and a date in the past). It also fixes the test comment: it now says only a 503 with Retry-After is resent and that the rule covers no other status, rather than giving "the read may have run" as the reason for a 429, which, as you say, isn't true everywhere.
On whether a 429 with Retry-After should join the rule: you're right that some endpoints promise nothing ran. But the slot can point at any HTTP endpoint, and I'm not sure every one of them makes that promise, so I've left the rule at 503 for now while I settle it. If we add it, it's a one-line change plus flipping the test you mutated. Related: a non-2xx answer is now typed (DocError::Endpoint { model, status, message }), so a caller can tell a refused credential from a refused request without parsing the message.
… tags With `--catalog file#Class`, the types query reused the label queries' scoped anchor, whose "@type" then replaced "?t": nothing bound, every row dropped, and the request carried the records' labels without any rdf:type. The types query is unscoped now (the label queries already chose the subjects). Labels also keep their language tag or datatype instead of becoming plain strings. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016CjYmSfiNVsRZmcpMicDfq
`fluree config set doc.reader.models x` writes a string, and the slot
wanted a sequence, so every `doc` command of the project then failed to
load its config ("expected a sequence in reader.models"). `models` now
takes either, a string split on commas as FLUREE_DOC_READER_MODELS is.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016CjYmSfiNVsRZmcpMicDfq
The run counted a mention, and set doc:sourceElement, only on a node typed doc:Mention, so a reader writing its own classes reported "0 mention(s)" for a reading full of them. A mention is now also any NIF string (nif:RFC5147String, String, Phrase, Word) carrying nif:beginIndex, which is how a reader marks a span whatever else it calls it (reading::is_occurrence, used by the counts and by doc:sourceElement). The integration stub answers in its own vocabulary now, as a reader does, rather than in doc: terms. The docs say what happens to a reader's terms: stored as written unless a vocabulary table for that model maps them (none ships yet), mentions read by NIF type, links by nif:entity. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016CjYmSfiNVsRZmcpMicDfq
The reading went into the commit whole whatever --relations said, so
`off` ("entities alone") still wrote the reader's relations and the edges
they asserted. reading::apply_relations now applies the mode: `reified`
keeps each doc:Relation but takes away the edge it asserted (and its
doc:asserted), `off` takes away both; a literal value is never a
relation's edge.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016CjYmSfiNVsRZmcpMicDfq
…t sees it The cut tests used flat leaves, or a container longer than one call, where the rule and its absence cut the same way; with the predicate replaced by `false` they stayed green. The new case (two sections of two leaves, a limit that falls inside the second) cuts at the section boundary only while the rule holds. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016CjYmSfiNVsRZmcpMicDfq
…, takes larger answers
- `Retry-After` is read as delay-seconds or as an HTTP-date (RFC 9110),
counted from now; the resend rule is unchanged (503 only).
- A non-2xx answer is `DocError::Endpoint { model, status, message }`, so
a caller can tell a refused credential from a refused request.
- The answer is read with a 64 MiB limit instead of ureq's 10 MiB
default: it echoes the structure graph beside the reading.
- The test comment on the no-resend case now names the actual rule.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016CjYmSfiNVsRZmcpMicDfq
…ead nothing - Requests are built and sized before the first call: a body over the reader's 2,000,000 bytes is re-planned in smaller parts, and when the ontology and catalog alone leave too little room nothing is sent and the document fails naming both sizes and suggesting `#Class` scoping. - The document node lists the predicates a reader wrote outside the pipeline's own (`doc:readerPredicate`); a re-ingest retracts only those from reader-minted nodes, so a human annotation on one survives. The integration test adds such a note and checks it after a re-read (red with the previous unbounded branch). - The reader's answer cache key includes the endpoint URL. - `canonical_ntriples` returns a Result, so a graph that can't be written fails the setup instead of hashing as the empty string. - A text with no structure elements is cut between words. - `--dry-run` with a reader plans the calls (and cache hits) and sends nothing; `--out-dir` still writes the requests. - Docs: request size, the bounded sweep in step 6 and the vocabulary, the reading cache holding reader answers, `--cache off`, `--dry-run`. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016CjYmSfiNVsRZmcpMicDfq
An empty file, or a scanned PDF with no vision model, used to go out as one call carrying the ontology and the catalog, billed for an empty reading. It now takes no call; ingest and read both see an empty reading. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016CjYmSfiNVsRZmcpMicDfq
|
Thank you, @arnaud-fluree, this was a really thorough review. The live run against a real reader, plus the mutation checks, caught things the stub couldn't have. Everything is pushed, and I've replied on each thread with the commits. In short:
And the smaller notes with no anchor:
The one thing I've left open is a 429 with |
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.
Stacked on #2206 (which frees
--model), so the diff here reads best against that branch.This adds a second kind of extractor to
fluree doc ingest: an HTTP reader, an extraction model that reads a whole document at once and takes its inputs as RDF, rather than an OpenAI-shaped LLM asked about one chunk at a time.--model <ID>now names the extraction model. If a[doc.reader]lists that id inmodels, each document is read whole with that reader. Any other id names the language model[doc.llm]runs, so--model gpt-5-miniworks as you'd expect too. The default isdoc.model, then[doc.llm] model, so nothing changes for existing setups.The request (
fluree-db-doc/src/reader/request.rs) is one TriG dataset per call. Its named graphs give each input a role underhttps://ns.flur.ee/extract#:document: the document node with its full text asnif:isString, plus the parser's elements with their offsets (we already have both from our own parse);ontology: the--ontologysource as it is (a file read directly, a ledger exported);instances: the catalog, meaning each--catalogrecord's types, labels and short description, and nothing else, since the whole catalog goes into every window;request: windows, when they're needed.The model id goes in
X-Fluree-Model,--cachegoes inX-Fluree-Cache, and the answer is asked for as JSON-LD. A document over 48,000 characters is read in several calls, cut between elements and never inside one. A container longer than one call (a big table, say) is the one thing that gets clipped, and it loses its text copies so nothing mismatches. When a call's text wouldn't fit one window beside the ontology and catalog (going by a deliberately high token estimate; the reader enforces the real limit before doing any work), it's tiled into up to 16 windows between leaf elements.The answer (
reader/reading.rs) is a dataset: the document graph we sent, echoed under the document's IRI, and the reading in graphs of its own. We drop the echo. The reading goes into the document's commit:<doc>/…,<doc>#…) are kept apart per call, so two calls'…/entity/1stay two entities;doc:sourceDocument;rdf:Statementis typeddoc:Relation, and markeddoc:assertedwhen the reading also states its triple with an IRI object, so the existing edge cleanup on re-ingest just works.graph::retract_updatealso now takes every triple on a stamped node minted under the document's IRI. Those nodes are entirely the pipeline's, whatever terms the reader wrote them in, and without this a reading would pile up on each re-ingest. The predicate-bounded sweep everywhere else is unchanged (#1868's concern). There's also a hook for a per-reader vocabulary table (reader::profile, empty for now), so a reader whose terms aren'tdoc:'s can be translated in one place rather than scattered through the code.What's reported: each document line gets the tokens the reader billed (
X-Fluree-Serialized-Tokens), plus prompt-cache reads/writes and fuel when the endpoint reports them. The run's last lines total them and say what the reader set aside or adapted in the ontology (X-Fluree-Ontology-Not-Shown/-Adapted). Nothing billing-related is written into the ledger.Resends are deliberately narrow (
reader/client.rs). A request is resent only on a 503 carryingRetry-After, which is the endpoint saying it had no capacity yet (a model still starting, a full queue). That's capped at four attempts and five minutes of waiting, and each wait is shown on stderr as it starts. Nothing else is resent, not a timeout, a dropped connection, or a 503 without the header, because any of those may follow a read that actually ran and was billed. Answers are also kept in the existing reading cache by request body, so--forcewith nothing changed doesn't pay twice;--no-cachereads afresh.One thing I tripped over:
fluree-graph-json-ld'sprocess_literaltyped an expanded{"@value": 0}with no@typeasxsd:stringwhile keeping the native integer, soformat_ntripleswrote"0"and a strict reader refused it (doc:columnIndex must be an xsd:integer). That's #2211, fixed on its own in #2212. This PR keeps a small workaround in the reader's ownparse_jsonldso it doesn't depend on #2212's merge order; once #2212 lands, the workaround is redundant and can go.Tests:
reader::request(cuts never inside an element, clipping, a leaf too long refused by name, windows under a big catalog, blank nodes kept apart across role graphs, numeric literals keep their types),reader::clientagainst a local stub (headers, usage parsing, a 503 +Retry-Afterresent and reported, a 503 without it plus 504 and 429 not resent, the attempt cap), andreader::reading(echo dropped, stamping,doc:Relation/doc:assertedonly with an IRI object, offsets and minted IRIs moved for a later call, a vocabulary table, compacted answers).doc_ingest_reads_with_an_http_reader_and_a_reread_replaces_the_reading(integration.rs) runs the whole path against a stub reader: the request's roles and headers, the per-document and run token lines, a--forcererun answered from the cache with no call, then a--no-cachere-read that replaces the reading and takes its asserted edge with it, then an unchanged document not read again. I checked it isn't vacuous: with theretract_updatechange reverted, the old reading's score survives the re-read and the test fails.cargo test -p fluree-db-doc(95 passed),cargo test -p fluree-db-cli(all suites passed),cargo clippy -p fluree-db-doc -p fluree-db-cli --all-targets --no-depsclean. I also ran it end to end against a real reader endpoint on a sample invoice: one call, 964 tokens, reading committed.What this doesn't do yet:
doc.remote-style sign-in for the reader (the credential seam isdoc_reader::credential);fluree doc readfor a single file with no project, which is next and builds on this; and literal-object asserted triples aren't cleaned up on re-ingest, which is the same as the LLM path today, since itsdrop_unsupported_edgesonly handles IRI objects.🤖 Generated with Claude Code
https://claude.ai/code/session_016CjYmSGfnxzJgMSzBESNee