Skip to content
Source
Sign inSign up

Find the slow parts of a repository

Site administration

Find the slow parts of a repository

The forge times each request, each call of a Durable Object, each database statement, each queue batch, cron task and Workflow step, each request to another service and each streamed response, and keeps the timings in ClickHouse for 30 days. The web Worker and the runner Worker of CI and the factory send them. Use them to find what makes a repository slow, and what to fix first as the forge grows.

21 min read

You need:

  • The Source repository on your computer. For the report of one repository (--repo), the vault file .env.postgres at the root of a checkout that you do not commit from: run src vault pull --scope role:admin there, and delete the file when you are done.
  • To be signed in to the analytics server as root. See Sign in to the server.

1. Add the timings table

Do this once. Your server was set up before the schema had the table analytics.timings.

On your computer, copy the schema to the server:

scp apps/web/clickhouse/schema.sql root@<server IPv4>:/root/schema.sql

On the server, apply it as the admin user default. Each statement is safe to run again, so the other tables and their rows do not change:

clickhouse-client --password "$(cat /root/.clickhouse-admin)" --queries-file /root/schema.sql

This creates analytics.timings, lets ingest insert into it, and lets reader read it. Until the table exists, the forge drops the timings it sends, and nothing else changes.

2. Make sure that the timings arrive

A few minutes after the next deploy, count the rows of the last hour:

clickhouse-client --password "$(cat /root/.clickhouse-admin)" --query "SELECT kind, count() FROM analytics.timings WHERE at >= now() - INTERVAL 1 HOUR GROUP BY kind"

Each kind has rows: route, rpc, rpc_call, pg, queue and cron, and the others when their work ran.

A Worker sends its timings in a few messages, about 5 seconds after the first one waits. A Durable Object sends its last timings 5 seconds after its last call, as a job object does at the end of its job. A request, a queue batch or a Workflow step can still lose the timings of its last 5 seconds when its isolate gets no other work.

3. Read the report

On your computer, read the slowest parts of the forge:

pnpm -C apps/web perf --ssh root@<server IPv4>

Or of one repository, over the last day:

pnpm -C apps/web perf --ssh root@<server IPv4> --repo pingdotgg/t3code --hours 24

If your SSH key for the server is not one of the keys that ssh uses by default, give its file with --key:

pnpm -C apps/web perf --ssh root@<server IPv4> --key ~/.ssh/<key file>

The report runs its queries on the server over SSH, and finds the repository's id in the database, Neon's main, with the vault file .env.postgres. For each operation it shows how often it ran, its times in ms (p50, p95, p99 and the longest), its total time in seconds, and how many failed.

Find the statements that cost the most

A page or a pass is slow, and its time goes to the database. Each database statement is a pg row, named by its SQL text as the app wrote it, with no values. To rank the statements by their total time, run this query on the server as the admin user:

clickhouse-client --password "$(cat /root/.clickhouse-admin)" --query "SELECT name, count() AS runs, round(sum(ms) / 1000, 1) AS total_s, quantile(0.95)(ms) AS p95_ms FROM analytics.timings WHERE kind = 'pg' AND at >= now() - INTERVAL 24 HOUR GROUP BY name ORDER BY total_s DESC LIMIT 20"

A pg row names no repository. To find the requests of one repository, read its route and rpc_call rows (repo_id) for the same time.

What each timing measures

  • route: a request to the web Worker, by its route pattern, such as GET /@:owner/:repo/blob/* or POST serverFn getRepoHome. It never holds an owner, a repository or a path.

  • rpc: a call of a Durable Object, timed inside the object, by <class>.<method>. A call of a repository's RepoSyncHub adds its repository.

  • rpc_call: the same call, timed by the caller. It adds the wait in the object's queue and the transit. The report shows the difference as the wait for the object. A large wait means the object is busy. A call of a repository that Postgres answers is named RepoData.<method>: it has no rpc row, and its statements are pg rows.

    The timings consumer counts the failed calls of each repository in each clock hour (UTC). At 20, it alerts the team once for that repository and hour: the Sentry issue alert: a repository object failed 20 calls in an hour, with the repository's id, the count and the start of the hour in the breadcrumbs of the event (repoId, failedCalls, hour). A busy refusal does not count: a call that failed only because other writes held the lock of its repository or account (RepoBusyError, AccountBusyError, or a wait that passed its lock or statement timeout). Its work runs again later, as when a webhook delivery goes to the queue. ClickHouse still keeps it as a failed call (ok is 0). Every other failure counts: an overloaded or reset object, a broken connection, or a method that threw.

  • RunnerCalls.<method>: a call of the runner Worker to the web Worker's entrypoint RunnerCalls, for the work that only the web Worker does: the vault calls of a repository, the MCP connections of an org, the webhooks and app deliveries, and the model of a factory run or a chat with its spend (modelChoice, modelSpend). While the seam of the PR chat is on (the row live.seam lists pr_chat), a PR chat or architecture chat turn makes these calls too: chatSetup (its model, its cap and its prompt), chatTool (each read tool) and chatTokens (the person's tokens), with modelSpend for a forge-paid model. While the seam of the CI jobs is on (ci_job), the outbound handler of a CI job makes them for the hosts of its container: ciHost for each request to its CI host but a log request, ciOidcClaims for an OIDC token, and agentSessionRevoked for each allowed request of a job whose run an agent session started, and at the job's start and each heartbeat. The job's object makes ciJobStart once, at its first container, ciJobSecrets once for each instance of the object, when a request first needs a secret, and its task step ciHiddenFiles for a job of a hidden workflow and ciSrcModules for a checkout with a .source/src.lock. Its steps make ciJobStarted and ciJobEnded, once each, and its object ciJobSaved at each save point of a run on Postgres, ciJobSlot at each heartbeat of such a job, ciJobAudit for each command that a person runs in its debug window, and ciLogRetention for each step of its log retention. A ci-job hop that ciJobStarted or ciJobEnded starts runs after the call answered, so the call's time holds no graph pass. The bundle step of a plan task makes ciBundleStart once, ciInstallSecrets once for an install that sends a secret, ciBundleFetch for each request of the fetch of its commit, and ciBundlePut for each file that it keeps. A job on a runner app makes ciRunnerInstall when its VM starts, and ciJobEvent for each of its ci_job events. These calls name no repository (repo_id is ''). The web Worker times it as rpc, and the runner as rpc_call. Its difference is the time between the two Workers. Its statements are pg rows of the web Worker.

  • RunnerGitHost.fetch: a request of a CI job's container for its git host, from the outbound handler of the job in the runner Worker to the web Worker's fetch entrypoint RunnerGitHost, while the seam of the CI jobs is on. It ends at the headers of the answer, and names no repository. The web Worker times it as rpc, and the runner as rpc_call. The time of the whole answer, to its last byte, is in the git.request event of the request (analytics.events), which the runner sends when the body ends, as it did before the seam.

  • relay: a run of the outbox relay of a repository, named relayAfterCommit. Its repo_id is the repository. It starts when the run takes the relay lease of the repository, and ends when the run gives the lease back. It failed when a statement failed. A failed send does not fail it: the events wait in the outbox for the next run. Each write runs it after its commit, and so does the cron task late outboxes.

  • due: a run of the pass of an alarm kind of a repository, named by its kind, such as ghsync or buckets. Its repo_id is the repository. It failed when the pass threw. A repo.due message of the repository events queue runs the passes.

  • pg: a database statement, by its SQL text as the app wrote it (SQLite's syntax), and a batch by its first statement. Its values are never kept. A write that went in the message of the next statement (db.later) has no row of its own: its time is in that statement's.

  • pg_replica: the same, on the read replica of the database. The page reads of visitors who are not signed in run there (README.md, "Read replica"). Compare its rows with the pg rows of the same statements to see what the replica takes off the primary.

  • alarm: the alarm of a Durable Object.

  • sync_step: a step of a GitHub sync pass, such as github.refs.

  • stream: a clone, fetch or push, an archive download (GET /@:owner/:repo/archive/*), or the data sync, from its headers to its last byte. Its rows_read is the bytes it sent.

  • queue: a batch of a queue consumer, by its queue.

  • cron: a task of the cron, by its name. The CI cron's tasks for the CI state on Postgres are CI passes, CI trims, CI reuse trims, CI purges, CI watch, CI outbox, CI retention, CI log retention and CI run moves. Each does nothing while the flag of its class (objects.ci_queue, objects.ci_run) keeps the state in the objects, except CI purges, which deletes only what a write on Postgres left, and CI reuse trims: the CI cache index is on Postgres only.

  • workflow_step: a step of a job's Workflow.

  • fetch: a request to another service: GitHub's API by its path pattern (GET github /repos/:owner/:repo/issues/:n), a webhook delivery, an MCP server. It never holds a URL.

  • cache: one answer of the edge cache of repository pages. page hit, page miss, page new, page latest and page stamp-failed are answers of the cache of signed-out HTML pages. read <scope> hit, miss, new and latest are answers of the cache of page reads, such as read repoPage hit. new means that this data center keeps nothing of that URL or read yet. ms is the time until the cache knew its answer. To see what the cache is worth for one repository, count its answers:

    clickhouse-client --password "$(cat /root/.clickhouse-admin)" --query "SELECT name, count() AS answers FROM analytics.timings WHERE kind = 'cache' AND repo_id = '<repo id>' AND at >= now() - INTERVAL 24 HOUR GROUP BY name ORDER BY answers DESC"
  • lock_wait: a write of a repository, from its start until it held the lock of the repository: a database connection, the round trip of the lock, and the wait behind the other writes of the repository. It failed when the write never got the lock (the repository was busy: it ran again, or failed with "This repository is busy"). A write sent in one message, with no round trip while it holds the lock, has only this row, for its whole round trip.

  • lock_hold: the same write, from the lock until its commit or rollback. The other writes of the repository wait this long. It failed when the write did not commit. Its rows_read is the number of round trips the write made while it held the lock, a statement each. A write that went in the message of the next statement (db.later) and a read that the write had made already (db.cached) add none. The report divides the time by them (ms_per_statement): about 5 ms is a caller next to the database, and about 70 ms a caller far from it, such as an object on the US West Coast.

    Both are named by what held the lock: the timed call that ran the write, then its first statement, such as RepoData.collabAddComment | SELECT ... or POST hop repo-events | INSERT INTO github_pending .... The report's Repository locks by total hold time ranks them, and Repositories by lock hold time shows the busiest repositories. To list the writes that held one repository the longest, run:

    clickhouse-client --password "$(cat /root/.clickhouse-admin)" --query "SELECT name, count() AS holds, quantile(0.95)(ms) AS p95_ms, round(sum(ms) / 1000, 1) AS total_s FROM analytics.timings WHERE kind = 'lock_hold' AND repo_id = '<repo id>' AND at >= now() - INTERVAL 24 HOUR GROUP BY name ORDER BY total_s DESC LIMIT 20"

    Each hold also carries the key of its lock, which ClickHouse does not keep: repo:<repository id>, account:<account id> for the CI queue of an account, author:<person id>, run:<run id> or item:<item> for a factory item. The timings consumer adds up the holds of each lock in each 5 minutes. When one lock is held more than 100 s in 5 minutes, it alerts the team once for that lock and those 5 minutes: the Sentry issue alert: a lock was held more than 100 seconds in 5 minutes, with the key of the lock, the ms it was held and the start of the 5 minutes in the breadcrumbs of the event (lock, heldMs, windowStart). Then every other caller of the lock waits much of the time. In the lock convoys of 2026-12-01 (16:05-16:50 UTC), the worst 5 minutes of the busiest locks held 126 to 173 s. A normal 5 minutes holds a lock under 60 s.

  • The changes of a CI run on Postgres lock the row of their run in ci_runs (withRunLock in jobs/ci-run-store-pg.ts), and record lock_wait and lock_hold rows too, named ci_runs <change>, such as ci_runs jobEnded or ci_runs moveOnce, with no repository. A long hold makes the other changes of that run wait: the ends of its jobs and its graph passes.

  • factory: one pipeline work of a factory item on Postgres, by the function that runs it, such as handleItemEvent, from its first try to take the lease of its item until it gave the lease back. It failed when the work threw, or gave up waiting for the lease. The lease records lock_wait and lock_hold rows too, named factory item lease: the wait until the take, whose rows_read is the tries, and the hold until the give-back. The other writes of the item do not wait for the hold: only the next pipeline work of the item does.

The times are wall times across I/O. The Workers clock moves only at I/O, so synchronous code takes 0 ms on it.

Check the home page

Use the existing timings report and focused tests to check home page work. Timings show observed request costs, not a guaranteed speed improvement.

  1. Open / while signed out, then open it with an approved browser session.
  2. Read the timings report without --repo, because the home page spans repositories.
  3. Compare the getDashboard route timings and pg statement counts for the same observation period.
  4. Inspect the home response in the browser network panel. Signed-out responses have empty dashboard lists and the request origin.
  5. With an approved session, check that the dashboard still shows recently updated public repositories and your personal sections.
  6. From the workspace root, run the focused regression tests:
pnpm -C apps/web exec vitest run test/home-data.test.ts test/session-read.test.ts --maxWorkers=2

The home data tests count the public-list statements that run after fixture setup. They cover missing, unknown, expired, revoked and waiting sessions. These cases must not query the recently updated public list. The approved session must retain the newest 12 public repositories in order. The tests also check the empty response lists and request origin.

The session tests check the existing request-scoped session reads. Use these tests for session safety evidence. Aggregate production timings alone cannot prove access safety or identify one browser session. Do not record cookies or credentials in the evidence.

Check the home loading boundary

Use the deployed release to check the browser graph. Source import tests alone do not prove the production chunk layout.

Match the release

  1. Record the source commit, lockfile SHA-256, build and deployment identifiers, URL, and observation time.
  2. Save the HTML, asset URLs, and build manifest from that exact release in the evidence folder.
  3. Match the HTML asset hashes to the manifest before comparing releases. Do not mix local output with deployed HTML.
  4. Record the browser, cache state, session state, and theme for each observation. Keep credentials out of evidence.

Collect the complete mandatory graph

  1. Save every required module script from the anonymous Home HTML as a root.
  2. Add the rendered Home component chunk, even across a dynamic edge.
  3. Add every JavaScript modulepreload from the same HTML and manifest as a root.
  4. Parse every root body and follow every static import and reexport, including bare imports and shared chunks.
  5. Save each complete body, SHA-256, decoded byte length, resolved edges, and a root path to each included module.

The mandatory closure contains all roots and every module reached by these static edges. A visited set handles cycles. Optional runtime requests, including Three.js, have a separate list. Network requests alone do not define the static closure.

  1. Require zero missing, truncated, hash-mismatched, or wrong-release bodies.
  2. Require zero unresolved static edges and parser errors.
  3. Check for target bodies inside required entry and shared chunks, even when their old filenames disappear.
  4. Attribute bodies through the matching manifest, source maps when available, and emitted code. Record uncertain ownership as incomplete proof.
  5. Repeat the complete capture for the baseline and candidate. Compare only release-matched artifacts.

Check the route and UI targets

The anonymous mandatory closure must exclude these UI bodies:

AreaTargets
Repository codeCodeFilter and its controls; file-nesting patterns and arrangement code
Repository navigation and settingsSection icons; Toggle and notice controls
Apps and webhooksRepoApps, AccountAppsGrid, Consent, AppPermissions, AppForm, WebhooksPanel, and SuspendApp
App page assembliesMyApps, AppSettings, InstalledAppsPage, public AppPage, and AppDirectory
Personal Home and chromeDashboard, HeaderAccountControls, NotificationBell, SiteDock, and VerifyEmailBanner

Required data stays ready: filter parsers and loaders, open-row search, section redirects, app search, and permission descriptions. Existing role and action data can remain through a real consumer. Authorization remains on the server. Shared Base UI code can remain when another required component uses it. Its presence alone does not prove a target UI body remains.

  1. Check every mapped critical route and any tsr-shared compiler output for retained UI imports, including bare imports.
  2. Check that wrappers use their exact getRouteApi ids and have no route-definition import back into UI.
  3. Require the emitted closure check too. Source moves and compiler probes do not prove production chunk removal.
  4. Repeat with an approved session. Record optional chunk requests and when their controls become usable.

Landing stays eager. The home loader and shared data runtime remain shared. A dynamic edge alone does not prove less initial work.

Header keeps public navigation, search, theme controls, and sign-in links available. Account controls load for approved or waiting sessions. SiteDock preloads for an eligible approved identity. It renders only after the notification listener registers for that account period. The email banner retains its identity guard. The dashboard receives the existing loaded data through an account-keyed boundary.

Check the docs route boundary

The native /docs/$ loader awaits the existing docs registry. It resolves the sidebar title after the data client returns the page. The stored view keeps only the Markdown source, directory, and slug. Existing in-session data can be reused. Docs views have no durable offline persistence. The page assembly uses the native component split. The registry still owns navigation, page titles, Markdown imports, and image URLs.

  1. Check the eager route output for static and bare imports of the docs registry or its UI consumers.
  2. Check the component split and any shared compiler output. Follow imports and reexports into the registry.
  3. Check rebuilt entry and shared bodies in the complete mandatory Home graph. A different filename does not prove removal.
  4. Open /docs, a nested page, and a missing page through direct requests and client navigation.
  5. Check sidebar titles separately from Markdown H1 text, including pages without an H1 and the Docs title fallback.
  6. Check fresh loads, cached entry, preload, and available in-session offline data. The title must work when the fetch callback does not run.
  7. Check text for browser Find, search, sidebar and mobile navigation, child links, pager order, outline, relative links, images, and copied code.
  8. Check both themes, hydration, media controls, deferred home decoration, and the existing missing-chunk recovery path.

CI runs the docs SSR and hydration cases through production Redact aliases. Local source and compiler checks do not establish production savings. Keep server-function identities, authorization, and the existing data cache policy unchanged during this check.

Maintain the Redact serializer patch

Keep the exact @tanstack/redact@0.2.3 pnpm patch registered in pnpm-workspace.yaml and recorded in pnpm-lock.yaml. It keeps numeric CSS custom properties unitless during server serialization. Ordinary numeric lengths still receive px.

  1. Before changing or removing the patch, check the target package's source serializer, built JavaScript, and matching source map.
  2. Check zero, positive, negative, fractional, numeric-text, and explicit-unit custom properties. Keep ordinary width and opacity controls.
  3. Require CI to pass the actual SSR and hydration controls, both docs home themes, and the existing runtime files and production build.
  4. For each patch revision, regenerate its native pnpm lock identity and check a frozen install. Never leave a stale patch hash or embedded map source.

The docs home checks require grid steps 0, 1, and 2 before hydration, with no recoverable or console errors afterward. The content fixture skips animation timing and completes queued Motion work after unmount. It does not prove native WAAPI cancellation. Pure serializer checks do not prove application hydration, a deployed browser result, or a performance gain. Remove the patch only after the replacement package passes the same source, distribution, and runtime controls.

Check account changes and actions

  1. Hold optional chunk responses on a fresh visit. Check that public controls and page content remain usable while account controls wait.
  2. Change from account A to B, then sign out and sign in again while imports are pending.
  3. Check that old menus, organization results, notifications, dashboard state, and banners do not appear for the new identity.
  4. On the first usable dock, click Notifications once. Check that one panel opens at the dock anchor, even while unread data waits.
  5. Close the panel with Escape, then open it from the header Bell. Check its anchor and keyboard focus.

Also check waiting-account sign-out, failed sign-out retry, and unsent-change confirmation. Waiting and anonymous sessions must not get the signed-in dock.

Collect PR CI evidence

  1. Record the tested candidate commit and lockfile hash with the Source checks from src pr checks.
  2. Require the existing type, unit, production Redact runtime, and production build jobs to pass.
  3. Keep the matching client manifest, emitted JavaScript bodies, and private source maps when available with the review evidence.
  4. Record artifact hashes and availability. A build cache entry alone is not a complete exported graph artifact.
  5. Use the existing deployed-release capture when CI does not retain the full client output. Mark emitted proof pending until that capture exists.

The focused app-directory runtime case uses the real route, hooks, SSR, and hydration with a fake Start transport. Ordinary data-hook fakes do not prove production Redact hydration. CI runtime results also do not replace release browser checks.

Check the production runtime

Use the tested candidate preview or deployed release. Record its identity with each result.

JourneyRequired checks
Anonymous HomeSame SSR content, title, public navigation, search, theme, and sign-in readiness
Waiting and approved sessionsIdentity guards, dashboard and dock readiness, account changes, and sign-out
Repository root, tree, and blobDirect SSR and client navigation; refs, paths, only/hide/owner/open search, stored filters, cap fallback, icons, and keyboard behavior
Agents and SettingsRole redirects, hashes, GitHub callback search, archived access, admin checks, sidebar icons, errors, partial saves, and pending forms
App journeysDirectory paging; public, private, and suspended detail; registration and edit; personal, organization, and repository installs; consent, secrets, and suspend/lift
Redact and Base UIHydration, navigation, labels, focus return, dialogs, popovers, switches, checkboxes, and forms in both themes
  1. Record hydration errors, console errors, visible layout failures, and failed requests in both themes.
  2. Refuse a deferred UI chunk and check the existing route error path and accessible manual recovery.
  3. Require at most one automatic reload per missing chunk per tab, with no reload loop.
  4. Navigate from an already-open old page during deployment. Check stable server-function methods, ids, and payloads.
  5. Check old-chunk failure through the existing recovery path. Do not add another reload or cache system for this procedure.

Keep the account-change and notification-action checks above. Hold optional responses and leave a page while imports wait to expose stale controls.

The check is complete when matching evidence covers the full graph, deferred journeys, account changes, runtime behavior, and failure recovery. A source-only candidate can be ready for review while emitted and release checks remain pending. Do not claim fewer bytes, lower CPU use, or faster pages without separate measurements from matched releases.

Done

The forge keeps the timings of the last 30 days. To see them in another tool, read analytics.timings as reader.