Skip to content

perf(admin): read account last activity from its own table - #3243

Merged
Quick104 merged 3 commits into
mainfrom
perf/admin-users-page-queries
Oct 29, 2026
Merged

Quick104 merged 3 commits into
mainfrom
perf/admin-users-page-queries

Conversation

@Quick104

@Quick104 Quick104 commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: changes #1197 C1, C2

The admin Users page can take several seconds to load on a busy server, and the user detail page has the same cost for one account. Both work out each account's last activity on every load by aggregating MAX("timestamp") over activity_log. That log records every request, so the query reads every row each listed account has and gets slower as the log grows. This change stores each account's last activity in its own small table and reads that instead.

#1197 C1 and C2 use the admin Users list and account detail, which now read Last Active from the new table. Neither case's criteria cover Last Active, and the values match what main shows, apart from the rolling-upgrade lag under Risks. Re-test both after merge.

Approach

  • A new user_last_activity table holds one row per account. A second migration fills it from activity_log, after the table's creation commits, so the scan holds no lock that blocks writes to users.
  • The activity log consumer updates it after each batch insert, with the newest timestamp per account. It writes accounts in id order so batches from different nodes cannot deadlock, never moves a timestamp backward, and skips accounts deleted since the request was logged. A failure there is logged and does not fail or retry the log insert. Requests whose audited admin mutation already stored its own activity_log row reach the consumer flagged as stored, so they count as activity without a second row.
  • After each retention pass, rows older than the oldest retained activity_log row are pruned, so the table matches what the log used to report.
  • loadUserLastActiveAt reads the table, so the list and detail pages do one key lookup per account. The /api/v2 response is unchanged.

The value does not live on users, because every users UPDATE bumps admin_revision, the validator behind admin edits. Writing activity there would make admins hit edit conflicts on accounts that are in use.

A per-account "newest row" query against activity_log was not enough. In weekly partitions that hold few distinct accounts, the planner scans the partition's timestamp index instead of the user index, so the query stayed slow.

Validation

  • Migrations: all apply to a fresh database.
  • New DB test (registered in scripts/ci/db-contracts.txt): passes. It covers newest-wins within a batch, skipping anonymous and deleted accounts, a late batch not moving the time backward, and an already-stored audited request updating last activity without a second row.
  • Focused Go tests for activitylog, apiv2, and the admin handlers: pass.
  • make lint-changed: 0 issues.
  • Not run: the full pre-PR gate, and the page on a deployed build.

Evidence

No user-visible change; build and test notes:
Evidence: https://evidence.siloserver.org/r/silo-server/pr-3243/

Risks

  • The backfill migration runs one full aggregate over activity_log. On a large log it adds seconds to the upgrade.
  • During a rolling upgrade, nodes still on the old build do not update the table. An account's last activity catches up on its next request served by an upgraded node.

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 (in T3 Code)
  • Tool(s): Claude Code
  • Model(s): claude-opus-5-5
  • Involvement: Fully AI-generated, pending maintainer review
  • Adversarial review: n/a

🤖 Generated with Claude Code

The admin account list and detail pages derived each account's last
activity with MAX(timestamp) over activity_log on every load. That log
records every request, so the aggregate read every row of each listed
account and grew slower with the log.

The activity log consumer now keeps user_last_activity current per batch,
and the admin pages read it with one key lookup per account. The table is
separate from users because any users UPDATE bumps admin_revision, the
admin edit validator. The migration backfills it from activity_log.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-triage silo-triage Bot added the size/M 50–199 added + deleted lines (all files); change volume, not priority. label Oct 29, 2026
@silo-kody

silo-kody Bot commented Oct 29, 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 29, 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-29T14:23:20.958732Z f6c7950 New commits
🔒 Security Review ✅ Completed 2026-10-29T14:24:55.422732Z f6c7950 New commits
ℹ️ 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 29, 2026

Copy link
Copy Markdown

