Skip to content

fix(insights): adoption history audit — consistent sources, buffered writer, UTC day bounds - #10557

Merged
waleedlatif1 merged 4 commits into
stagingfrom
fix/adoption-audit
Dec 1, 2026
Merged

waleedlatif1 merged 4 commits into
stagingfrom
fix/adoption-audit

Conversation

@waleedlatif1

Copy link
Copy Markdown
Collaborator

Summary

Follow-up to #10532 / #10540 from an audit of the adoption history. Each finding was checked against the code first; all six held.

  • Backfill and live recorder agree on sources. Inbox email conversations (run for an external sender as the workspace owner, user message saved without an origin) are excluded from the backfill. v2 Chat API turns are now recorded live as agent; the route admits only a person's own credential (personal API key or OAuth), so every turn is that person's, and the backfill already counted them the same way. Backfill logic moved to lib/organizations/member-activity/backfill.ts so it is testable; the script is a thin loop over it
  • Writer off the hot path. recordMemberActivity was four round trips (BEGIN, SET LOCAL, upsert, COMMIT) on the primary pool per chat turn, manual/API run, search and MCP call, and a tight loop serialized on one row lock. It now adds uses up in-process and writes them in one multi-row upsert every 5s, at 500 pending keys, and on SIGTERM/SIGINT/beforeExit (the lib/monitoring/metrics.ts pattern). Flushes are serialized and rows are written in key order. first_at/last_at keep LEAST/GREATEST. A failed flush drops its uses (analytics), logged
  • One set of day bounds. adoptionDays maps a period to whole UTC days, from the day its start falls on to the day its end falls on, or through today when it ends today. A period in another time zone no longer gains an extra UTC day, and the Search MCP breakdown now uses the same UTC days instead of exact instants
  • Search page Uses. The Search page refetches (staleTime 0), and each refetch was counted. The same query and filters by the same person now count once a minute (lru-cache, max 10,000, 60s TTL keyed by a hash). DAU is unaffected
  • One retention. Search MCP call metadata was swept at 270 days while daily counts kept 400, so an old period could show search_mcp uses with an empty MCP breakdown. Both now keep 400 days (ADOPTION_HISTORY_RETENTION_DAYS); helm/docs updated
  • The assistant-vs-agent split and the workflow-run gate (person acting, manual/api only) are named helpers in record.ts so their rules are tested

Type of Change

  • Bug fix

Testing

Real Postgres/Redis integration suites; each guard below was reverted and its test went red unless noted:

  • history.integration.ts (10): non-member and personal-workspace use never counted; uses add up across flushes and an organization plus its workspace into one row (red without GROUP BY); a flush waits for one already writing; a refused write is swallowed; a rate-limited or person-less Search MCP call is not counted (red without the outcome guard); the Search page counts once a minute and no other search surface (red without the surface gate and without the dedupe); the sweep removes only rows past retention; a batch that times out on a held row leaves the other table swept (red without the timeout catch)
  • backfill.integration.ts (2): one day counted as the live recorder would and identically on rerun, with a forked copy once (red without DISTINCT), inbox email excluded (red without the anti-join), job turns and rate-limited calls excluded, dry run writing nothing; --before excluded from the day range
  • organization-adoption.integration.ts (9): a window ending now runs through today; a Pacific-time period reads as the same UTC days and the Search MCP breakdown leaves out a call after the last UTC day (both red on the old bounds)
  • adoption/export/route.integration.ts (2): a member is refused 403 with no CSV; an admin gets one row per member
  • record.test.ts: the workflow-run gate and the assistant/agent split
  • The overlapping-flush test could not be made reliably red on the unserialized code (the race is timing-dependent); serialization is kept for the deadlock/ordering reasons above
  • Unit suites: lib/knowledge/mcp, lib/execution, chat post, app/api/v2/chat, live search application, lib/organizations; lint, check:file-names, check:boundaries, check:source-conventions, check:comment-hygiene, check:utils, check:api-validation:strict, check:unused-exports

Checklist

  • Code follows project style guidelines
  • Self-reviewed my changes
  • Tests added/updated and passing (new tests pass the test-audit authoring gate)
  • No new warnings introduced
  • I confirm that I have read and agree to the terms outlined in the Contributor License Agreement (CLA)

@vercel

vercel Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated
docs Skipped Skipped Dec 1, 2026 8:37am UTC

Request Review

@greptile-apps

greptile-apps Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5 · The PR appears safe to merge; no blocking issues remain.RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no blocking issues remain.

Summary

The PR aligns adoption history sources, buffers activity writes, shares search deduplication across replicas, and uses consistent UTC days and retention.

  • Live activity counts build up before the app writes them.
  • Live events and backfilled history count the same kinds of activity.
  • Adoption reports use whole UTC days for every activity breakdown.
  • Daily counts and Search MCP details share a 400-day history.

Reviews (4) · Last reviewed commit: "fix(insights): a window starting after n..." · Reviewed by Greptile

@cubic-dev-ai cubic-dev-ai 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.

1 issue found across 18 files

Confidence score: 4/5

  • In apps/sim/app/api/v2/chat/route.ts, failed admission, billing, or turn execution can still increment the live usage counter, making usage inaccurate. Count the use only after the turn succeeds.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="apps/sim/app/api/v2/chat/route.ts">

<violation number="1" location="apps/sim/app/api/v2/chat/route.ts:290">
P2: This counts the use before the turn is admitted, billed, or run. If billing attribution, entitlements, or the lifecycle fails, the request returns an error but the live counter still records a use. Backfill counts only persisted turns, so the two drift. Move the `recordMemberActivity` call to just before `runLifecycle` runs, after the billing and entitlement steps succeed, to match the post.ts admission-time recording.</violation>
</file>

This PR changes concurrency-sensitive code such as locks, queues, or retries. Ultrareviews find 2.4x more serious bugs than standard reviews. Comment @cubic-dev-ai ultrareview to run one.

Turn on auto-fix | Re-trigger cubic

Comment thread apps/sim/app/api/v2/chat/route.ts Resolved
@waleedlatif1

Copy link
Copy Markdown
Collaborator Author

@greptile

@waleedlatif1

Copy link
Copy Markdown
Collaborator Author

@cubic-dev-ai review this PR

@cubic-dev-ai

cubic-dev-ai Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

@cubic-dev-ai review this PR

@waleedlatif1 I have started the AI code review. It will take a few minutes to complete.

@cubic-dev-ai cubic-dev-ai 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.

All reported issues were addressed across 19 files

Reply with feedback, questions, or to request a fix.

Turn on auto-fix | Re-trigger cubic

@waleedlatif1

Copy link
Copy Markdown
Collaborator Author

@greptile

@waleedlatif1

Copy link
Copy Markdown
Collaborator Author

@cubic-dev-ai review this PR

@cubic-dev-ai

cubic-dev-ai Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

@cubic-dev-ai review this PR

@waleedlatif1 I have started the AI code review. It will take a few minutes to complete.

@cubic-dev-ai cubic-dev-ai 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.

No issues found across 19 files

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Turn on auto-fix | Re-trigger cubic

@waleedlatif1
waleedlatif1 merged commit 8bfa583 into staging Dec 1, 2026
93 checks passed

This branch was previously deployed

1 inactive deployment
Preview — e4eaf8b9 Deployed Dec 1, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant