Skip to content

feat(ratelimit): add an hourly request quota per sign-in session and an API clients card - #3075

Merged
Quick104 merged 8 commits into
mainfrom
t3/diagnose-prod-outage
Oct 31, 2026
Merged

Quick104 merged 8 commits into
mainfrom
t3/diagnose-prod-outage

Conversation

@Quick104

@Quick104 Quick104 commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: changes #1188 C1, #1217 C1 and #1218 C1 (all not yet run)

Silo's rate limits only look at short windows, so a client that stays under them can poll the API around the clock, and nothing in the admin UI shows it. On one production server, a single household's integration sent about 700,000 requests a day, about 70% of all API traffic, re-reading the same catalog items roughly every 40 minutes. It never came near a limit: the account budget is 480 requests a second and 24,000 a minute. The traffic also grew the request log by about 2.5 GB a week.

This adds an hourly request quota per sign-in session, which can log or refuse that traffic, and a dashboard card that shows which sessions make the most requests and lets an admin sign one out.

Approach

  • Session quota. Each sign-in session gets a token bucket that holds 30,000 requests and refills at 10,000 an hour (ratelimit.session.burst, ratelimit.session.requests_per_hour). ratelimit.session.mode is off, log (the default: serve and log once per session every 10 minutes) or enforce (429 with Retry-After). It runs in the existing limiter after the account check, on the same backend. With Redis, one bucket per session is shared by every instance, timed by the Redis clock, and the quota shares the window limiter's outage pause. Settings changes keep bucket balances.
  • What it doesn't count: anything under /stream and /playback (so a player keeps reporting progress, replanning and stopping after its session runs out), the other media transfer routes, API-key requests (they have their own tiers), admins, impersonation, and signing out (POST /api/v2/auth/logout and GET /api/v2/auth/provider-logout, so a session that spent its quota can still end itself). ratelimit.QuotaExemptPathPattern defines the exempt routes once, for Go and for SQL; a test fails if a route in the native media route list isn't exempt. Jellyfin-compatible sessions are not covered; they have their own session model.
  • Sizing. Against three months of a production request log, a flat 10,000 an hour would have refused requests from 15 sessions besides the polling integration, including first-party web and Android sessions that peak at 17,000 to 19,000 in an hour. With the 30,000 burst and the exemptions, the integration is held to 10,000 an hour and only one other session is affected: a third-party client's full-library sync, which would have had 11,000 of 64,000 requests deferred. Starting in log mode lets an admin check the card before enforcing.
  • Busiest API clients card. A hidden task summarizes activity_log into a new api_client_usage_hourly table every 15 minutes, on one server at a time (a transaction-scoped advisory lock), in UTC hours, kept for 30 days and leaving out what the quota leaves out. GET /api/v2/admin/stats/api-clients and GET /api/v2/admin/stats/api-clients/{session_id}/endpoints (admin-only; api_clients in the dashboard capabilities) serve the card. It ranks sessions over 1 hour to 30 days, each window read from the start of the hour it begins in, with share of traffic, 429 count and signed-out state. Opening a row shows the routes the session called in the last 24 hours and a button that signs out just that session through the existing admin login-session revoke. The card is in the Add widget sheet, not the default layout.
  • Settings UI: a new "Per sign-in session" group under Security, Rate limiting.
  • /api/v1 stays frozen: the v1 rate-limit config endpoints neither return nor accept session_quota.
  • Clients: no change needed in silo-apple or silo-android. First-party sessions stay well under the quota, and it starts in log mode. Docs: docs/auth-api.md (Session quota) and docs/admin-api.md. The user manual needs an update for the new setting and card; that issue will follow on siloserver.org.

Validation

  • Go build, vet, gofmt, make lint-changed (0 issues) and make lint-router-recovery pass.
  • make test-go passes except TestPlaybackInfoWithoutStripOrToneMapStillHasNoRoute and TestPlaybackInfoSkipsStripWhenRPUCannotBeStripped in internal/jellycompat, which fail the same way on the base commit on the test machine; they depend on the host's ffmpeg.
  • The new DB contract TestAPIUsageSummaryDB passes against a migrated pgvector database, including with the database session in a +05:30 time zone. It is listed in scripts/ci/db-contracts.txt.
  • The Redis bucket script was checked by hand against Redis 8 (burst, refusal, refill, key expiry). CI has no Redis, so the committed test covers the outage fallback only.
  • Web lint, format, build, bundle budget and make test-web pass.
  • Contract and hygiene targets pass. verify-actionlint was not run because actionlint 1.7.12 isn't installed; no workflows changed.
  • Rebased onto current main. On a disposable test server built from main and then rebuilt from this branch, the migration applied out of order (its version sorts before five newer migrations on main). Enforce at 60 an hour with a 20 burst refused requests 21 to 25 with Retry-After. The drained session could still sign out, and its token then got 401. The card listed sessions with their 429 counts, showed an idle session's routes as empty, and signing a session out from the card revoked its token.
  • The tests added with the review fixes fail before them: the one-hour window row in TestAPIUsageSummaryDB and the sign-out rows in TestSessionQuotaMiddleware. TestAPIUsageSummaryDB also runs a summary pass on a one-connection pool and checks that a pass is skipped while another server holds the lock.
  • Run by hand on a local server: with a 60/hour, 20-burst quota in enforce mode, a user session got 20 requests and then 429 with Retry-After: 60, and an admin session was never limited. An invalid mode was rejected with 422. The card listed sessions with the right 429 counts and left out the admin session and playback calls. Signing a session out from the card revoked its token while other users kept working. Saving Enforce from the Security page persisted.

Evidence

Evidence: https://evidence.siloserver.org/r/silo-server/pr-3075/

Surface and build: web admin Security settings and dashboard, desktop and phone width. "Before" is main and "after" is this branch, on one test server rebuilt in place, so both use the same data.

Risks

  • The migration adds one table and changes nothing existing.
  • After upgrade nothing is refused: the default mode is log, which logs one line per over-quota session every 10 minutes.
  • On Redis-backed deployments every counted request makes one more Redis call, even in log mode.
  • In enforce mode, a third-party client that syncs a large library may get 429 and has to honor Retry-After.
  • The summary task re-reads up to two hours of activity_log every 15 minutes, or up to 48 hours after downtime.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • Each test this pull request adds meets "Decide what to test" in CONTRIBUTING.md.
  • The Evidence section shows every change a user can see, or says there is none.

AI Disclosure

  • Harness: Claude Code, running in T3 Code
  • Tool(s): Claude Code, GitHub CLI
  • Model(s): claude-opus-5-5
  • Involvement: Fully AI-generated; human verification pending
  • Adversarial review: An independent Claude Code review pass (code-review at high effort, claude-opus-5-5) read the full diff for correctness, security and performance. It found ten issues: playback control calls refused in enforce mode, an unanchored exemption pattern, time-zone-dependent hourly buckets, a new field on frozen /api/v1, admins and impersonation counted on the card, an unbounded per-session endpoint scan, a second Redis outage pause, a leaked eviction goroutine, late activity rows dropped, and one extra Redis call per request. The first nine are fixed with tests where they apply; the extra Redis call is kept and listed under Risks.
  • Review after rebase: Claude Code (claude-opus-5-5) with three review subagents and one Codex round (gpt-6.1-sol) found six more issues, all fixed on this branch: the summary pass ran on every server at once, the card's 1-hour view read only the current clock hour, an idle session's routes showed as a load error, a session that spent its quota couldn't sign out in enforce mode, clock skew between servers could trigger a 48-hour rescan, and docs/admin-api.md didn't describe session_quota. Kody then found that the first lock fix could deadlock a one-connection pool; that is fixed too. Codex's security review then found that quota buckets were kept a week after their last request, so repeated sign-ins could grow memory; a bucket now expires once any allowed rate would have refilled it.

Note

Add per-sign-in-session hourly request quota and an API clients dashboard

  • Adds a configurable session quota (off/log/enforce modes, default log at 10,000 requests/hour with a 30,000 burst) enforced via token buckets in middleware.go. Checks run after the account quota and before the global limiter; admins, API keys, impersonated requests, and media/sign-out/download paths are exempt.
  • Implements the buckets in session_quota.go: a Redis Lua-backed limiter shared across servers, with an in-memory fallback during Redis outages. Buckets expire after at most 7 days of inactivity; a burst must refill within one week.
  • Adds admin API v2 endpoints (GET /api/v2/admin/stats/api-clients and per-session endpoints) backed by hourly summaries in the new api_client_usage_hourly table, refreshed every 15 minutes by a scheduled task in summarize_api_usage.go.
  • Adds an admin UI section for the session quota in SecurityAccessSettings.tsx and a Busiest API clients dashboard widget with a revoke-session action.
  • Behavioral Change: over-quota requests are served in default log mode and rejected with 429 only in enforce mode; summaries exclude impersonated, admin, and quota-exempt traffic, and the frozen v1 rate-limit handlers omit the new session_quota field.

Macroscope summarized 5b891ef.

@silo-triage silo-triage Bot added the size/XXL 1000–2999 added + deleted lines (all files); change volume, not priority. label Oct 25, 2026
@silo-kody

silo-kody Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 25, 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-31T04:27:09.101848Z 5b891ef New commits
🔒 Security Review ✅ Completed 2026-10-31T04:27:57.040715Z 5b891ef New commits

Security findings

Advisory findings (1)

ℹ️ 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.

@macroscopeapp

macroscopeapp Bot commented Oct 25, 2026

Copy link
Copy Markdown

The Evidence URL still contains the literal PRNUMBER, so it does not point to this pull request’s published evidence page. Replace it with the actual PR evidence URL (https://evidence.siloserver.org/r/silo-server/pr-3075/). The visible effects need evidence showing:

  • web/src/pages/admin-settings/SecurityAccessSettings.tsx: before-and-after desktop and phone-width captures of the per-session quota controls.
  • web/src/components/admin/dashboard/widgets/ApiClientsWidget.tsx: before-and-after desktop and phone-width captures of the API clients card and expanded details; include a short recording if showing the multi-step sign-out flow.
  • internal/ratelimit/middleware.go: before-and-after API response excerpts for a quota-exhausted request, showing the new 429 behavior in enforce mode.

Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness.

Posted via Macroscope — Visible change evidence

@silo-triage silo-triage Bot added enhancement New feature or request go Pull requests that update go code javascript Pull requests that update javascript code priority: P2 Limited scope, workaround exists, or polish labels Oct 25, 2026
@coderabbitai

coderabbitai Bot commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: d5379dcd-8dd3-4619-853f-f299090b0e9d
Commits

Reviewing files that changed from the base of the PR and between c7ec35b and 5cb9e1f.

Files selected for processing: 13
  • cmd/silo/main.go
  • contracts/api/v2/openapi.json
  • docs/admin-api.md
  • docs/auth-api.md
  • internal/apiusage/apiusage.go
  • internal/apiusage/apiusage_db_test.go
  • internal/apiv2/admin_api_clients.go
  • internal/ratelimit/middleware.go
  • internal/ratelimit/session_quota_test.go
  • internal/taskmanager/tasks/summarize_api_usage.go
  • web/src/api/v2/schema.ts
  • web/src/components/admin/dashboard/widgets/ApiClientsWidget.tsx
  • web/src/hooks/queries/admin/apiClients.ts
Files skipped from review as they are similar to previous changes: 3
  • docs/auth-api.md
  • web/src/api/v2/schema.ts
  • internal/apiv2/admin_api_clients.go

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 2 remain after this review.

Walkthrough

This change adds hourly API-usage summaries, admin endpoints and a dashboard widget for session and endpoint statistics, and configurable per-session request quotas with memory and Redis-backed token buckets.

Changes: API Client Usage

Layer / File(s) Summary
Hourly summaries and task wiring
migrations/sql/20261025174621_add_api_client_usage_hourly.sql, internal/apiusage/*, internal/taskmanager/tasks/summarize_api_usage.go, cmd/silo/main.go, internal/apiusage/apiusage_db_test.go, scripts/ci/db-contracts.txt
The store aggregates eligible requests and refusals by session and UTC hour, provides client and endpoint statistics, and prunes old summaries. A hidden task runs at startup and every 15 minutes. The application initializes the store from the database and registers the task.
Admin usage endpoints and contracts
internal/apiv2/admin_api_clients.go, internal/apiv2/admin_api_clients_test.go, internal/api/router.go, internal/apiv2/router.go, internal/apiv2/document.go, internal/apiv2/admin_dashboard_capabilities*, contracts/api/v2/openapi.json, web/src/api/v2/schema.ts, web/src/api/v2/operations.ts, internal/api/testdata/media_routes.txt, docs/admin-api.md
Two admin GET endpoints return session rankings and per-session endpoint counts. The API advertises the api_clients capability. The API contracts, route fixtures, and admin API documentation include the new endpoints.
API-client dashboard widget
web/src/hooks/queries/admin/apiClients.ts, web/src/hooks/queries/keys.ts, web/src/components/admin/dashboard/widgets/ApiClientsWidget.tsx, web/src/components/admin/dashboard/registry.tsx, web/src/components/admin/dashboard/types.ts, web/src/pages/AdminDashboard.tsx
The dashboard widget displays up to eight sessions and loads endpoint details for expanded rows. Active sessions can be signed out. Dashboard refresh invalidates the API-client queries.

Session Quotas

Layer / File(s) Summary
Quota settings and admin controls
internal/ratelimit/config.go, internal/ratelimit/ratelimit.go, internal/api/handlers/rate_limits.go, internal/api/handlers/rate_limits_test.go, internal/apiv2/admin_rate_limit_*, contracts/api/v2/openapi.json, web/src/api/v2/schema.ts, web/src/api/types.ts, web/src/pages/admin-settings/SecurityAccessSettings.tsx, docs/auth-api.md
Rate-limit configuration includes off, log, and enforce modes, an hourly request rate, and a burst. The admin API supports reading and updating these fields, validates quota values, and omits the setting from v1 responses and updates. The security settings page provides controls for the quota.
Token-bucket enforcement
internal/ratelimit/session_quota.go, internal/ratelimit/middleware.go, internal/ratelimit/session_quota_test.go, internal/api/media_routes_test.go, docs/auth-api.md
Memory and Redis-backed limiters track quota tokens. Middleware skips specified request categories and media paths, logs over-quota requests in log mode, and rejects them in enforce mode. Tests cover bucket behavior, middleware modes, and Redis outage fallback.

Estimated code review effort: 4 (Complex) | ~50 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant AdminDashboard
  participant ApiClientsWidget
  participant useAdminApiClients
  participant AdminAPIClientsRoute
  participant apiusageStore
  participant PostgreSQL
  AdminDashboard->>ApiClientsWidget: render widget
  ApiClientsWidget->>useAdminApiClients: request session statistics
  useAdminApiClients->>AdminAPIClientsRoute: GET API-client statistics
  AdminAPIClientsRoute->>apiusageStore: query usage statistics
  apiusageStore->>PostgreSQL: read hourly summaries
Loading
sequenceDiagram
  participant Client
  participant RateLimitMiddleware
  participant RedisQuotaLimiter
  participant Redis
  Client->>RateLimitMiddleware: send request with session token
  RateLimitMiddleware->>RedisQuotaLimiter: check session quota
  RedisQuotaLimiter->>Redis: refill bucket and spend token
  Redis-->>RedisQuotaLimiter: quota result
  RedisQuotaLimiter-->>RateLimitMiddleware: allow or deny
  RateLimitMiddleware-->>Client: serve request or return 429
Loading

Possibly related PRs

  • Silo-Server/silo-server#2719: Changes authenticated account rate limiting and middleware ordering, which overlap with the per-session quota check added here.

Suggested labels: api-v2, impact: usability, needs-review, evidence-required

Suggested reviewers: rhainland

Merge Risk: Minimal · up to 5cb9e

No merge-blocking issue is established by the supplied evidence.

Security architecture risk: Low · up to 5cb9e

The inspected quota and reporting paths preserve existing authentication and administrator controls. No material security regression was established, but deployment behavior and some affected areas remain only partially verified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The new allowance is independently scoped to each authenticated sign-in session, not to an entire account. Multiple sessions have separate buckets, while the existing IP, account, API-key, and global checks remain in the inspected request path. Reporting exposes server-wide session metadata only through acting-admin routes.

Trust Boundaries and Controls

  • observed — The v2 gate chain authenticates before invoking the rate limiter and subsequently applies viewer and acting-admin gates where required. Production wiring supplies the shared limiter, resolving the potential nil-claims quota bypass caused by reversed middleware ordering.
  • observed — Quota eligibility excludes admins, impersonation, API keys, and explicit media/logout paths. The path expression anchors its alternatives under the native API prefixes and is reused by reporting SQL. These exclusions skip the session quota, not the surrounding existing limits.

Resilience and Maintainability Implications

  • observed — Memory bucket mutation is mutex-protected; Redis refill, spend, and expiry execute in one script with a bounded call timeout. Buckets expire after seven idle days, and administrative validation requires refill within that interval, preventing ordinary idle cleanup from prematurely replenishing a depleted bucket.
Pre-merge checks: Passed 4
Check name Status Explanation
Title check Passed The title clearly identifies both primary changes: the per-sign-in-session hourly rate quota and the API clients dashboard card.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The pull request description clearly explains the session quota, API-client usage dashboard, settings, endpoints, migration, tests, validation results, and risks. These topics directly match the chang…
Full details: Description check

Explanation

The pull request description clearly explains the session quota, API-client usage dashboard, settings, endpoints, migration, tests, validation results, and risks. These topics directly match the changeset.

Finishing Touches
Generate docstrings
  • Commit to this branch
  • Create a new PR
Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment thread internal/ratelimit/session_quota.go Resolved
@coderabbitai coderabbitai Bot added api-v2 API v2 / Huma migration program (epic #135); long-running, stacked by phase evidence-required Needs before-and-after evidence before the Evidence check passes impact: usability Core flow broken or severely blocked needs-review Needs maintainer review to resolve uncertain classification, scope, or changed evidence. labels Oct 25, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments: 1
web/src/api/types.ts: 1

4865-4870: Trivial · Maintainability & Code Quality · Quick win

Derive RateLimitSessionQuota from the generated v2 schema.

This change adds a handwritten mirror of AdminRateLimitSessionQuota. The same PR regenerates web/src/api/v2/schema.ts, so the generated type already exists. A handwritten copy can drift from the contract. The mode union is the most likely field to drift.

This file already derives other types from the generated schema, for example DisplayRating. Use the same pattern here.

♻️ Proposed change
-export interface RateLimitSessionQuota {
-  mode: "off" | "log" | "enforce";
-  requests_per_hour: number;
-  burst: number;
-}
+export type RateLimitSessionQuota = V2Components["schemas"]["AdminRateLimitSessionQuota"];

As per path instructions: "The handwritten mirror in web/src/api/types.ts is retired as each consumer moves to the generated surface."

Source: Coding guidelines


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 7ce416b1-78a1-4ea4-bfb4-ec77b9b3d56e
Commits

Reviewing files that changed from the base of the PR and between 6de6d5e and b40f9a1.

Files selected for processing: 36
  • cmd/silo/main.go
  • contracts/api/v2/openapi.json
  • docs/admin-api.md
  • docs/auth-api.md
  • internal/api/handlers/rate_limits.go
  • internal/api/media_routes_test.go
  • internal/api/router.go
  • internal/api/testdata/media_routes.txt
  • internal/apiusage/apiusage.go
  • internal/apiusage/apiusage_db_test.go
  • internal/apiv2/admin_api_clients.go
  • internal/apiv2/admin_api_clients_test.go
  • internal/apiv2/admin_dashboard_capabilities.go
  • internal/apiv2/admin_dashboard_capabilities_test.go
  • internal/apiv2/admin_rate_limit_reads.go
  • internal/apiv2/admin_rate_limit_types.go
  • internal/apiv2/admin_rate_limit_write.go
  • internal/apiv2/document.go
  • internal/apiv2/router.go
  • internal/ratelimit/config.go
  • internal/ratelimit/middleware.go
  • internal/ratelimit/ratelimit.go
  • internal/ratelimit/session_quota.go
  • internal/ratelimit/session_quota_test.go
  • internal/taskmanager/tasks/summarize_api_usage.go
  • migrations/sql/20261025174621_add_api_client_usage_hourly.sql
  • scripts/ci/db-contracts.txt
  • web/src/api/types.ts
  • web/src/api/v2/operations.ts
  • web/src/api/v2/schema.ts
  • web/src/components/admin/dashboard/registry.tsx
  • web/src/components/admin/dashboard/types.ts
  • web/src/components/admin/dashboard/widgets/ApiClientsWidget.tsx
  • web/src/hooks/queries/admin/apiClients.ts
  • web/src/hooks/queries/keys.ts
  • web/src/pages/admin-settings/SecurityAccessSettings.tsx

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 3 remain after this review.

Comment thread docs/admin-api.md Resolved
@silo-kody

silo-kody Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@Quick104

Copy link
Copy Markdown
Contributor Author

The Evidence line now points to https://evidence.siloserver.org/r/silo-server/pr-3075/, and the page is published with before-and-after desktop and phone captures of the Security settings and the dashboard's Add widget sheet, plus the new card.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 0c1857a8-1ed3-462f-b226-dd42fbb08388
Commits

Reviewing files that changed from the base of the PR and between b40f9a1 and df4a66d.

Files selected for processing: 8
  • contracts/api/v2/breaking-approvals.json
  • docs/admin-api.md
  • docs/auth-api.md
  • internal/ratelimit/session_quota.go
  • internal/ratelimit/session_quota_test.go
  • web/src/api/types.ts
  • web/src/components/admin/dashboard/widgets/ApiClientsWidget.tsx
  • web/src/pages/AdminDashboard.tsx
Files skipped from review as they are similar to previous changes: 3
  • web/src/components/admin/dashboard/widgets/ApiClientsWidget.tsx
  • docs/auth-api.md
  • docs/admin-api.md

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 3 remain after this review.

Comment thread internal/ratelimit/session_quota.go Resolved
@silo-kody

silo-kody Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌
⚠️ 2 Kody Rule(s) were not evaluated

These rules declare that they need repository context beyond this diff, and the review could not retrieve it, so they were not judged on this pull request:

  • Preserve optional store capabilities through production wrappers
  • Detach mandatory cleanup from request cancellation and bound its lifetime

@macroscopeapp

macroscopeapp Bot commented Oct 25, 2026

Copy link
Copy Markdown

The corrected Evidence link and the reported desktop/phone captures cover the settings and dashboard card. The described evidence still does not establish:

  • internal/ratelimit/middleware.go: before-and-after response excerpts for the same request, showing the exhausted-session 429 and Retry-After in enforce mode.
  • web/src/components/admin/dashboard/widgets/ApiClientsWidget.tsx: captures of the expanded session/route details, plus a short recording of the confirm-and-revoke sign-out flow.

Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness.

Posted via Macroscope — Visible change evidence

@Quick104

Copy link
Copy Markdown
Contributor Author

The evidence page now covers both gaps: before-and-after response excerpts for the same request sequence (the base commit serves all 25 requests; this branch, with the quota enforced at 60 an hour and a 20 burst, answers requests 21 to 25 with 429 and Retry-After: 60), and a recording of opening a session's row, confirming the sign-out, and the row afterwards. https://evidence.siloserver.org/r/silo-server/pr-3075/

@macroscopeapp

macroscopeapp Bot commented Oct 25, 2026

Copy link
Copy Markdown

Validation tasks: omits the Account sessions Web admin case. ApiClientsWidget adds another path to inspect a session and sign it out through the existing admin session-revoke route; this maps to #1188 C1. That case is Not run, so no prior result is invalidated, but the new sign-out entry point should be included in initial validation.

Suggested line:
Validation tasks: changes #1188 C1, #1217 C1, and #1218 C1 (all not yet run)

Automated check: Macroscope check run agent (gpt-6-luna). No validation was performed.

Posted via Macroscope — v1 validation impact

@Quick104

Copy link
Copy Markdown
Contributor Author

Added: Validation tasks: changes #1188 C1, #1217 C1 and #1218 C1 (all not yet run). The card's sign-out uses the same admin session-revoke route #1188 C1 exercises.

@silo-kody

silo-kody Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@Quick104 Quick104 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Review of c7ec35b4f (this branch rebased onto current main). Six findings; I'm fixing all six in a commit on this branch, so there's nothing for you to change.

Minor: docs/admin-api.md doesn't describe session_quota in the rate-limit config section. GET and PATCH /api/v2/admin/rate-limits/config now carry session_quota and return 422 for an unknown mode or a burst that would take more than a week to refill. The "Rate-limit configuration reads" section still lists only API-key tiers and auth endpoint budgets, so a third-party admin tool built from that doc won't know about the field or the new 422. Repair: name the field and its 422 cases there and link to Session quota in auth-api.md. I'm fixing this in a commit on this branch, so there's no need to change it yourself.

🤖 Claude Code (claude-opus-5-5)

Comment thread internal/apiusage/apiusage.go Resolved
Comment thread internal/ratelimit/middleware.go Resolved
Comment thread internal/apiusage/apiusage.go Resolved
@silo-kody

silo-kody Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@silo-kody

silo-kody Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

1 similar comment
@silo-kody

silo-kody Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@Quick104

Quick104 commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor Author

Review summary

Reviewed head: 5b891efce. I rebased the branch onto main twice and force-pushed it, so earlier commit hashes no longer exist. The second rebase, onto 312d70c16, only changed the DB contract list. The conflicts were the dashboard capability fields, the DB contract list, the docs, and the generated contract files, which I regenerated. Main had already emptied breaking-approvals.json, so that part of the PR dropped out.

Fixed on this branch

  • The summary pass ran on every API server at once. It now takes a transaction-scoped advisory lock and runs both statements in that transaction (c196d5859). My first fix, a session lock in the task, could deadlock a one-connection pool, as Kody pointed out.
  • The card's 1-hour view read only the current clock hour, so it was empty for the first minutes of each hour. Windows now start at the beginning of the hour they begin in, as the playback activity card does.
  • An idle session listed in the 7-day view showed a load error when opened. It now shows "No requests in that time."
  • In enforce mode, a session that had spent its quota got 429 on POST /auth/logout and GET /auth/provider-logout. The web app then cleared its credentials while the server session stayed valid. Both routes are now exempt.
  • Clock skew between servers could make a pass rescan 48 hours of activity_log. The last hour is now clamped to the current one.
  • docs/admin-api.md didn't describe session_quota or its 422s in the rate-limit config section.
  • Every quota bucket was kept a week after its last request, so a signed-in user who kept signing in again grew server memory (or Redis) by one bucket per session. A bucket now expires once any allowed rate would have refilled it: a drained bucket still lasts a week, and one a client barely used goes within seconds (5b891efce, from Codex's security review).
  • 5cb9e1f5b broke the web type check. 98999eea fixed it before CI finished.

How it was verified

  • On a test server built from main and then rebuilt from this branch, with the same data: the migration applied out of order (its version sorts before five newer migrations on main). Enforce at 60 an hour with a 20 burst refused requests 21 to 25 with Retry-After, and the drained session still signed out. The card listed sessions with their 429 counts. Signing a session out from the card revoked its token, which then got 401.
  • The tests added with the fixes fail before them: the one-hour window row in TestAPIUsageSummaryDB returned 2 of 7 requests, and the sign-out rows in TestSessionQuotaMiddleware got 429. The DB contract also covers a pass on a one-connection pool and a pass skipped while another server holds the lock; replacing the lock query with SELECT true fails that check.
  • Every test the PR itself adds fails to build on main, because each tests new code, so the live run is the proof for the feature.
  • A Codex round (gpt-6.1-sol) on c7ec35b4f found one issue, the sign-out refusal, which matched one of my findings.

Left for maintainers

  • Maintainer decision: default mode. log counts every non-admin request on every install. That costs one more Redis call per request on Redis deployments. The Busiest API clients card works in every mode, including off. The options are to keep log so over-quota sessions show up in the server log, or to ship off and leave the card as the signal.
  • The card counts a few requests the quota doesn't: Apple push display-token fetches, public reads with an attached session, and routes with their own auth budget. It's an approximation of the quota, not a mirror.
  • With the memory backend on several API servers, each server keeps its own bucket, as the other limiters do.

Validated features: I couldn't read the validation board (missing read:project access). The PR body names #1188 C1, #1217 C1 and #1218 C1, which the issue tables record as not yet run.

User manual: no siloserver.org issue exists yet. It needs one for the new Per sign-in session group and its modes and defaults (running-a-server/configuration.md, Rate limiting) and the Busiest API clients card (running-a-server/monitoring.md).

Apple and Android: no change needed. First-party sessions stay well under the default quota, and enforce is off by default. I didn't check whether the apps honor Retry-After on ordinary API calls.

Evidence: https://evidence.siloserver.org/r/silo-server/pr-3075/

Fit: 7/10 · Readiness: 8/10 — conditional (assuming CI is green)

  • Fit: this solves a real problem the short windows can't catch, at the right place, the existing limiter, and it starts without refusing anyone. It adds a settings group, a table, a background pass every 15 minutes on every install, and per-request counting by default, which is a lot of new surface while the project is focused on QA.
  • Readiness: every verified defect is fixed, and the feature was shown working on the rebased head. The default-mode decision is still open, and the final lock change is covered by the DB contract test rather than the live run.

🤖 Claude Code (claude-opus-5-5)

Quick104 and others added 7 commits October 31, 2026 00:11
The per-second and per-minute limits stop bursts but not volume: a client
that stays just under them can send hundreds of thousands of API requests a
day. Each sign-in session now also spends a token bucket (10,000 requests an
hour, 30,000 burst) with off, log, and enforce modes; log is the default.
Media transfer routes, admins, impersonating admins, and API keys are not
counted.

Admins get a Busiest API clients dashboard card, backed by hourly summaries
of the activity log, that shows which sessions make the most requests, the
routes they call, and lets an admin sign one session out.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…on quota

Review fixes for the session quota and API clients summary:

- Exempt everything under /stream and /playback, so a player keeps
  reporting progress, replanning and stopping after its session runs out,
  and anchor the direct-download exemption so POST /direct-download/links
  is counted.
- Share the window limiter's Redis outage pause instead of keeping a
  second one, and drop refilled memory buckets inline instead of in a
  goroutine that was never stopped.
- Leave session_quota out of the frozen /api/v1 rate-limit config.
- Summarize UTC hours whatever the database time zone, redo the previous
  hour on each pass to pick up rows the activity log writes late, and leave
  out admins and impersonation as the quota does.
- Cap one session's endpoint read at 24 hours.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ients card

Review fixes:

- Keep an untouched quota bucket for seven days in memory and Redis instead
  of until the last request's rate would have refilled it, so lowering the
  rate cannot hand a drained session a fresh burst.
- Refresh the Busiest API clients card with the rest of the dashboard.
- Keep the sign-out dialog open until the request settles, so a failure
  shows its error.
- Derive the web session quota type from the generated v2 schema, and add
  api_clients to the capability example in docs/admin-api.md.
- Drop the two approvals #3050 left in breaking-approvals.json; the base
  already contains the changes they approve.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
An idle quota bucket is dropped after a week, so a quota that takes longer
than that to refill from empty would get a fresh burst back early. The
admin settings now reject a burst larger than 168 times the hourly rate.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… let a spent session sign out

- Take a cluster advisory lock in the API usage summary task, so servers
  don't run overlapping scans and upserts of the same hours.
- Read a card window from the start of the hour it begins in, so the
  one-hour range isn't empty while the current hour is being summarized,
  and read one session's routes over exactly the requested hours.
- Treat a summarized hour ahead of this server's clock as the current hour
  instead of rescanning the 48-hour catch-up window.
- Leave POST /auth/logout and GET /auth/provider-logout out of the session
  quota, so an exhausted session can still end itself.
- Show an idle session's routes as empty rather than a load error.
- Document session_quota in the admin rate-limit config section.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n empty list

The hand-built empty result didn't carry the v2 contract brand, so the web
build failed type-checking. Return only the endpoints the card reads.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…pass

The task held a session advisory lock on one pooled connection while the
summary and prune statements asked the pool for another. With
database.max_connections at 1 the startup pass waited on itself and held
the only connection. Refresh now takes a transaction-scoped lock and runs
both statements in that transaction, and skips the pass when another
server holds the lock.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Quick104
Quick104 force-pushed the t3/diagnose-prod-outage branch from c196d58 to f51e4fa Compare October 31, 2026 04:13
@silo-kody

silo-kody Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@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 Security Review · Automatically triggered

Here are some automated security review suggestions for this pull request.

Reviewed commit: f51e4fa6bf

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

Comment thread internal/ratelimit/session_quota.go Resolved
…ould have refilled it

Every bucket was kept a week after its last request, so a signed-in user
who kept signing in again grew the in-process map (and Redis) by one
bucket per session for a week. A bucket now goes after the share of a week
it is missing: the admin settings require any rate to refill a full burst
within a week, so by then any allowed rate has refilled it and dropping it
grants nothing. A drained bucket is still kept a week, so lowering the rate
can't hand it a fresh burst; one a client barely touched goes within
seconds.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-kody

silo-kody Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@Quick104

Copy link
Copy Markdown
Contributor Author

The ci / Go test failure on 5b891efce comes from main, not this branch: TestTokenHandlers_ScopeLibrariesToAuthenticatedProfile/login in internal/audiobooks/abs fails on main at 6db67ade4 too. #2919 and #2793 merged 11 seconds apart and conflict in a test fixture. #3302 fixes the fixture; once it merges, this branch needs a rebase to go green. This PR touches nothing under internal/audiobooks.

🤖 Claude Code (claude-opus-5-5)

@Quick104
Quick104 merged commit 5a20556 into main Oct 31, 2026
26 of 28 checks passed
@Quick104
Quick104 deleted the t3/diagnose-prod-outage branch October 31, 2026 13:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api-v2 API v2 / Huma migration program (epic #135); long-running, stacked by phase enhancement New feature or request evidence-required Needs before-and-after evidence before the Evidence check passes go Pull requests that update go code impact: usability Core flow broken or severely blocked javascript Pull requests that update javascript code needs-review Needs maintainer review to resolve uncertain classification, scope, or changed evidence. priority: P2 Limited scope, workaround exists, or polish size/XXL 1000–2999 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant