Repository navigation
feat(doc): read through the machine's Fluree AI sign-in ([doc.reader] account = true) - #2260
Conversation
…= true) With `account = true` the reader's credential is this machine's `fluree login` (a Bearer token, renewed before each document so a run longer than the hourly token keeps going), and `url` defaults to the account's own reader at `<api base>/grounding`. Not signed in, the run says to `fluree login`; a 401 says to sign in again. FLUREE_DOC_READER_ACCOUNT sets it from the environment. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016CjYmSGfnxzJgMSzBESNee
# Conflicts: # fluree-db-cli/src/commands/doc.rs # fluree-db-cli/tests/integration.rs
A 401 from the account's reader (config_stale after the account's configuration changed, most often) renews the token with account::session(force) and sends the document again, once. Calls the first try answered come from the reading cache when there is one. Also follows #2205's session(http, force) signature. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016CjYmSfiNVsRZmcpMicDfq
… on a 401 Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016CjYmSfiNVsRZmcpMicDfq
jdorety
left a comment
There was a problem hiding this comment.
Review of 5817b63. I reproduced every finding below with temporary integration tests (none committed).
🔴 Blocking
1. A 401 retry re-reads the whole document, so calls already answered are sent and billed again (doc_reader.rs:115-129)
After a 401, read_document calls session.read again from the first part. Parts that were already answered are only skipped if the reading cache has them.
- Without a cache (
--no-cache, no project or global dir, or a failedstore_reading): with a 2-part doc where the stub answers 200 then 401, the reader received grounding ×2, exchange, grounding ×2. Part 1 was billed twice. This breaks the rule indocs/cli/doc.mdthat nothing else is resent because a failure "may follow a read that ran and was billed". - Reported usage is wrong with or without a cache. Without a cache:
2 call(s), 2,064 tokens, but 3 calls succeeded. With a cache:1 from cache, 1,032 tokens, but 2 calls were billed. - Per-document
renewdoesn't prevent this. A long multi-call document, with up to 5 minutes of 503 waits per call, can outlast the token, andconfig_stalecan arrive between any two calls.
Fix: retry only the refused call. For example, give ReaderClient::read a renewal callback that it runs once on a 401 before resending that one request.
2. A project's config can send the machine-wide account token to any URL (doc_reader.rs:28-40)
With account = true the token comes from the global fluree login, but url is used as written. [doc.reader] is read from the project's .fluree/config.toml, which is found by walking up from cwd. I reproduced it: a project config with account = true and a foreign url (the account's api_base_url on a different host, no env vars set) sent Authorization: Bearer <account token> to that URL. A cloned repo could do the same. Before this PR, a project file could only route credentials that the same file or the user's env supplied.
Fix: in account mode, reject a url whose scheme/host/port differs from api_base_url, or accept the override only from env or the global config.
🟡 Should fix in this PR
3. The new code paths have no test. I made these three changes together, and all 27 doc_ integration tests and all 276 CLI unit tests still passed:
- deleting
doc_reader::renew(&reader).await?(doc.rs:812); - removing the
if setup.accountguard on the 401 retry, so a reader using its own key would attempt an account token exchange; - removing the "run
fluree loginagain" hint.
Suggested tests:
- an ingest where the token is close to expiry: an exchange must come before the second document;
- a non-account reader that gets a 401: one request, no
/oauth/; - an account reader refused twice: grounding, exchange, grounding, then the hint.
🟢 Non-blocking
4. The "sign-in refused" hint is chosen by matching text, so it appears on errors that aren't 401s (doc_reader.rs:130-135)
error_message joins error and message with ": ". A 502 whose body is {"error":"upstream_error","message":"401 Unauthorized from model host"} printed hint: the sign-in was refused; run fluree login again, though the sign-in was fine. Match on DocError::Endpoint { status: 401, .. } instead.
Checked, no issue
Handle::current().block_oninsideread_documentis safe. Both callers run it insidespawn_blockingon the multi-threaded runtime.- The Python bindings don't read
DocConfig, so an emptyurlin account mode doesn't reach them.
… the account's API
A 401 used to re-read the whole document, so calls already answered were
sent and billed again when no reading cache held them, and the run's usage
report was wrong either way. The renewal now lives in ReaderClient: a client
given a Renewal answers a 401 by renewing once and resending that call
alone; a second 401 is the caller's error. read()'s signature is unchanged.
With account = true, a [doc.reader] url on another scheme, host or port
than the sign-in's api_base_url is refused before anything is sent, since
the section may come from a project's .fluree/config.toml.
The "sign-in refused" hint now matches DocError::Endpoint { status: 401 }
instead of the message text, and a failed renewal surfaces its own error.
Tests: the client renews once and resends one call; a two-call document
refused on its second call resends only that call and reports 2 calls; an
account refused twice gets the hint after one renewal; a reader with its
own key that gets a 401 sends one request and no exchange; a 502 that
mentions 401 gets no hint; an ingest renews the token before each
document; a url off the account's API is refused.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thank you, @jdorety, this is a really careful review, and the repros made each of these easy to confirm. All four are right, and they're fixed in a1cd4e2 (with 🔴1, the 401 retry re-reading the whole document. You're right that the cache was carrying the correctness here, and only when there was one. The renewal now lives in the client instead of around 🔴2, a project config sending the account token anywhere. I went with your first option. With 🟡3, tests. All three of yours are in, plus the two above and one for 🟢4:
I also re-ran your three mutations, plus removing the origin check and going back to text matching for the hint. Each one now fails a test. 🟢4, the hint matched on text. It now matches
|
The docs show `[doc.reader]` with `account = true` and no `url` (the account's API supplies it), but `url` was a required field, so that config file failed to load: "[doc] section: missing field `url` in `reader`". The environment variables never hit it, which is what the tests used. `url` now defaults to empty, and an empty one isn't written back. For #2260. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…th login` The device-code flow is shared by `fluree auth login` (a remote) and `fluree login` (the account), and its expiry message named the first. It now says to run the same login command again. For #2260. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…'s reader The project-config case of the url rule, through the config file rather than the environment (which never hit the missing-field error): with `account = true` and no `url`, the call goes to `<api base>/grounding`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…says so Any 401 from the account's reader renews the sign-in once and resends only that call. When the renewal is itself refused (invalid_grant), the run fails with the sign-in's own message and its `fluree login --url` hint, not an endpoint error. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Two more fixes for this PR, both found in end-to-end testing after the review round:
Also a402561, a test for two more cases. A |
bplatz
left a comment
There was a problem hiding this comment.
Approving. The per-call 401 resend and the origin check look right, and the tests pin both. Please look at the three inline comments before merging. The first one (ingest keeps going after the sign-in is gone) is the one I'd most like addressed here or filed as a follow-up.
| } | ||
| } else { | ||
| // A signed-in account's token, renewed before the call. | ||
| doc_reader::renew(&reader).await?; |
There was a problem hiding this comment.
If a call is refused and the forced refresh also fails (a revoked refresh token, say), read_document returns the renewal error, and this loop prints ✗ and continues. The stored access token still looks unexpired locally, so the next document's renew doesn't refresh. Each remaining document then sends a grounding call (401) plus a failing exchange. Neither is billed, but a large folder becomes 2N pointless requests and N ✗ lines. Suggest ending the run when renewal_failed is set.
The opposite case is odd too: a transient exchange error in this renew(..).await? aborts the whole run. Worth deciding deliberately which way each one should go.
There was a problem hiding this comment.
You're right, and the stored token still looking unexpired is exactly why it kept going. Fixed in 61d6f84.
read_document now returns a ReadFailure, either Document or Run, and a refused sign-in whose forced renewal also fails is Run. The loop prints one ✗ for that document, stops there, still indexes and totals what it already committed, and then ends with one error that names where it stopped and what it left, e.g. the run stopped at memo-2.md, leaving 1 document(s) unread that would fail the same way: the reader refused the sign-in, and renewing it failed: your sign-in is no longer valid (…), with the fluree login --url … hint underneath. doc_ingest_through_the_account_stops_when_the_sign_in_is_gone pins it: two documents, a 401 and a revoked refresh, and only /v1/grounding + /v1/oauth/exchange are ever sent.
On the opposite case (a transient exchange error in the renew(..).await? before a document), I did think about which way it should go, and I went with ending the run there too, on purpose. That renewal only runs when the token is inside its refresh margin, so every document after it needs the same renewal first. If the sign-in is revoked, ✗-and-continue is the same N failing exchanges. If it's a passing outage at the exchange, what was committed before it is kept and a rerun skips those documents as unchanged, so stopping costs very little. It now goes through the same ReadFailure::Run path (renewing the sign-in: …) rather than a bare ?, so it gets the same message and the run is still indexed and totalled. doc_ingest_through_the_account_stops_when_renewing_before_a_document_fails covers that one: the first document is read, the second document's renewal is refused, and the run ends with 1 ingested.
This is one rule I'm keeping across all three reader PRs so the ingest loop stays coherent: a failure of this document (a bad answer, a refused call, a failed commit) marks it ✗ and the run goes on, and a failure every remaining document is sure to repeat ends the run with one message. Here that's the sign-in being gone; in #2261 it's a reader asking to wait past the cap, and #2295 applies the first half to the commit step.
| /// another scheme, host or port is refused, since `[doc.reader]` may come | ||
| /// from a project's `.fluree/config.toml` that a cloned repository carries. | ||
| pub async fn resolve(endpoint: &ReaderEndpoint) -> CliResult<(String, Option<Credential>)> { | ||
| if !endpoint.account { |
There was a problem hiding this comment.
With account = true, an api_key on the same slot is silently ignored. Having both set is most likely a mistake, so I'd refuse it or at least warn.
There was a problem hiding this comment.
Agreed. I went with refusing rather than warning, since either way one of the two is the wrong credential for someone. Fixed in 18b09e2: resolve refuses a reader with account = true and a non-empty api_key (from the file or from FLUREE_DOC_READER_API_KEY) before anything is sent, with [doc.reader] has both `account = true` and an `api_key` (or FLUREE_DOC_READER_API_KEY): pick one and a hint for each way out. doc_read_refuses_an_account_reader_with_a_key covers it, and docs/cli/doc.md now says a reader takes account or api_key, not both.
| self.cache = Some(v); | ||
| } | ||
| if let Some(v) = var("ACCOUNT") { | ||
| self.account = matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes"); |
There was a problem hiding this comment.
Any value other than 1/true/yes (on, a typo) silently means false, and that also overrides an account = true from the file. Suggest erroring on a value it doesn't recognize.
There was a problem hiding this comment.
You're right, and it's worse for being the value that overrides the file. Fixed in 3a19d98: FLUREE_DOC_READER_ACCOUNT takes 1/true/yes or 0/false/no (any case, trimmed), and anything else is an error that names the variable and what it takes, e.g. FLUREE_DOC_READER_ACCOUNT="on": expected 1, true or yes, or 0, false or no. That meant DocConfig::with_env returns a Result now; its four callers in doc.rs pass the error on. I also left an empty value as an error rather than a quiet no, so an export FLUREE_DOC_READER_ACCOUNT= doesn't turn off the file's account = true either. a_flag_variable_is_yes_no_or_an_error covers the parsing, and doc_read_refuses_an_account_variable_it_cannot_read the command end to end.
Any value other than 1/true/yes read as false, and a value overrides the file, so a typo (or `on`) quietly turned off `account = true`. It now takes 1/true/yes or 0/false/no in any case, and anything else is an error that names the variable and what it takes. DocConfig::with_env returns a Result to carry it. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_018gr44NC1vnaK3VWs79jCxm
With `account = true` the slot's `api_key` (or FLUREE_DOC_READER_API_KEY) was quietly ignored. Both set is most likely a mistake, and either way one of them would be the wrong credential for someone, so the reader is now refused before anything is sent, with a hint to remove one. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_018gr44NC1vnaK3VWs79jCxm
When a call was refused and the forced renewal failed too (a revoked
refresh token), the document was marked ✗ and the run went on. The stored
token still looked valid, so each later document sent a refused call and a
failing renewal of its own: 2N requests and N ✗ lines for nothing.
One rule now covers every failure in the ingest loop. A failure of this
document marks it ✗ and the next is read. A failure every remaining
document is sure to meet too ends the run with one error, after what was
already done is indexed and totalled. read_document says which with
ReadFailure::{Document, Run}.
A renewal that fails before a document is read ends the run too, by the
same rule: the token is about to expire, so every later document would
need the same renewal first. Documents read before the stop are kept, and
the error names the document and how many were left unread.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018gr44NC1vnaK3VWs79jCxm
|
Thanks @bplatz! I folded all three inline notes in here rather than leaving any as follow-ups, and answered each in its thread:
I also merged On the first note, I took your "worth deciding deliberately which way each one should go" as a rule for the whole ingest loop, and applied the same rule in #2261 and #2295 so the three stay coherent: a failure of this document marks it ✗ and the run goes on; a failure every remaining document is sure to repeat ends the run with one message, after it indexes and totals what it already did. Both renewal failures (the one after a refused call and the one before a document) fall in the second group. |
What
fluree doccan now read through the machine's Fluree AI sign-in (fluree login, #2205) instead of a key in config:With
account = true(orFLUREE_DOC_READER_ACCOUNT=true):Authorization: Bearer.url. It defaults to the account's own reader at<api base>/grounding, read from the sign-in. An expliciturlon the same scheme, host and port still wins; one elsewhere is refused before anything is sent, so a project's.fluree/config.tomlcan't send the sign-in's token to another server.doc ingestrenews the token before each document (a refresh only when it's about to expire), so a run longer than the hourly token doesn't fail partway.401from the account's reader, the token is renewed once with a forced refresh and that call alone is resent; calls already answered aren't sent (or billed) again. The common case isconfig_stale, after the account's configuration changed. A second401fails with a hint to runfluree loginagain.urlneeded in the file.[doc.reader] account = truewith nourlloads (it used to fail with "missing fieldurl").fluree login".How
ReaderEndpoint.account(serde-defaulted tofalse, so existing configs are unchanged).is_usable()accepts an account slot with nourl.doc_reader::resolvepicks the URL and credential (and refuses aurloff the account's origin), andrenewrefreshes the sign-in between documents.ReaderClient::with_renewal(Renewal): on a 401 the client runs the hook once, swaps in the credential and resends that one request. The CLI's hook forces a refresh on the reading's blocking thread through the runtime handle.read()'s signature is unchanged.ReaderClient's credential sits behind anRwLockso a run can swap in the renewed token (set_credential).DocError::Endpoint { status: 401, .. }, not message text.Also: an expired device code during
fluree loginnow says to run the same login command again, notfluree auth login.Tests
doc_read_through_the_signed_in_account: reading through the sign-in, plus the not-signed-in error.doc_read_through_the_account_renews_a_stale_token_once: a stub answers401 config_stale, then the refresh, then the reading. The test checks the order of calls, that the retry carries the new token, and thataccount.tomlnow holds it.a_refused_credential_is_renewed_once_and_the_call_resent(client);doc_ingest_through_the_account_resends_only_the_refused_call(a two-call document refused on its second call: grounding, grounding, exchange, grounding, and2 call(s)reported);doc_read_through_the_account_refused_twice_says_to_sign_in_again;doc_read_with_its_own_key_is_not_renewed_on_a_401;doc_read_through_the_account_gives_the_sign_in_hint_only_for_a_401;doc_ingest_through_the_account_renews_the_token_before_each_document;doc_read_through_the_account_refuses_a_url_off_the_accounts_api.cargo test -p fluree-db-doc -p fluree-db-cligreen; clippy clean forfluree-db-doc,fluree-db-cliandfluree-db-python --features extension;cargo fmt --all --checkclean.🤖 Generated with Claude Code
https://claude.ai/code/session_016CjYmSfiNVsRZmcpMicDfq