This changes admin-visible data: accounts whose activity-log rows have expired can now keep a last-active timestamp instead of showing no activity, which can also change last-active sorting. The Evidence section says there is no user-visible change. Please add before-and-after captures of the admin Users list (including the resulting sort), the account detail, and the dashboard Users widget for the same accounts; include desktop and mobile web captures where those surfaces show the change, and identify the build or commit for each capture.

Suggested fix: No diff; update the Evidence section with the requested before-and-after captures.

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

Posted via Macroscope — Visible change evidence

@coderabbitai

coderabbitai Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Caution

Review failed

The pull request is closed.

Walkthrough

The change adds user_last_activity, backfills it from activity-log records, and updates it from consumed batches. The admin handler now reads last-activity timestamps from the new table. A database-backed test checks timestamp ordering and user filtering.

Changes: User last-activity tracking

Layer / File(s) Summary
Activity table and backfill
migrations/sql/20261029133717_add_user_last_activity.sql
The migration creates the per-user activity table, backfills each matching user’s maximum activity timestamp, and drops the table on rollback.
Batch activity recording
internal/activitylog/consumer.go, internal/activitylog/consumer_db_test.go, scripts/ci/db-contracts.txt
The consumer records the newest timestamp per non-nil user after inserting activity rows. It skips deleted users and logs recording errors without failing the stored batch. The database test checks timestamp ordering and user filtering.
Admin activity lookup
internal/api/handlers/admin.go
The admin handler reads last-activity timestamps from user_last_activity instead of aggregating activity-log rows.

Priority: Pending latest changes

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Refactor

Sequence Diagram(s)

sequenceDiagram
  participant ActivityLogConsumer
  participant UserLastActivity
  participant AdminHandler
  ActivityLogConsumer->>UserLastActivity: Record newest user timestamps after batch insertion
  AdminHandler->>UserLastActivity: Read last_active_at for requested user IDs
Loading

Possibly related PRs

Suggested reviewers: rhainland, blurbery

Merge Risk: Moderate · previous review ab70c

Upgrades can delay account writes, and some admin activity timestamps can remain stale. Address these risks before merging.

Security architecture risk: Low · up to ab70c

The change preserves the existing administrator access controls and keeps activity timestamps separate from authorization decisions. However, some successful administrative actions do not update the new table, and failed updates can leave account activity stale indefinitely. The demonstrated impact is misleading administrative activity information, not loss of the underlying audit history.

Retained concerns

  • Low · reliability · observed: The new last-activity projection has incomplete maintenance ownership. Successful transactional administrator mutations persist audit rows directly and suppress the queued request entry, so those actions do not advance the actor's projected timestamp. Separately, a projection failure after batch persistence is not retried. Without a later eligible request, administrator account activity can remain stale indefinitely despite newer durable audit records. This weakens account-activity visibility, but the inspected consumers use the value only as an informational hint.
Security review details

Security Blast Radius

  • inferred — The demonstrated exposure is account-recency information in administrator list and detail responses. Omitted transactional mutations affect the acting account's timestamp, not the mutation target's timestamp. The underlying audit record remains available; the inspected consumers do not use last activity for access or retention enforcement.

Security Findings and Attack Paths

  • inferred — An authorized actor can perform a successful transactional administrative mutation without advancing their displayed activity when committed-audit suppression applies. This is an administrative visibility gap, not demonstrated audit erasure, identity spoofing, privilege escalation, or an authorization bypass.

Trust Boundaries and Controls

  • observed — Administrator account reads retain acting-admin authorization and API-key scope checks. The requested account ID selects the response target after authorization; changing the timestamp query does not grant additional authority.
  • observed — The database enforces one projection row per existing account and cascading cleanup. The upsert's timestamp predicate prevents older or repeated batches from moving activity backward; the database contract test covers newest-wins, anonymous and deleted IDs, and late batches.

Resilience and Maintainability Implications

  • observed — Failure containment favors durable audit history and available account reads over projection freshness: failed projection writes do not retry audit insertion, and failed projection reads do not fail account retrieval. These controls limit operational impact but do not establish that displayed activity is complete.

