Skip to content

SEL-346: AMW API: per-key usage events and daily per-key summary - #841

Open
PetrefiedThunder wants to merge 4 commits into
mainfrom
agent/codex/sel-346
Open

PetrefiedThunder wants to merge 4 commits into
mainfrom
agent/codex/sel-346

Conversation

@PetrefiedThunder

@PetrefiedThunder PetrefiedThunder commented Oct 20, 2026 •

Copy link
Copy Markdown
Collaborator

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 that use_count is 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 . and git 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). APIKeyUsageMiddleware records after the routed handler; writes use an admin RLS scope and never fail the API response. Auth extends CredentialAcceptance so key_id is captured even when later authorization (e.g. demo route denial) returns 403.

A portable api_key_usage_daily view aggregates calls, 4xx/5xx, and p50/p95 latency by key and UTC day. Bootstrap admins can query it via GET /v1/admin/api-keys/usage/daily. Schema boot checks now require the table and view; SQLite create_all creates the view when missing. api_keys.use_count is documented as bounded-key budget only, not total traffic. RLS posture includes api_key_usage_events as admin-only.

Reviewed by Cursor Bugbot for commit b9981ca. Bugbot is set up for automated code reviews on this repo. Configure here.

Linear: SEL-346
Engine: codex (fleet coding engine, Grok Bot dispatch)
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-20T20:39:39.352504Z aad039b PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread app/routers/api_keys.py
Comment on lines +82 to +84
parameters = {}
if key_id is not None:
query += " WHERE key_id = :key_id"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@cursor

cursor Bot commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

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.

@PetrefiedThunder PetrefiedThunder left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) and trust_release_gate failed, 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 checks displays fail, but the job API reports conclusion: cancelled with 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.
  • mergeStateStatus is BEHIND (main has about 10 newer commits). mergeable is 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 tests passed. 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: APIKeyUsageMiddleware is added before RateLimitMiddleware, so it runs inside it. The rate limiter sets a fresh CredentialAcceptance holder per request before call_next, and the mutable holder is visible to auth in the child task. Requests without a holder skip recording.
  • The endpoint column uses scope["route"].path (the registered template), never the raw path or query, which matches the metadata-only claim in docs/api-key-usage.md. HEAD requests are recorded as HEAD through amw_original_method.
  • _note_resolved_key records 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 through get_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 to enable_rls_statements.
  • The percentile SQL reproduces percentile_cont linear 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):

  1. Unbounded growth and an unbounded read. There is no retention or pruning for api_key_usage_events, and GET /v1/admin/api-keys/usage/daily with no key_id window-ranks the entire table on every call and returns every key/day row. I agree with the open Codex P2 on app/routers/api_keys.py:84: add a required or defaulted day range (for example since/until) or a limit before this ships, and track retention as a follow-up.
  2. 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.
  3. Migration 051 imports CREATE_API_KEY_USAGE_DAILY_VIEW_SQL from app/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.
  4. Docstring wording: APIKeyUsageMiddleware says 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. The app/main.py comment 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 PetrefiedThunder left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. Unbounded admin read (agrees with the open Codex P2). app/routers/api_keys.py:78 selects every row from api_key_usage_daily when key_id is omitted, and the view at app/db/api_key_usage_view.py:29 window-ranks the whole api_key_usage_events table 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:77 calls require_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. The key_id branch at app/routers/api_keys.py:83 is parameterized and correct, and no test calls it.

  2. The daily view follows the view owner, not the invoker. migrations/versions/051_api_key_usage_events.py:52 runs the shared CREATE VIEW from app/db/api_key_usage_view.py:21 with no PostgreSQL security_invoker. Under the documented NOSUPERUSER owner plus FORCE, the owner is subject to the admin-only policy, and tests/test_tenant_rls.py:565 locks that (0 rows without app.rls_bypass, 1 row with it). That test migrates as a NOSUPERUSER owner (tests/test_tenant_rls.py:271 defaults to enforce). CI's postgres_trust job instead runs alembic upgrade head as the postgres superuser. 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 set app.rls_bypass (stated in app/db/tenant_rls.py:26). security_invoker=true on 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.

  3. The insert is on the request path. app/core/api_key_usage.py:72 awaits the write in finally, after the response has started, and swallows exceptions (app/core/api_key_usage.py:87). A failed write does not change the status, which tests/test_api_key_usage.py:163 covers 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.

  4. Wording. APIKeyUsageMiddleware says it records "once per API request" (app/core/api_key_usage.py:44). The docs and app/main.py:662 correctly 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.

  5. Migration SQL is live application text. migrations/versions/051_api_key_usage_events.py:14 imports CREATE_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 SQLite create_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.

  6. Demo kill switch records nothing. app/core/auth.py:315 raises for a disabled demo tenant before _note_resolved_key at app/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 after get_auth_context returns, are recorded. The daily-route 403 in tests/test_api_key_usage.py:139 is the latter and is counted. The kill-switch gap is small.

What I checked and found sound

  • Middleware order: APIKeyUsageMiddleware is registered before RateLimitMiddleware (app/main.py:665), so it runs inside the limiter and sees the shared CredentialAcceptance object. 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 sets amw_original_method (app/middleware/head_method.py:45), and the event method is HEAD (tests/test_api_key_usage.py:114).
  • use_count is documented as the bounded-key budget counter (app/schemas/billing.py:815, docs/api-key-usage.md:10). This PR does not change how use_count advances. docs/openapi.json includes GET /v1/admin/api-keys/usage/daily and APIKeyUsageDailyRow with the same fields as app/routers/api_keys.py:51. The OpenAPI description at docs/openapi.json:5411 does 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_TABLES and enable_rls_statements. The writer uses rls_admin_scope. A bootstrap admin binds admin_reason for the rest of the task (app/core/auth.py:172), so the read session sets app.rls_bypass under enforce. I did not re-run that HTTP read on Postgres locally.
  • docs/railway-customer-manifest.example.json expects 051_api_key_usage_events. docs/schema-051-rollout.md says 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 check on 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.py with TEST_RLS_POSTGRES_ADMIN_URL not set, including test_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:78 and :83 are 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 8d4b2ce said CI had not run. That head is obsolete. 955099588 merged main and d24e3cf synced the OpenAPI schema. CI has since passed on d24e3cf, including postgres_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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants