Repository navigation
SEL-346: AMW API: per-key usage events and daily per-key summary - #841
PetrefiedThunder wants to merge 4 commits into
Conversation
Linear: SEL-346 Engine: codex (fleet coding engine, Grok Bot dispatch)
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: aad039b80f
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| parameters = {} | ||
| if key_id is not None: | ||
| query += " WHERE key_id = :key_id" |
There was a problem hiding this comment.
Bound the unfiltered usage report
When key_id is omitted, the endpoint queries the entire append-only event history, computes both window-ranked percentiles over every event, and materializes every key/day row into one response. Because one event is added per authenticated request, a normal unfiltered admin call grows without bound and can eventually consume substantial database CPU and application memory; require a date window or add pagination/materialized aggregates before allowing the unfiltered path.
Useful? React with 👍 / 👎.
aad039b to
8d4b2ce
Compare
|
This PR is too large for Bugbot to review. It changes 94,757 lines and 4,025,370 characters. Split the change into smaller pull requests to get a review. |
2d62e2b to
861d46c
Compare
PetrefiedThunder
left a comment
There was a problem hiding this comment.
Independent review (Claude, COMMENT only, not an approval) of head 8d4b2ce9165b5f172c311ceb8c7d589f2bbca06f.
Headline: this head has no test CI, so it is unverified, not green
- The only checks on 8d4b2ce are default-setup CodeQL.
ci.yml(test matrix, lint, postgres_trust, trust_release_gate, RLS Postgres jobs) has never run on this head. Its only run on this branch was on the earlier head aad039b (2026-10-20), and it concluded failure:test (3.12)andtrust_release_gatefailed,test (3.11)was cancelled. The PR body says two bookkeeping test failures were fixed afterward, but no CI has confirmed that. - CodeQL / Analyze (python):
gh pr checksdisplaysfail, but the job API reportsconclusion: cancelledwith zero steps executed, so Python was never analyzed. Treat it as missing coverage, not a pass and not a finding. Leaving the code unchanged in response to that cancellation was the right call, because there was nothing in the code to fix. It is not evidence that the PR is ready. - The two GitHub Advanced Security cache poisoning annotations point at
.github/workflows/railway-deploy.yml, which this PR does not touch. They look pre-existing and are not attributable to this change. mergeStateStatusis BEHIND (main has about 10 newer commits).mergeableis MERGEABLE. Migration 050 is still main's head, so revision 051 does not collide, and no other open PR claims 051.
Suggested next step: rebase or update the branch through a normal push so ci.yml runs on a fresh head, and re-run CodeQL Python. The Postgres-only parts of this PR (the 051 policy, FORCE RLS under enforce, and the view SQL on Postgres) run only in CI's postgres_trust job, which sets TEST_RLS_POSTGRES_ADMIN_URL. They have not run anywhere for this head.
Local verification (this head as-is, behind main, SQLite)
- Targeted tests (
test_api_key_usage*,test_tenant_rls,test_demo_key_funnel,test_dispatch_reconcile_migration): 30 passed, 13 skipped. All 13 skips are the Postgres RLS tests (TEST_RLS_POSTGRES_ADMIN_URL not set). - Full suite on Python 3.12: 5916 passed, 134 skipped, 3 xfailed, 1 failed. The failure was
test_acp_checkout_end_to_end_under_45ms. It passed 3 of 3 runs in isolation. It calls the ACP adapter directly rather than over HTTP, so the new middleware is not in its timed path. I read it as a load flake, not a regression from this PR. ruff check app testspassed. IntelliJ inspections on the changed files reported only known false positives (SQLModel constructor arguments, SQL with no configured data source) and nothing actionable.
Correctness review
Looks right:
- Middleware ordering:
APIKeyUsageMiddlewareis added beforeRateLimitMiddleware, so it runs inside it. The rate limiter sets a freshCredentialAcceptanceholder per request beforecall_next, and the mutable holder is visible to auth in the child task. Requests without a holder skip recording. - The
endpointcolumn usesscope["route"].path(the registered template), never the raw path or query, which matches the metadata-only claim indocs/api-key-usage.md. HEAD requests are recorded as HEAD throughamw_original_method. _note_resolved_keyrecords a valid DB key even when demo-route or tenant checks later return 403. This is intended and tested.- RLS: the writer uses
rls_admin_scope. The admin read route goes throughget_auth_context, which binds the admin scope for bootstrap admins, so the admin-only policy admits it under enforce. The table is added to posture checks and toenable_rls_statements. - The percentile SQL reproduces
percentile_contlinear interpolation with integer arithmetic that behaves the same on SQLite and Postgres. Single-row days resolve correctly (remainder 0). - Write failures are caught and logged by exception type only, without the key or the payload.
Risks and suggestions (non-blocking, in priority order):
- Unbounded growth and an unbounded read. There is no retention or pruning for
api_key_usage_events, andGET /v1/admin/api-keys/usage/dailywith nokey_idwindow-ranks the entire table on every call and returns every key/day row. I agree with the open Codex P2 onapp/routers/api_keys.py:84: add a required or defaulted day range (for examplesince/until) or a limit before this ships, and track retention as a follow-up. - Hot-path cost. Every authenticated DB-key request now does one more session checkout and commit after the routed app returns. The response bytes are already sent by then, but the ASGI cycle and a pool connection are held until the insert finishes. During a database brownout, every request also pays a failing insert attempt. Consider a bounded fire-and-forget queue, or at least a short statement timeout for this insert.
- Migration 051 imports
CREATE_API_KEY_USAGE_DAILY_VIEW_SQLfromapp/db/api_key_usage_view.py. A later edit to that module would silently change what revision 051 creates on fresh databases. Consider freezing the SQL text inside the migration file, or adding a test that pins it. - Docstring wording:
APIKeyUsageMiddlewaresays it records "once per API request". The docs correctly say the insert is best effort and can leave gaps. Consider "at most once" to match. Theapp/main.pycomment already says "at most one event".
Claim language
The new docs are careful: they state the events are best effort, are "usage reporting, not signed audit evidence", and that database administrators can still alter rows. Please keep that framing. These rows are not tamper-evident and should not be described as receipts or audit evidence. In the added lines I found no em or en dashes, no delivery-guarantee overclaims, and no license wording. The Bugbot summary in the PR body contains one em dash (between "method" and "including"), but that text is bot-generated, not authored copy.
Verdict
The code direction is sound and I found no correctness defect that warrants a code change in this review. It is not merge-ready until ci.yml (including postgres_trust and trust_release_gate) passes on a current head and CodeQL Python completes. Bounding the unfiltered admin read (item 1) is worth doing before merge.
PetrefiedThunder
left a comment
There was a problem hiding this comment.
Independent review (grok): PASS
Head: d24e3cf
I reviewed the full diff against origin/main (83342ec), the PR body, CI, and the open review threads. No GitHub issue is linked. The body cites Linear SEL-346, which I could not read from here. I found no blocking defect on this head.
Blocking findings
None.
Non-blocking findings
-
Unbounded admin read (agrees with the open Codex P2).
app/routers/api_keys.py:78selects every row fromapi_key_usage_dailywhenkey_idis omitted, and the view atapp/db/api_key_usage_view.py:29window-ranks the wholeapi_key_usage_eventstable before that filter can help. One event is written per authenticated database-key call (app/core/api_key_usage.py:76). A bootstrap admin can eventually pull an unbounded result and a heavy scan. This is operator availability, not an auth bypass:app/routers/api_keys.py:77callsrequire_bootstrap_admin()first, and that denial is tested. I would add a required or defaulted day window, or a limit, before the table is large. Thekey_idbranch atapp/routers/api_keys.py:83is parameterized and correct, and no test calls it. -
The daily view follows the view owner, not the invoker.
migrations/versions/051_api_key_usage_events.py:52runs the sharedCREATE VIEWfromapp/db/api_key_usage_view.py:21with no PostgreSQLsecurity_invoker. Under the documented NOSUPERUSER owner plus FORCE, the owner is subject to the admin-only policy, andtests/test_tenant_rls.py:565locks that (0 rows withoutapp.rls_bypass, 1 row with it). That test migrates as a NOSUPERUSER owner (tests/test_tenant_rls.py:271defaults to enforce). CI'spostgres_trustjob instead runsalembic upgrade headas thepostgressuperuser. A superuser view owner bypasses RLS, FORCE included, so SELECT on the view would return every key's daily row to a role that was granted the view. Direct SELECT on the table would still fail closed. The HTTP route does not depend on this, because it checks bootstrap admin before querying, and the runtime role can already setapp.rls_bypass(stated inapp/db/tenant_rls.py:26).security_invoker=trueon the PostgreSQL view would make the tested property hold even when a superuser runs the migration. SQLite cannot take that option, so it has to stay on the Postgres branch only. -
The insert is on the request path.
app/core/api_key_usage.py:72awaits the write infinally, after the response has started, and swallows exceptions (app/core/api_key_usage.py:87). A failed write does not change the status, whichtests/test_api_key_usage.py:163covers with a patched raise. The worker and a pool connection stay held until the insert returns or the pool times out, including during a database brownout. A bounded statement timeout, or a queue, would match the best-effort claim more closely. -
Wording.
APIKeyUsageMiddlewaresays it records "once per API request" (app/core/api_key_usage.py:44). The docs andapp/main.py:662correctly say the write is best effort and at most one event. A failed insert leaves a gap (docs/api-key-usage.md:12). I would use "at most once" in the class docstring. The new docs do not call these rows tamper-evident or signed audit evidence, and they say database administrators can alter them. That matches the code. -
Migration SQL is live application text.
migrations/versions/051_api_key_usage_events.py:14importsCREATE_API_KEY_USAGE_DAILY_VIEW_SQL. A later edit changes what revision 051 creates on a fresh database, while a database that already migrated keeps the old view. Sharing one string with SQLitecreate_all(app/db/database.py:480) is why the two cannot drift inside one commit. A test that pins the SQL text would keep history stable. -
Demo kill switch records nothing.
app/core/auth.py:315raises for a disabled demo tenant before_note_resolved_keyatapp/core/auth.py:325. A valid demo key that is refused by the kill switch produces no event. Route denials after the note, and 403s afterget_auth_contextreturns, are recorded. The daily-route 403 intests/test_api_key_usage.py:139is the latter and is counted. The kill-switch gap is small.
What I checked and found sound
- Middleware order:
APIKeyUsageMiddlewareis registered beforeRateLimitMiddleware(app/main.py:665), so it runs inside the limiter and sees the sharedCredentialAcceptanceobject. Invalid and missing credentials write no row (tests/test_api_key_usage.py:86). - The stored endpoint is
scope["route"].path, the registered template. The usage test sends a private query, header, and body and asserts none of them are stored. HEAD is rewritten to GET on a copied scope that setsamw_original_method(app/middleware/head_method.py:45), and the event method is HEAD (tests/test_api_key_usage.py:114). use_countis documented as the bounded-key budget counter (app/schemas/billing.py:815,docs/api-key-usage.md:10). This PR does not change howuse_countadvances.docs/openapi.jsonincludesGET /v1/admin/api-keys/usage/dailyandAPIKeyUsageDailyRowwith the same fields asapp/routers/api_keys.py:51. The OpenAPI description atdocs/openapi.json:5411does not say bootstrap-admin only. The summary says "Admin" and the route enforces it.- Revision 051 revises 050, creates the table, the
(key_id, created_at)index, the Postgres admin-only policy, and the view. Downgrade drops the view before the table. The SQLite migration test pins calls, 4xx, 5xx, p50 25.0, and p95 38.5 for four latencies, which is continuous linear interpolation for percentile 0.5 and 0.95. Single-row days resolve to the only latency. - RLS: the table is in
RLS_POSTURE_TABLESandenable_rls_statements. The writer usesrls_admin_scope. A bootstrap admin bindsadmin_reasonfor the rest of the task (app/core/auth.py:172), so the read session setsapp.rls_bypassunder enforce. I did not re-run that HTTP read on Postgres locally. docs/railway-customer-manifest.example.jsonexpects051_api_key_usage_events.docs/schema-051-rollout.mdsays the operator release checks were not run in the authoring worktree. That sentence is about a qualified image and a private parity run, not about CI. Added lines use ASCII hyphens only, and they do not misstate the license or a delivery guarantee.
Tests I ran
Python 3.11.18, ruff 0.9.0, pytest, no coverage.
ruff checkon the touched app, migration, and test files: all checks passed (exit 0).- Targeted pytest: 64 passed, 13 skipped, 0 failed, 1 warning (pre-existing SQLite reflection warning in
test_dispatch_reconcile_migration.py). About 6 seconds. - All 13 skips are
tests/test_tenant_rls.pywithTEST_RLS_POSTGRES_ADMIN_URL not set, includingtest_api_key_usage_view_requires_admin_bypass. - Files:
tests/test_api_key_usage.py,tests/test_api_key_usage_migration.py,tests/test_tenant_rls.py,tests/test_demo_key_funnel.py,tests/test_dispatch_reconcile_migration.py,tests/test_clean_database_coverage.py,tests/test_migration_rollout_notes.py,tests/test_railway_preflight.py::test_committed_customer_manifest_template_is_non_secret_and_current,tests/test_head_method.py. - I did not rerun the full suite. CI
test (3.12)on this head took 17 minutes, past the local limit. CI already ran it.
CI
gh pr checks 841 on this head: 28 passed, 2 skipping (CodeRabbit, Stateful exploration), 0 failed. Required checks are green, including lint, test (3.11), test (3.12), test (3.13), postgres_trust, postgres_permit_concurrency, production_trust, trust_release_gate, secret_scan, and the Python SDK legs. CodeQL Analyze (python), (javascript-typescript), and (actions) passed. Cursor Bugbot passed in 6m36s.
Bot and earlier review threads
- Codex P2 on
app/routers/api_keys.py:84(unfiltered usage report) is still open and not outdated. The code is unchanged. I agree. Non-blocking. See finding 1. - Two CodeQL cache-poisoning comments on
.github/workflows/railway-deploy.yml:78and:83are resolved and outdated. This diff does not touch that file. Not this PR. - The 2026-10-20 Bugbot comment said the PR was too large to review. That does not describe this head (22 files, 897 additions). The Bugbot check on d24e3cf passed. The PR body summary describes risk and does not list a code defect. No open Bugbot finding.
- The earlier comment-only review on
8d4b2cesaid CI had not run. That head is obsolete.955099588merged main andd24e3cfsynced the OpenAPI schema. CI has since passed on d24e3cf, includingpostgres_trust.
Merge with main
git merge --no-commit --no-ff origin/main printed Already up to date. No conflicts and no merge to abort. HEAD stayed d24e3cf64ffb7233ca43fd30b4e3571c2a0395fb. Local origin/main and GitHub main are both 83342ecd32bb63c64f76933c00dac3599ffe0086, which is also the PR base. The branch is 0 commits behind main and 3 ahead.
GitHub reports mergeable: true and mergeable_state: blocked. The check rollup is SUCCESS. The org ruleset main-protect requires 0 approving reviews and does not require thread resolution. I did not find a failing required check. This review is comment-only and does not approve.
Linear: SEL-346
Coding engine: codex, dispatched by Grok Bot for C.Lee.
What changed
Added revision
051_api_key_usage_events, a metadata-only per-key event table, and the UTC daily SQL view. Database-backed authenticated calls now append one event with the registered route template, status, and latency; failed event writes leave the API response intact. Added a bootstrap-admin-only daily usage endpoint. Documented thatuse_countis the bounded-key budget counter and events are the call-count source. Updated local SQLite view setup, RLS posture coverage, migration rollout notes, and the manifest example revision.How verified
UV_CACHE_DIR=/private/tmp/sel346-uv-cache ~/metacode/fleet/heavy uv run --with-requirements requirements-dev.txt pytest tests/ -q -m 'not proof and not perf' --no-cov, 5,180 passed, 131 skipped, 737 deselected, 3 xfailed; two migration bookkeeping tests failed. Both failures were fixed afterward.UV_CACHE_DIR=/private/tmp/sel346-uv-cache ~/metacode/fleet/heavy uv run --with-requirements requirements-dev.txt pytest tests/test_api_key_usage.py tests/test_api_key_usage_migration.py tests/test_clean_database_coverage.py tests/test_demo_key_funnel.py tests/test_dispatch_reconcile_migration.py tests/test_tenant_rls.py tests/test_head_method.py tests/test_jwt_authority.py tests/test_migration_rollout_notes.py tests/test_railway_preflight.py::test_committed_customer_manifest_template_is_non_secret_and_current -q --no-cov, 84 passed, 13 skipped.UV_CACHE_DIR=/private/tmp/sel346-uv-cache ~/metacode/fleet/heavy uv run --with-requirements requirements-dev.txt mypy app, passed, 214 source files.ruff check .andgit diff --check, passed.Not done / follow-ups
PostgreSQL migration, enforced RLS, and admin view access were not run locally because the required isolated PostgreSQL fixture is unavailable; the new PostgreSQL test is skipped locally and will run in CI. The full fast suite was not rerun after the two bookkeeping fixes; their tests and the relevant usage tests passed in the focused rerun. Event inserts are best effort, so failed writes can leave reporting gaps. The application only appends events; database administrators can alter them. No commit, push, deployment, or PR was made; the wrapper handles publication for SEL-346.
Note
Medium Risk
Adds request-path middleware and auth ContextVar mutations on every authenticated call, plus a new trust table/view and migration boundary; event writes are best-effort so reporting gaps are possible.
Overview
This PR adds metadata-only per-key HTTP usage tracking for database-backed API keys, backed by Alembic revision
051_api_key_usage_events.Authenticated requests with a resolved DB key now append one row to
api_key_usage_events(route template, method—including original method for HEAD—status, latency, tenant).APIKeyUsageMiddlewarerecords after the routed handler; writes use an admin RLS scope and never fail the API response. Auth extendsCredentialAcceptancesokey_idis captured even when later authorization (e.g. demo route denial) returns 403.A portable
api_key_usage_dailyview aggregates calls, 4xx/5xx, and p50/p95 latency by key and UTC day. Bootstrap admins can query it viaGET /v1/admin/api-keys/usage/daily. Schema boot checks now require the table and view; SQLitecreate_allcreates the view when missing.api_keys.use_countis documented as bounded-key budget only, not total traffic. RLS posture includesapi_key_usage_eventsas admin-only.Reviewed by Cursor Bugbot for commit b9981ca. Bugbot is set up for automated code reviews on this repo. Configure here.