Hardening Proposals

  • proposed — Define projection maintenance for every authoritative activity-log producer and an idempotent repair path for missed updates, while preserving audit durability and the existing timestamp monotonicity guard.
Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documenta… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title "perf(admin): read account last activity from its own table" matches the main change: admin pages now read last activity from a new user_last_activity table instead of aggregating MAX(timest…
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 directly explains the performance problem, the new user_last_activity table, the activity-log updates, migration, validation, and known risks. It matches the changeset.
Full details: Title check

Explanation

The title "perf(admin): read account last activity from its own table" matches the main change: admin pages now read last activity from a new user_last_activity table instead of aggregating MAX(timestamp) over activity_log. It is specific, concise, and follows a conventional commit style.

Full details: Docstring Coverage

Explanation

Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 2 functions across 3 files. (2 skipped: 2 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

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 @coderabbitai help to get the list of available commands.

@silo-triage silo-triage Bot added evidence-required Needs before-and-after evidence before the Evidence check passes go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish labels Oct 29, 2026

@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: ab70c06fe8

ℹ️ 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 internal/api/handlers/admin.go Resolved
Comment thread internal/api/handlers/admin.go Resolved
- Use bigint for user_last_activity.user_id and the account id
  parameters, as users.id is bigint.
- Count requests whose audited mutation stored its own activity_log row:
  the middleware now hands them to the consumer flagged as persisted, so
  they update last activity without a second row. This stays outside the
  domain transaction.
- Prune last activity older than the activity log retention, so an
  account idle past retention still shows none.

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

silo-kody Bot commented Oct 29, 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

Addressed in da80eaa without captures: the retention cleanup now prunes user_last_activity rows older than the activity log retention cutoff, so an account idle past retention shows no last activity, as before. The Users list, account detail, and dashboard widget show the same values as on main, so the Evidence section stays "no user-visible change".

@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

Nitpick comments: 1
internal/activitylog/consumer_db_test.go: 1

15-74: Trivial · Data Integrity & Integration · Quick win

Exercise insertBatch in the database test.

TestRecordLastActivityKeepsNewestDB calls recordLastActivity directly. No test invokes Consumer.insertBatch. Removing or moving the projection update from insertBatch would leave the registered database test passing while user_last_activity remains stale.

Add one valid activity entry through insertBatch and assert the projection. Keep the existing helper assertions for newest-wins and stale batches.

Suggested fix
diff --git a/internal/activitylog/consumer_db_test.go b/internal/activitylog/consumer_db_test.go
@@
 	"github.com/jackc/pgx/v5/pgxpool"
+
+	"github.com/Silo-Server/silo-server/internal/logstream"
 )
@@
 	defer func() { _, _ = pool.Exec(ctx, `DELETE FROM users WHERE id=$1`, user) }()
+	requestID := "last-active-" + suffix
+	defer func() { _, _ = pool.Exec(ctx, `DELETE FROM activity_log WHERE request_id=$1`, requestID) }()
@@
 	if got := lastActive(); !got.Equal(base.Add(2 * time.Minute)) {
 		t.Fatalf("last_active_at = %v, want %v", got, base.Add(2*time.Minute))
 	}
+
+	consumer := NewConsumer(pool, logstream.NewHub("test", nil))
+	if err := consumer.insertBatch(ctx, []LogEntry{{
+		Timestamp:  base.Add(3 * time.Minute),
+		ClientIP:   "127.0.0.1",
+		UserID:     &user,
+		RequestID:  requestID,
+		Method:     "GET",
+		Path:       "/test",
+		StatusCode: 200,
+		UserAgent:  "test",
+	}}); err != nil {
+		t.Fatal(err)
+	}
+	if got := lastActive(); !got.Equal(base.Add(3 * time.Minute)) {
+		t.Fatalf("insertBatch did not update last_active_at: %v", got)
+	}
 }

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: 8c9fb075-2281-4ce4-a4a8-b52b8d9ac494
Commits

Reviewing files that changed from the base of the PR and between 5a602b8 and ab70c06.

