You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
perf(admin): read account last activity from its own table - #3243
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.
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.
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]>
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.
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.
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.
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
Silo-Server/silo-server#2306: Adds audit mutations that write activity-log rows, a path that affects activity and last-activity behavior.
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: 4 · 1
Failed checks: 1 warning
Check name
Status
Explanation
Resolution
Docstring Coverage
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 checks: 4 passed
Check name
Status
Explanation
Title check
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
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Description check
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.
- 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]>
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".
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.
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 2 remain after this review.
…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-triageBot
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
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.
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.
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.
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]>
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
evidence-requiredNeeds before-and-after evidence before the Evidence check passesgoPull requests that update go codepriority: P2Limited scope, workaround exists, or polishsize/L200–499 added + deleted lines (all files); change volume, not priority.
1 participant
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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")overactivity_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
user_last_activitytable holds one row per account. A second migration fills it fromactivity_log, after the table's creation commits, so the scan holds no lock that blocks writes tousers.activity_logrow reach the consumer flagged as stored, so they count as activity without a second row.activity_logrow are pruned, so the table matches what the log used to report.loadUserLastActiveAtreads the table, so the list and detail pages do one key lookup per account. The/api/v2response is unchanged.The value does not live on
users, because everyusersUPDATE bumpsadmin_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_logwas 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
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.activitylog,apiv2, and the admin handlers: pass.make lint-changed: 0 issues.Evidence
No user-visible change; build and test notes:
Evidence: https://evidence.siloserver.org/r/silo-server/pr-3243/
Risks
activity_log. On a large log it adds seconds to the upgrade.Checklist
AI Disclosure
🤖 Generated with Claude Code