Repository navigation
fix(server): one HTTP status table for API errors - #2102
Conversation
The server mapped API errors to statuses in its own table and never asked ApiError::status_code, while every path that flattens an error to ApiError::Http (consensus, shared ledger loads, tracked queries) carries the API's status. One error answered differently by route; tracked queries had a third table of their own. ApiError now owns both the status and the @type code, side by side and exhaustive, and the server derives both. Disagreements are resolved toward the explicit decision over the catch-all, and by evidence where both decided (Json is stored data: 500; credentials are documented 401). Wrong in both, now fixed: a t past the head is 400, syncing a dropped graph source is 409 GraphSourceRetracted. A write whose every commit attempt loses its race is 503 CommitContention with Retry-After, typed through consensus so it stays settled, and each retry loop records its attempts on a txn_attempts span.
The query loader tagged every load failure that was not a not-found as `error:NotFound` and logged "ledger not found", a holdover from before not-found reporting moved to the callers. A real storage failure read as a missing ledger in logs and traces on the JSON-LD, dataset-clause and info routes; only SPARQL overwrote the tag. The loader now reports it as `error:LedgerLoad` / "ledger load failed", and SPARQL's overwrite goes.
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz yes to one table, and to ApiError owning both the status and the @type side by side. The exhaustive matches plus every_variant's count are the structural fix this needed, and when I rebuilt the before/after from main's three tables your body's table held row for row. Two headline notes.
(1) The class this PR attacks, an error re-decided where it gets flattened, has one more front than the server table: tracked queries still pick a literal status at about a dozen resolution sites (mostly query/connection.rs), so a missing ledger is 404 untracked and 500 tracked, which is #1595's symptom. I'd fix those statuses here, since it's mechanical and the PR closes #1595, and leave carrying the @type through every flatten (#2103, and the per-condition SubmissionError variants that keep multiplying because Execution only keeps a status) to its own effort.
(2) My #2007 overlaps this in both error.rs files: it adds QueryError::Nameservice (500, err:system/NameServiceError) to the two tables this PR replaces. Your exhaustive query_error_status will force the row on whichever of us lands second. If this lands first, I'll carry the row in #2007's rebase, including an error_type arm, since the == 500 guard would otherwise give it err:system/InternalError. And on the old 400-vs-404 question, main, #2007 and this PR all answer 404 err:db/GraphNotFound for a graph the ledger lacks, except on the tracked path in (1).
Full review below:
✅ Approving to unblock you — with 1 thing that needs to be addressed before this merges.
I'm quite happy with this one, @bplatz. Moving the status and the @type onto ApiError side by side, deriving the server's answer from them, and making both matches exhaustive is the shape this needed. I rebuilt the before/after from code (main's ApiError::status_code, the server's two tables and the tracked status_for_query_error, run over every row of every_variant), and the body's table holds: every row reproduces, and the changes outside it (CommitContention 409 → 503, the flattened 404/408 codes) are the ones the prose names. No change moves an answer between 403 and 404, and the existence-masking 404s are the server's own ServerError::not_found, decided on bearer scope by name before anything loads, so switching validate and BM25-create to the engine's err:db/LedgerNotFound doesn't open an existence oracle.
Must address before merge:
fluree-db-api/src/error.rs:658: tracked queries still choose a literal status at their resolution sites (query/connection.rs×11,query/builder.rs,graph_query_builder.rs,tx.rs). A tracked query naming a missing ledger, or the unknown graph #2005 made a 404, answers 500; untracked it's 404. ATrackedErrorResponse::from_apithat takese.status_code()fixes it. Details inline. (Or dropFixes #1595until it lands.)
Should address:
fluree-db-api/src/error.rs:706: the Python binding maps 503 toFlureeError, so contention no longer raisesConflictErrorandLedger.transactstops retrying it. One arm influree-db-python/src/error.rs. Inline.
On the listed follow-ups: #1908 (79 ApiError::query call sites, each needing its own judgement) and #2085's remaining items are rightly separate. #2103's smallest version is four waiter sites in ledger_manager.rs mapping is_not_found() to ApiError::NotFound; it's the same class as (1), so I'd be glad to see it folded in, though I understand wanting its concurrent-load regression test to come with it.
Adherence to repo commitments:
- Patterns/abstractions: ✔ one table on the type that owns the error, derived by the server and by consensus, exhaustive at the
ApiErrorlevel;⚠️ the tracked resolution sites still decide on their own. - Performance (speed first, memory second): ✔ no performance-degradation risk: error paths only, plus a
txn_attemptsdebug span per write (disabled unlessfluree_db_apiis at debug) and one field record per attempt. - Deployment targets:
⚠️ the answers change for every host's clients: the server's HTTP statuses and codes, embedded callers that branch onstatus_code()or matchSubmissionErrorexhaustively (a newCommitContentionvariant), the Python exception classes (inline), and the CLI's remote messages (409 "conflict" → "server error" on exhaustion, with no retry logic depending on it). wasm32 compiles in CI. No fence is involved. - Testing: ✔
every_variant_answers_the_same_typed_or_flattened(red under a mutation), bothit_commit_contentiontests (red when the loops return the raw conflict), the load-failure test and the BM25/validate HTTP tests, all passing by name;⚠️ nothing covers a tracked query's resolution errors. - Conventions: ✔ thorough commit bodies;
docs/api/errors.md(the 507 section, 409 causes, the corrected 408 example) and the telemetry and tracing docs updated.
Verified locally at df2a8b744: cargo test -p fluree-db-api --lib error:: and --test grp_ledger it_commit_contention; cargo test -p fluree-db-server --lib --test grp_search --test grp_http --test graph_source_query_logging (all green, new tests by name); two mutations (restored); a scratch before/after table over every variant; the tracked-vs-untracked probe; and a trial merge with #2007 and #2019.
Approving now so you can merge without waiting on another pass from me. Just be sure the tracked statuses are in before you do.
| /// like fluree-db-server or external HTTP wrappers. | ||
| /// The one status table: fluree-db-server answers with it, and every path | ||
| /// that flattens an error to [`ApiError::Http`] (the consensus committer, | ||
| /// shared ledger loads, tracked queries) carries it, so an error answers |
There was a problem hiding this comment.
🔴 Must address before merge: tracked queries still pick their status per call site (fluree-db-api/src/query/connection.rs and three other files), so a tracked query naming a missing ledger answers 500 where the same query untracked answers 404, which is the #1595 symptom this PR closes.
This doc says every path that flattens to ApiError::Http, tracked queries included, carries this table. The query-execution half does now (query_error_status), but the dataset and view resolution that runs before it doesn't: query/connection.rs maps the ApiError from try_single_view_from_spec, build_dataset_view* and policy application to TrackedErrorResponse::new(500, e.to_string(), None) at :74, :83, :98, :541, :560, :606, :625, :901, :966, :1014, :1123. The same literal 500 is at query/builder.rs:1516 and graph_query_builder.rs:374 (the crawl) and on the tracked write path at tx.rs:3205, with literal 400s over ApiErrors at query/builder.rs:1491 and tx.rs:3124, :3158. The server then answers ApiError::http(e.status, e.error) (fluree-db-server/src/routes/query.rs:2853-2854, and :954-955 for SPARQL with tracking headers).
I ran it at this head, query_connection against query_connection_tracked with the same body:
from: "rv-nope:main": untracked404 err:db/LedgerNotFound, tracked500.from: "rv-db:main#http://ex.org/nonexistent"(the unknown-graph case fix(query): 4xx for unknown graphs and commit refs; urn:default names the default graph #2005 settled on 404): untracked404 err:db/GraphNotFound, tracked500.from: ["rv-db:main", "rv-nope:main"]: untracked404, tracked500.
The fix is mechanical: a TrackedErrorResponse::from_api(&e, tally) (or a From<ApiError>) that takes e.status_code(), used at every site where the error is an ApiError so that no site can choose a number, plus one test that a tracked query naming a missing ledger answers 404. Carrying e.error_type() along as well would stop the server's flattened answer from degrading to err:api/NotFound, which is #2103's shape; I'd be fine with that half landing with #2103.
Commenting here because query/connection.rs, query/builder.rs, graph_query_builder.rs and tx.rs are not in this diff.
There was a problem hiding this comment.
Fixed in 46693a7. There were more literal sites than the ones listed: 60 in all, across query/connection.rs, query/builder.rs, graph_query_builder.rs, view/query.rs, view/dataset_query.rs and tx.rs.
TrackedErrorResponse::from_api takes the status from ApiError's table and keeps the error's own message, so the tracked policy-denial messages the tests pin are unchanged. It accepts anything that converts into ApiError, which covers the TransactError sites in tx.rs and the FormatError sites. Literal statuses remain only for fixed messages: a missing ledger or dataset specification, and builder validation.
tracked_connection_query_errors_answer_the_untracked_status runs your three probes, plus SPARQL FROM a missing ledger and a SPARQL syntax error, tracked and untracked. Each must give the same status: 404, and 400 for the syntax error. Against the old sites it fails with (404, 500) on the first case.
The tracked write path (transact_tracked_with_policy, which credential_transact uses) had the same problem:
- a policy denial was 400 where untracked it's 403;
- a lost commit race was 500 where untracked it's 409.
Both are pinned now: the policy-tracking test asserts 403, and a_tracked_write_that_loses_its_race_keeps_the_conflict_status asserts 409. Both fail against the old tx.rs literals.
Carrying error_type() through stays with #2103, as you suggested.
| // 503 + retryable: capacity that clears on its own (the indexer | ||
| // draining, other writers easing off), so neither the caller's | ||
| // fault (4xx) nor a fault at all (500). | ||
| ApiError::NoveltyDeferred { .. } | ApiError::CommitContention { .. } => 503, |
There was a problem hiding this comment.
🟠 Should address: Python callers lose ConflictError on contention, and with it Ledger.transact's retry (fluree-db-python/src/error.rs:14-60).
The binding picks the exception class from the typed error first (TransactError::CommitConflict → ConflictError with expected_t/head_t) and otherwise from class_for_status, where 503 falls to FlureeError. Before this PR, a transaction whose every attempt lost came back as the last raw CommitConflict and raised ConflictError; now it's CommitContention, so 503, so FlureeError. Ledger.transact and aio.transact retry only ConflictError (python/fluree/_connection.py:632, aio.py:355), and fluree-db-python/README.md:437 tells users to hand conflicting work to transact. It's reachable wherever several processes write one ledger, which connect(config=…) supports (S3 plus a DynamoDB nameservice).
One arm fixes it: map ApiError::CommitContention { last, .. } to ConflictError, taking expected_t/head_t from last when it's a CommitConflict. ConflictError's own docstring ("A concurrent change won; retrying against the new state may succeed") already describes contention. The Python CI jobs are green only because nothing exercises this path.
Commenting here because fluree-db-python/src/error.rs is not in this diff.
There was a problem hiding this comment.
Fixed in 869f27b. ApiError::CommitContention raises ConflictError, taking expected_t / head_t from last when it's a CommitConflict (a PublishLostRace leaves them None, as the class docstring allows).
There's no test for this one. Python can't force contention, and the binding has no Rust unit tests, because it builds only as a cdylib and CI doesn't link libpython. The PR body says so.
| .iter() | ||
| .map(|(e, ..)| std::mem::discriminant(e)) | ||
| .collect(); | ||
| assert_eq!(variants.len(), VARIANTS, "every_variant misses a variant"); |
There was a problem hiding this comment.
👍 This is the right guard. An exhaustive match plus a discriminant count means a new variant can't ship unclassified, and checking the flattened status alongside the typed one means the consensus path can't drift from the direct one again. I took FutureTime out of the 400 arm and this went red (left: 500, right: 400).
Tracked queries and tracked writes chose a literal status where they wrapped an engine error: 500 for resolving a query's dataset, applying policy, the crawl and formatting, 400 for parsing, and 400/500 for a tracked write's staging and commit. A tracked query naming a missing ledger or a graph the ledger lacks answered 500 where the same query untracked answered 404, and a tracked write's policy denial was 400, not 403. TrackedErrorResponse::from_api takes the status from ApiError's table and keeps the error's own message. Every site that wraps an ApiError, a TransactError or a FormatError uses it; literal statuses remain only for fixed messages (a missing ledger or dataset specification, builder validation).
Contention answers 503, which the binding mapped to FlureeError, so Ledger.transact and aio.transact, which retry only ConflictError, stopped retrying a write whose every commit attempt lost a race. It raises ConflictError again, with expected_t and head_t when the last conflict carries them.
Brings in #2102 (one HTTP status table), #2068, #2056, #2053, #2046, #2045 and the v4.2.4 release. - api error.rs: main's exhaustive status_code / error_type tables, with ApiError::ConfigUnavailable and TransactError::ConfigUnavailable classified as 500 err:storage/ReadFailure in both, and rows for them and RequestOverrideRefused in every_variant. - server error.rs: main's derivation from ApiError; this branch's ConfigUnavailable arms move to the API tables. - consensus: SubmissionError keeps both ConfigUnavailable and CommitContention. - server routes/transact.rs: both submission arms and test rows. - transaction.rs, tx_builder.rs: main's txn_attempts loops, with this branch's request-governance argument on every stage_plan / stage_all call.
The server mapped API errors to HTTP statuses in its own table (
ServerError::status_code) and never consultedApiError::status_code. Every path that flattens an error toApiError::Http— the consensus committer, shared ledger loads, tracked queries — carries the API's status, so the same error answered differently depending on the route. Tracked queries used a third table of their own (status_for_query_error).ApiErrornow owns both the status and the@typecode (ApiError::error_type), side by side, and the server derives both forServerError::Api. Its own table covers only its own variants. BothApiErrortables are exhaustive matches, so a new variant has to be classified before it compiles.Status changes
Where one table made an explicit decision and the other fell through a catch-all, the explicit one stands. Where both decided, the evidence picked:
Ledger(FutureTime)(sync or load at atpast the head)err:api/BadRequestDrop)err:db/GraphSourceRetractedQuery(MemoryBudgetExceeded)IndexTimeoutReindexConflictReindexConflict) / 409IndexingDisabled,BuilderIndexer(LedgerNotFound / NoCommits / other)err:system/IndexingErrorTransact(CommitIdMismatch)(a head-CAS mismatch)err:db/CommitConflictIceberg(MergeOnReadDeletes / other)err:iceberg/MergeOnReadDeletes/ 400AwaitTNotReachedMaterializePartialCredentialCredentialError::status_codeis goneJsonserde_jsonerror reaching it parses stored records (graph-source configs, BM25 manifests)QueryErrors (Core, operator lifecycle,NoSuitableIndex,DictionaryLookup,NeedFetch,Policy,Internal)QueryErrors (VariableNotFound,ResourceLimit, snapshots, R2RML, …) and storage/catalog denials on tracked queriesA flattened
Httperror now names its status: 404 iserr:api/NotFoundand 408 iserr:db/QueryCancelled, where both used to readerr:system/InternalError.The BM25-create and SHACL-validate routes no longer re-wrap a missing ledger themselves. The derived table answers 404 for both of the ledger-not-found forms, now with
err:db/LedgerNotFoundrather thanerr:api/NotFound.A ledger that fails to load is not a missing ledger
The query loader (
load_ledger_or_missing) tagged every load failure that was not a not-found aserror:NotFoundand logged "ledger not found". That was a holdover from before not-found reporting moved to the callers. On the JSON-LD, dataset-clause and info routes, a real storage failure read as a missing ledger. It now reportserror:LedgerLoad/ "ledger load failed", and the SPARQL route's overwrite of that tag is gone.Tracked requests
Tracked queries and tracked writes chose a literal status wherever they wrapped an engine error:
ApiErrorarms #1595's symptom).transact_tracked_with_policy, whichcredential_transactuses, answered 400 for staging and 500 for the commit. A policy denial was 400, not 403, and a lost commit race was 500, not 409.TrackedErrorResponse::from_apitakes the status fromApiError's table and keeps the error's own message. Every site that wraps anApiError,TransactErrororFormatErroruses it. Literal statuses remain only for fixed messages: a missing ledger or dataset specification, and builder validation. The server's tracked writes already returned anApiErrorand are unchanged. Tracked errors still carry only a status, so the server's answer to one keeps the flattened@type; carrying the type through is #2103.Commit contention (#1726)
The
Internal("transaction commit retry limit exceeded")the issue measured was reachable through a barecontinuein the optimistic path, which 63305ae removed. Since then, retry exhaustion has returned the last raw conflict as a 409, and theInternaltail has been unreachable. Retries now only happen when another process shares the nameservice and storage.When every attempt loses, both retry loops (the staged builder and multi-operation
Transaction) now returnApiError::CommitContention { attempts, last }, which answers 503 +Retry-After+err:db/CommitContention. Through consensus it travels as a typedSubmissionError::CommitContention, because anExecution { status: 503 }would read as unsettled and pin a keyed retry toAlreadyInFlightfor the cache TTL. The local committer still retries an inner loop's contention, as it did the raw conflict. A conflict the server returns without having retried stays 409err:db/CommitConflict.Each loop runs inside a
txn_attemptsdebug span that recordsattempts.In Python,
CommitContentionraisesConflictError, as the raw conflict did, soLedger.transactandaio.transactkeep retrying it.expected_tandhead_tare set when the last conflict carries them.Tests
every_variant_answers_the_same_typed_or_flattened(fluree-db-api): one row perApiErrorvariant, plus extra forms for the variants that split, pinning status and@type. It also checks that the flattened form keeps the status and that no 4xx reads aserr:system/InternalErrorin either form. An exhaustive match plus a variant count fail it when a variant has no row. Breaking theFutureTimerow, or dropping the flattened 404 code, fails it.it_commit_contention(grp_ledger): a nameservice whose commit-head CAS always loses drives both retry loops toCommitContentionwith nothing committed, and checks the span records 16 attempts. Returning the raw final conflict instead fails both tests.a_ledger_that_fails_to_load_is_not_reported_missing: a ledger whose commit blobs are gone is reported as a load failure on all four routes. The old tag fails it.tracked_connection_query_errors_answer_the_untracked_status(grp_query) runs each case tracked and untracked: a missing ledger, an unknown graph and a two-ledgerfromwith one missing (all 404), SPARQLFROMa missing ledger (404), and a SPARQL syntax error (400). The old literal statuses fail it with(404, 500).a_tracked_write_that_loses_its_race_keeps_the_conflict_status(409, was 500) and the tracked policy-denial test, now pinning 403 (was 400).GraphSourceRetractedfor both sync forms on a dropped index, 400 for?t=past the head, andLedgerNotFoundon the two 404s.The
tx_builder.rsandtransaction.rsdiffs are mostly re-indentation from wrapping each loop in its span;git diff -wshows the change.Fixes #1595
Fixes #1726
Partially addresses #2085: the status-table item. Variable ids in plan errors, plan errors after the stream's head, and
sh:selectvalidation remain.Follow-up: #1908 (the
ApiError::queryaudit, which still buildsInternal500s)Follow-up: #2103 (a request waiting on another's ledger load gets a flattened 404 that
is_not_found()misses)