Files selected for processing: 5
  • internal/activitylog/consumer.go
  • internal/activitylog/consumer_db_test.go
  • internal/api/handlers/admin.go
  • migrations/sql/20261029133717_add_user_last_activity.sql
  • scripts/ci/db-contracts.txt

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

Comment thread internal/activitylog/cleanup.go Resolved
…the log boundary

- Move the user_last_activity backfill into its own migration, so the
  foreign key's lock on users is released before the activity_log scan.
- Prune last activity below the oldest retained activity_log row rather
  than the retention cutoff: retention drops whole partitions, and the
  log keeps rows older than the cutoff until their partition goes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-triage silo-triage Bot added size/L 200–499 added + deleted lines (all files); change volume, not priority. and removed size/M 50–199 added + deleted lines (all files); change volume, not priority. labels Oct 29, 2026
@silo-kody

silo-kody Bot commented Oct 29, 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 ❌

@macroscopeapp

macroscopeapp Bot commented Oct 29, 2026

Copy link
Copy Markdown

Major change: Web admin cases #1197 C1 and C2 passed on build 807 · d4e35ba9. Both exercise the admin Users list/detail, where the new user_last_activity lookup supplies the Last Active value and sort. Because the summary is best-effort and older nodes do not update it during a rolling upgrade, displayed timestamps can differ from the previously validated behavior. The PR must explain why this validated behavior changes, and C1/C2 need re-validation after merge. The current Validation tasks: none line is incorrect; use Validation tasks: changes #1197 C1, C2.

Suggested fix: No diff; update the Validation tasks line and explain the Last Active display change.

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

Updated the body: Validation tasks: changes #1197 C1, C2, with a note that both cases read Last Active from the new table, their criteria do not cover it, and the values match main apart from the rolling-upgrade lag listed under Risks. Both should be re-tested after merge.

@Quick104
Quick104 merged commit 44a345d into main Oct 29, 2026
27 checks passed
@Quick104
Quick104 deleted the perf/admin-users-page-queries branch October 29, 2026 14:28
@macroscopeapp

macroscopeapp Bot commented Oct 29, 2026

Copy link
Copy Markdown

Major change: #1200 C1 and C2 have recorded validation on build 807 · d4e35ba9. Both flows use the Admin Users list/detail before and after impersonation. Those reads now source the visible Last Active value from user_last_activity, which can differ during rolling upgrades; impersonation authorization and session restoration remain unchanged. The PR must explain why this validated display behavior changes, and both cases need re-validation after merge. The current Validation tasks: line omits them.

Suggested fix: No diff; update the line to Validation tasks: changes #1197 C1, C2; changes #1200 C1, C2 and document the rollout-dependent Last Active change.

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

Posted via Macroscope — v1 validation impact

Quick104 added a commit to Rhainland/silo-server that referenced this pull request Oct 31, 2026
Main now locks the acting profile FOR UPDATE at the start of a profile
create or update (Silo-Server#2704). On this branch that lock came before the audit
row's account lock, so an audited create or update again locked a profile
and then the account, the reverse of account deletion. Take the account
locks first, and make the lock-order test delete every profile of the
account, as the account's cascade does, with a create case.

Also bring the audit tests up to date with main: the profile verifier
takes the profile, and a request whose domain row committed now reaches
the activity writer flagged Persisted (Silo-Server#3243), so count only unpersisted
entries as request rows. Check rows.Err in that test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Quick104 added a commit that referenced this pull request Oct 31, 2026
Main now locks the acting profile FOR UPDATE at the start of a profile
create or update (#2704). On this branch that lock came before the audit
row's account lock, so an audited create or update again locked a profile
and then the account, the reverse of account deletion. Take the account
locks first, and make the lock-order test delete every profile of the
account, as the account's cascade does, with a create case.

Also bring the audit tests up to date with main: the profile verifier
takes the profile, and a request whose domain row committed now reaches
the activity writer flagged Persisted (#3243), so count only unpersisted
entries as request rows. Check rows.Err in that test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

evidence-required Needs before-and-after evidence before the Evidence check passes go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish size/L 200–499 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant