Repository navigation
Release 2026.3.4 - #1038
Merged
Merged
Release 2026.3.4#1038
Conversation
API-key authentication returned the key's stored role without comparing it to the roles its owner holds now, so an admin key kept acting as admin after the role was revoked. It also skipped the inactive-user check the JWT path makes, and ignored the key's expiration date. A key's active role is now its stored role only while the owner still holds it; otherwise the key authenticates with no role. Keys of inactive users and keys past their expiration date don't authenticate. The RLS policies will trust these roles, so they have to match the owner's.
… timeouts Postgres reports a policy rejection and a missing grant with the same SQLSTATE, 42501, and callers had to match on SQLSTATEs to tell timeouts from other operational errors. A handle_error listener on the engine now raises RowSecurityViolation, MissingGrant or DatabaseBusy, so the api and the worker can catch them by type. The engine also hides bound parameters, so a stored or logged error no longer quotes the values a statement was given. The server's DETAIL line can still quote a row, so the message stays out of alerts. The worker classifies both privilege errors as configuration errors, since its role should never hit either and a retry won't help.
An exception's message can quote row data, and a URL's path and query can carry identifiers and search terms, so alerts posted both to Slack. Alerts now carry the exception type, its location, the correlation id and the route template. The full message stays in the logs, which the correlation id finds. Worker alerts have no correlation id until #1008, so they name the job run and pipeline from the logging context instead. cleanup_stalled_jobs passed a string to send_slack_error, so it now uses send_slack_message.
server_main.py registered a hand-written handler for each exception, so each one decided its own status, body and alerting. Each domain now maps its exceptions in a table of status, body and whether it alerts, and one handler serves every table. A test fails when an exception in the domain modules is neither mapped nor listed as deliberately unmapped. A write that row security rejects returns 403, since Python already let the caller see the row. A write the policy hid matches no row and returns 404. Both alert, because either one means the Python check and the policy disagree. Missing grants return 500 and alert, and timeouts return 503 without alerting. Starlette wraps an exception raised after a stream has started, so the middleware unwraps it. It logs and alerts the original type from inside the request's context, so the alert carries the response's correlation id. The handlers are plain functions, so Starlette runs them in its threadpool and the blocking Slack webhook call doesn't stall the event loop.
Records the error-table pattern for sessions that touch routers, lib or db, so new exceptions get mapped rather than caught and re-raised as literal HTTPExceptions. Expect: agents add a table entry for a new domain exception instead of raising HTTPException with a literal message in a route.
annotation_event appends a row every time a check runs, so it grows with runs rather than with what we know: 221M rows and 89 GB on production, about 70% of them repeating an outcome already recorded. annotation_status replaces it with a ValidTime table that has one live row per key (subject, type, ClinVar release, kind) and changes only when an outcome does. The retired rows are the history. A failure gets its own row kind, so a failed re-check never overwrites a known result. v_annotation_status_current pairs each key's live outcome with its live failure, so readers don't each repeat that join. Nothing writes to the table yet. annotation_event shares its subject-type lists and IN-list helper from here until the cutover removes it.
Creates the table, its live-key unique index (NULLS NOT DISTINCT, so the NULL subject and release columns still collide) and the current-status view. The view is security_invoker, so row-level security policies on annotation_status will apply to whoever queries it. annotation_event is left in place for the cutover.
AnnotationStatusManager now writes to annotation_status instead of appending to annotation_event. A pure plan() compares each key's reports with its live outcome and failure rows, so a re-run that changes nothing writes nothing, a changed outcome supersedes the live one, and a failure gets its own row that a later success retires. flush() reads and writes under a transaction-scoped status lock that the caller's commit releases, so concurrent jobs sharing alleles can't plan against a stale read. Jobs report with report() and flush at the same points as before; the migration script flushes once per batch, outside its per-variant savepoints. variant_annotations reads v_annotation_status_current. Refs #973
ClinVar status splits into two annotation types. clinvar_allele_id records once per allele whether ClinGen links its CAID to a ClinVar AlleleID, and clinvar_control records per release whether that AlleleID is in it, only for alleles that have one. An allele with no AlleleID, or a protein-level or multi-variant one, now writes one status instead of one per release. refresh_clinvar_controls looks up only alleles without a known AlleleID and evaluates only releases an allele hasn't been evaluated against, so it skips downloading release files nothing needs. A forced run looks every AlleleID up again; one that changed is recorded as corrected, and each release's link is replaced through the new AlleleID or withdrawn. AnnotationStatusManager.current_statuses reads current statuses for either subject type. AnnotationType members document the question each answers. Refs #973
…ersion gnomAD and VEP skip alleles whose live status is a settled absence at the current source version, read from status columns only. VEP's status version now includes the resolver version, so a resolver change re-checks alleles. The status manager buffers withdrawals and applies them in flush, under the same lock as reports. When CAR replaces a CAID, it withdraws the statuses matched through the old one (CAID_MATCHED_TYPES), so gnomAD and ClinVar check the allele again. Every annotation type is classified as CAID-matched or not, and a test keeps the classification exhaustive.
The status manager adds to counters in the open logging context on each flush: annotation_status.keys_changed and .keys_unchanged for reported keys, .withdrawn for statuses withdrawals retired, and .source_versions for the versions reported. Each job's canonical log shows what its checks changed, and scripts, which open no context, record nothing.
--translated-since selects score sets an RT job finished processing since the date, from job_runs: statuses record only changes, so a run that changed nothing leaves no trace there. The mapping and RT checks and the outcomes summary read current statuses, with a failing key counted as failed, and outcomes joins through variants since statuses carry no score set. The mapped-variants migration counts and describes annotation_status rows.
Replays the log through the jobs' own plan(), timestamped at each event's created_at, so the result matches what the jobs would have written. The first pass reads the whole log a range of subjects at a time and commits per chunk; later passes replay the events since the high-water mark in annotation_event_backfill, in one transaction, for the catch-up during the deploy. ClinVar events split into clinvar_allele_id and per-release clinvar_control statuses. Drops the legacy mapped_hgvs and variant_translation types: no job writes or reads either, so the backfill skips their events and they leave the enum, the subject lists, the CHECK and the mapped-variants migration.
An event that commits below the high-water mark after a pass has read past it is never replayed, and nothing would notice. The backfill is now run with the worker stopped, as the #973 rehearsal planned, and a pass refuses to start while any event is less than ten minutes old.
A job reports `corrected` only when the value it stores changed, but the value itself (a ClinVar AlleleID, a CAID) lives in the status metadata, which plan() doesn't compare. So a second correction in a row looked like no change and the status kept the value before it: an AlleleID that went A, B, then back to A stayed at B.
The job decided an AlleleID had changed by comparing it with the AlleleIDs of the allele's live links. An AlleleID that no release contains leaves no links, so after A, B, then A again the job saw A as new and never re-evaluated the releases it had recorded as absent under B. And an allele with links through two AlleleIDs, left when a correction couldn't fetch one release, resolved to whichever row came back last, so the stale link stayed. The stored clinvar_allele_id status now decides a correction, and an allele whose links don't all match its AlleleID is evaluated against every release again, which replaces the stale links.
…e_where The status writer retired live rows and inserted their successors in separate statements. Both were stamped with the same `now`, so there was no gap, but the ValidTime convention is to replace rows only through supersede. Each chunk of keys now supersedes its own rows; a recovered failure has no successor, so it is still only retired.
…-role-checks fix: drop an API key's role once its owner loses it
…ror-mapping feat: map database permission errors to client responses without leaking row data
The test for skipping alleles already found absent at this gnomAD version never stubbed the Athena engine, so its "older" case, which queries, opened a real Athena connection. That works with local AWS credentials, but in CI boto falls back to the instance metadata address, the socket guard blocks it, and the job fails before the mocked fetch.
Golden files for the score-set and variant CSVs, written by the current exports, so a change to how the exports are built can't change what they emit. Rewrite them with MAVEDB_UPDATE_GOLDEN=1 after a deliberate output change. The shared fixture in tests/helpers/util/csv_export.py seeds one score set with a fully annotated mapped variant, a benign-absent and a failed mapping, unmapped variants whose HGVS covers every null token, a named target gene, a superseded calibration whose title needs CSV quoting, and gnomAD and ClinVar links replaced after a known instant. The snapshots cover namespace sets, namespacing, HGVS dropping, paging and as_of for both exports. Adds tests that the variant CSV leaves out equivalent measurements from score sets the caller can't read, and that a permitted caller receives a private calibration in the score-set CSV. Moves the calibration and ClinVar test helpers into tests/helpers/util so these tests and the variant CSV tests share them. Refs #845
…and one writer Each CSV export ran the same steps, wired by hand per data source: a fetch result with one list per source, row builders with one parameter per source, and each export calling the calibration step itself. Adding a source took about a dozen edits across seven files. Now an export plans its cells once (CsvPlan), asks iter_csv_rows for its scope's rows, and writes them with render_csv. A row is one dict of sources. The scope supplies the variant and its match type; every other source has a loader in the new sources module, registered by RowSource and run only when a planned cell reads it. Adding a source is a RowSource, a loader and a spec. - Mapping is a loader queried per batch by variant id rather than a join on the variant query. - Calibrations load once per export; ClinVar reads every requested release in one query (#845). - Score and count columns are read off the variant, so they are no longer row sources. - ClinVar and calibration namespaces are marked by a parameter on their spec instead of pattern checks. - Labels and groups live on the spec, and the mapping-derived namespace list is shared by both exports. - drop_unused_hgvs_columns is answered by one aggregate query before the header is written. Output is byte-identical: the golden snapshots from the previous commit, written by the old exports, pass unchanged. A new test pins the dataframe the score-set router rebuilds from stored variants when only one of its files is re-uploaded, which matches the old one value for value. Refs #845, #1001
… coverage Golden snapshots only check what they're asked for, so a new namespace, export parameter or loader could ship with no snapshot or test and nothing would fail. test_coverage reads what needs covering from the code (the namespace enum, the source registry, the modules that write CSV and their exports' signatures) and requires each to be declared as covered by a snapshot, a test, or an exemption with a reason. Every declaration has to resolve to a snapshot or test that exists, and a declaration whose subject is gone fails too. A source claimed to honour as_of by snapshot must differ between the as_of snapshot and the current one, so the claim is checked rather than taken on trust. Refs #845
…tion-status Store annotation statuses only when they change
When Postgres ends a session (the 60-second idle-in-transaction limit, a restart or a failover), the next query fails with an OperationalError that often carries no SQLSTATE, so CatchAllErrorMiddleware answered it with a 500 and the client couldn't tell a retry would work. SQLAlchemy marks these errors with connection_invalidated and discards the connection, so a retry gets a fresh one. The middleware now answers an invalidated connection with a 503 and Retry-After: 5. Unlike the database timeouts it still logs an error and alerts Slack, since a dropped connection can also mean an outage. Every other database error is still a 500.
Retry-After isn't a CORS-safelisted response header, so a browser hides it from scripts on another origin. The ui is served from a different origin than the api, so it saw a 503's status but read Retry-After as null and couldn't wait the time the server asked for. That applies to the CSV build cap's 503 today, and to the dropped-connection 503 in #905. Scripts and other non-browser clients were never affected.
The first commit answered it in CatchAllErrorMiddleware, which is meant only for the 500 path; every other status belongs in a domain table. db/errors.py now raises ConnectionDropped for an error SQLAlchemy marks connection_invalidated, checked before the SQLSTATEs because a dropped session often has none, and DATABASE_ERROR_RESPONSES answers it with a 503 that alerts. ErrorResponse gains an optional headers field so the entry can send Retry-After.
…d it A request's session stays in an open transaction until get_db's teardown, which FastAPI runs after the response is sent. A slow client downloading a large CSV keeps that transaction idle past the API's 60-second idle_in_transaction_session_timeout, so Postgres ends the session and rolls it back. The rollback in db.close() then fails on the dead connection, and the middleware sent a Slack alert for a request that had already returned 200: 1,055 of the week's 1,459 production alerts. get_db now swallows a close error only when SQLAlchemy marks the connection invalidated, and records db_session_ended_by_server in the canonical log so the drops stay countable. Any other close error still raises. Ending the session when the route returns is the permanent fix (#1036); this stays as a backstop for routes that keep their session through a streamed response.
Once #1036 ends sessions when the route returns, only routes that read while streaming can still reach it.
…wrapper ConnectionDropped now has a handler in the error table, so when the connection drops after the response has started, Starlette re-raises it as a RuntimeError caused by the ConnectionDropped. The test now checks that cause, and that the error middleware unwraps it so the Slack alert names ConnectionDropped rather than the wrapper. The client still gets the same truncated array.
The old suite's app_ fixture sets a get_db override on the shared app and never clears it, so when an app_ test ran earlier on the same worker, the probe route got the test session instead of the real get_db and the quiet close never ran. The fixture now sets any leftover override aside while the probe is registered and restores it after. #183 removes the shared app and this workaround with it.
…y-after-header fix: expose Retry-After to cross-origin browser clients
…v-row-sources refactor(csv): build every export from one plan, one source registry and one writer
…-connection-503 fix: return 503 with Retry-After when the database drops a connection
Updates dnspython 2.8.0 -> 2.9.2, pyasn1 0.6.4 -> 0.6.5, opentelemetry-api 1.45.0 -> 1.45.2 and soupsieve 2.9.2 -> 4.1.3 for their CPU and memory denial-of-service advisories, and the dev-only virtualenv 21.14.1 -> 21.15.13 for its activation-script advisories. distlib and packaging move with virtualenv. soupsieve's fixed releases need Python 3.11.5, so the project's floor rises from 3.11 to 3.11.5; otherwise Poetry keeps the vulnerable 2.x for 3.11. The image and CI already run a later 3.11.
filelock 3.29.0 has advisories against UnixFileLock, which truncates and chmods a file another user renames onto the lock path, and against its SQLite ReadWriteLock and SoftFileLock. The api only takes a FileLock around the ClinVar cache download, so the 4.x API change doesn't reach it; the ClinVar tests pass unchanged.
…t-close fix(db): close a request's session quietly when Postgres already ended it
Nothing in the api imports authlib and no other package depends on it; it has been listed in the server extra since the 2023 packaging switch without being used. Removing it clears its open Dependabot alerts, among them a critical JWS signature-forgery advisory, rather than taking a 1.6 to 1.9 bump of a library we don't run.
The score set CSV routes built the whole file in memory before sending a byte, so a large score set held every row and all of its text at once. They now stream it: iter_csv_rows reads the score set's variants from a server-side cursor in batches of CSV_BATCH_SIZE (5000), loads each batch's sources for that batch alone, and render_csv sends one chunk per batch. - stream_score_set_variants_as_csv is the streaming export; get_score_set_variants_as_csv keeps its signature and joins the stream, so the scripts that call it are unchanged. - The routes build the first chunk before responding, so a refused build slot or an immediate query failure is still an error status. The build slot is held until the stream finishes, and the stream's duration is logged. - An explicit variant set, as the variant CSV uses, stays one batch. Batching never changes the bytes: tests compare batch sizes of 1 and 2 against a single batch across namespaces, HGVS dropping and paging, and the golden snapshots pass unchanged. Refs #770
ConnectionDropped has a handler since #1033, so a connection dropped after the CSV stream has started reaches the client as Starlette's RuntimeError caused by ConnectionDropped, not a raw OperationalError. Match the lean view's test: check that cause, and that the Slack alert names ConnectionDropped. The client still never gets the last row.
Coverage Report for CI Build 45712388769Coverage increased (+0.09%) to 91.282%Details
Uncovered Changes
Coverage Regressions12 previously-covered lines in 3 files lost coverage.
Coverage Stats
💛 - Coveralls |
…csv-downloads fix(csv): stream score set CSV downloads in batches
Streaming the CSV straight to the client tied the database to the client's reading speed: the server-side cursor kept the transaction open between batches, so a client slower than the 60-second idle-in-transaction limit on one chunk got a truncated file and the stream alerted Slack. A failure partway through also reached the client only as an unterminated chunked body, after a 200. The routes now run the same batch generator into an anonymous temporary file under the build slot, end the transaction and release the slot, then send the file. Memory stays at about one batch as before; the largest files are 57-73 MB on disk. A build failure is now an error status before any byte is sent, and a slow client touches neither the database nor a build slot. Content-Length is sent, though GZipMiddleware drops it for clients that ask for gzip.
The slow-client test lowered the session's idle limit to 200 ms before the request, which also bounded the build. On CI's slower runner the build paused longer than that between batch queries, so Postgres ended the session mid-build and the route correctly failed. The test now checks the condition the idle limit acts on: no backend sits idle in a transaction while the file is sent. It fails when the build's transaction is left open.
…sv-downloads fix(csv): spool score set CSV downloads before sending them
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Features
annotation_status, which stores a row only when a check's result changes, instead of a row inannotation_eventon every run (about 250 million rows in production). Every writer and reader moves to it. gnomAD and VEP skip alleles already known to be absent at the current source version, and a CAID replacement withdraws the statuses matched through the old CAID.scripts/backfill_annotation_status.pyreplaysannotation_eventinto it. The follow-up dropsannotation_eventin the next release.RowSecurityViolation,MissingGrant,DatabaseBusy), and every mapped exception is answered from one error table per domain. Statement and lock timeouts return 503 without alerting. Slack alerts carry the exception type, location, correlation id and route template, never the message or URL.Bug Fixes
/scores,/countsand/variants/dataCSVs are built 5,000 variants at a time from a server-side cursor into a temporary file, then sent, instead of being built whole in memory. The bytes don't change. A full download of a 650k-variant set peaks at about 350 MB instead of 2.4 GB. The build finishes before the response starts, so a failure is an error status rather than a truncated file, and the transaction and build slot are released before the send, so a slow client holds neither. Clients that don't ask for gzip also get aContent-Length.db_session_ended_by_serverin the canonical log. Release a request's database session when the route returns, not after the response is sent #1036 is the permanent fix.Retry-After: 5instead of 500, and still alerts.Retry-Afteris exposed through CORS, so the ui's retry (feat: retry busy requests and explain rate limits mavedb-ui#789) can read it.Maintenance
Dependencies
authlib. Nothing imported it, and it carried a critical JWS signature-forgery advisory among its 17 alerts.python-jose(algorithm confusion with DER-encoded keys) andecdsa(Minerva timing attack). Neither is reachable: ORCID tokens are decoded withalgorithms=["RS256"]only, and nothing signs or verifies with ECDSA. Leaving python-jose for PyJWT or joserfc is cycle work.setuptoolsstays on 81:eutilsstill importspkg_resources, which later releases removed, and both of its advisories apply only when building packages.Deployment
9a73f37ec1bcand run the backfill with annotation jobs stopped, before this code runs. Once it runs, jobs stop writingannotation_event. Stop both the main worker andmavedb2-prod-worker-campaign-envfor the pass, then resume the campaign.mapperrole in production, or fix: drop an API key's role once its owner loses it #1006 drops the role from the key and mapping requests lose it.release-2026.4.0ontomain, cutrelease-2026.3.5for Drop annotation_event once the backfill has caught up #1015, andpoetry publish --buildfrommain.Issues closed by this release
Generated from the issues linked to PRs merged into
release-2026.3.4for this release, and rewritten on every push. Issues still linked from an open PR are left out. To change the list, change those PRs' linked issues or Closes lines.