Files
PaperClipAI/scripts/benchmark-task-activity-index-writes.ts
T
DottaandPaperclip 2a6d4d1694 perf(db): index canonical task activity lookups (#18043)
<!-- entire-trail-link-start -->
https://entire.com/gh/paperclipai/-/trails/177/changes/paperclip/177
<!-- entire-trail-link-end -->

## Thinking Path

> - Paperclip helps people manage AI agents and their tasks.
> - Task lists rank tasks by their latest canonical activity.
> - The existing lookup reads every event for each task before
pagination.
> - Query-only alternatives failed a narrow visibility control or the
performance goal.
> - This PR adds an index that lets the unchanged lookup stop at the
newest qualifying event.
> - The result is less history work with the same permissions, ordering,
and response.

## Linked Issues or Issue Description

Refs: #13803. That broader proposal stores a new activity field with
triggers and a backfill. This index was authored independently and uses
the existing query.

**Subsystem affected**

Task-list activity ranking and the database schema.

**Current behavior**

The list computes `MAX(activity_log.created_at)` for every eligible
task. The existing entity index reads 50 events per task across 1,199
candidates in the representative fixture.

**Proposed behavior**

Add `(company_id, entity_type, entity_id, created_at)`. Keep the
production task service and permission helpers unchanged. PostgreSQL
reads backward until an event passes the existing exclusions.

**Reason and benefit**

Fresh paired measurements on the current base improve the
full-description scoped SQL from **44.60 to 20.33 ms (2.19×)**. Activity
buffer accesses fall from **63,547 to 4,796**, and history rows per
probe fall from 50 to one. The complete service median falls from 50.63
to 31.31 ms. Complete positional SQL results and service responses
match.

## What Changed

- Add generated migration `0414_closed_edwin_jarvis.sql` and the
matching Drizzle index.
- Use `CREATE INDEX CONCURRENTLY IF NOT EXISTS` through the existing
top-level runner and invalid-index retry cleanup. The client change is
one whitelist entry.
- Preserve all upstream SQL and journal entries; retain snapshots
0410–0414.
- Cover full and index projections, canonical ordering, invalid-index
recovery, concurrent migrators, and incomplete fixture rejection.
- Repair benchmark seeding, apply requested work memory to both
connections, and record both settings. Hosted defaults now include six
Slack conversations, 642 GitHub conversations, and 53 removed
conversations.

## Verification

- **All final-head CI gates passed**, including full workspace
typechecks, tests, build, Runner checks, and all eight E2E shards.
Greptile is **5/5** on `67ca7ae1cf15fc054ef515ffd8205b1fe30a0d55`; no
unresolved review threads remain.
- Local database/server typechecks and migration numbering/safety checks
pass. Three server regression tests and three migration regression
suites pass on real PostgreSQL.
- The original pre-index work guard fails at eight rows per probe; the
indexed guard now checks both the full-description query and index
projection. The service oracle covers cleanup/inbox exclusions, raw text
IDs, company scope, comments, ties, sort directions, visibility before
pagination, empty lists, and one child per parent.
- The documented pre-index seed command reproduced the review failure
before the fix and now succeeds. A paired run with non-default memory
confirms both independent connections use `16MB`.
- Fresh proof pins pre-index base
`929e840595c8933ca485ac7a2e99413e1e11ca64`, with identical cloned data,
unchanged generated SQL and parameters, two warmups, and five
alternating samples per arm. All **18 comparison cells** preserve every
positional row and complete service response. The 15-case default-memory
matrix passes its physical-work, speed, and control bounds.
- The one-visible-task control is 6.64 → 7.25 ms SQL; the 20-task
control is 3.71 → 3.72 ms. Both pass the declared 25% or 2 ms budget.
Full-query memory controls use matching `4MB` or `16MB` settings.
- Committed 1,000-row write batches measured 40.09 → 43.17 ms median
(+7.7%). Ranges overlap (34.67–71.85 and 34.27–48.05 ms); this is an
observed local cost, not a precise throughput guarantee.
- The final-numbered migration builds a valid index through the normal
runner on the fresh 300,000-row fixture in 0.55 s. Earlier large-fixture
proof of the same index SQL used 5,000 tasks and 1.25M activity rows:
2.58 s first apply, concurrent write/read probes 5.16/2.43 ms,
interrupted invalid-index cleanup, successful retry, and one receipt.
Current migration recovery tests verify the renumbered path.
- [The proof
document](https://github.com/paperclipai/paperclip/blob/67ca7ae1cf15fc054ef515ffd8205b1fe30a0d55/docs/performance/task-list-activity-index.md)
retains the historical baseline, rejected rewrites, and the earlier
matrix invalidated by severe host contention. Those historical timings
are not substituted for the fresh measurements above.

## Risks

The migration is an exception after measured query-only alternatives
failed. The index adds storage and work to every activity write: about
30 MiB for 300,000 rows and 123 MiB for 1.25M rows. Concurrent creation
avoids the writer blocking observed with an ordinary index build, but
long transactions can delay it. Local timing does not establish Neon
build duration.

The query still ranks all eligible tasks, and excluded newer events
still need to be skipped. These are local SQL/service measurements;
deployed HTTP latency remains unverified. No hosted DDL or deployment
was performed.

## Model Used

OpenAI Codex, GPT-6 family, with reasoning, code execution, and tool
use. The environment does not expose the exact model identifier or
context-window size.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either linked existing issues or described the issue using
the relevant issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links
- [x] My branch name describes the change and contains no internal issue
id
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-29 09:06:41 -05:00

55 lines
3.3 KiB
TypeScript

import assert from "node:assert/strict";
import { availableParallelism, loadavg } from "node:os";
import { randomBytes } from "node:crypto";
import { promises as fs } from "node:fs";
import { createDb } from "../packages/db/src/index.js";
const host = { availableCpus: availableParallelism(), loadBefore: loadavg() };
const arg = (name: string) => process.argv.find(value => value.startsWith(`--${name}=`))?.slice(name.length + 3);
const urls = [process.env.TASK_PROJECTION_BASELINE_URL, process.env.TASK_PROJECTION_TREATMENT_URL];
assert.ok(urls.every(Boolean), "Set isolated baseline and treatment database URLs");
for (const value of urls) {
const url = new URL(value!);
assert.ok(["127.0.0.1", "localhost"].includes(url.hostname));
assert.match(url.pathname, /^\/task_projection_[a-z0-9_]+$/);
}
const clients = urls.map(value => createDb(value!, { maxConnections: 1 }));
const samples: number[][] = [[], []];
const noise = randomBytes(3072).toString("base64");
const count = Number(arg("count") ?? 1000);
assert.ok(Number.isSafeInteger(count) && count > 0 && count <= 10000);
const keepAlive = setInterval(() => {}, 1000);
try {
const records = await clients[0]!.$client.unsafe("select company_id,id from issues order by id limit 1200");
assert.ok(records.length);
const companyId = records[0]!.company_id;
const issueIds = records.filter(row => row.company_id === companyId).map(row => row.id);
for (const client of clients) await client.$client.unsafe("select 1");
for (let round = 0; round < 7; round++) for (const arm of round % 2 ? [1, 0] : [0, 1]) {
const client = clients[arm]!;
const started = performance.now();
await client.$client.unsafe("begin");
let inserted: { id: string }[] = [];
try {
inserted = await client.$client.unsafe<{ id: string }[]>(`insert into activity_log(company_id,entity_type,entity_id,actor_type,actor_id,action,details)
select $1::uuid,case when n%5=0 then 'issue' else 'heartbeat_run' end,
case when n%5=0 then ($2::text[])[1+n%array_length($2::text[],1)] else gen_random_uuid()::text end,
'agent','index-write-benchmark','issue.updated',jsonb_build_object('noise',left($3,case when n%5=0 then 4096 else 256 end))
from generate_series(1,$4::integer)n returning id`, [companyId, issueIds, noise, count]);
await client.$client.unsafe("commit");
} catch (error) {
await client.$client.unsafe("rollback");
throw error;
}
if (round >= 2) samples[arm]!.push(performance.now() - started);
await client.$client.unsafe("delete from activity_log where id=ANY($1::uuid[])", [inserted.map(row => row.id)]);
}
const stats = (values: number[]) => ({ medianMs: [...values].sort((a, b) => a - b)[2], meanMs: values.reduce((sum, n) => sum + n, 0) / values.length, minMs: Math.min(...values), maxMs: Math.max(...values), samplesMs: values });
const report = { host: { ...host, loadAfter: loadavg() }, rowsPerTransaction: count, warmupsPerArm: 2, samplesPerArm: 5, commitIncluded: true, cleanupOutsideTiming: true, baseline: stats(samples[0]!), treatment: stats(samples[1]!) };
if (arg("output")) await fs.writeFile(arg("output")!, JSON.stringify(report, null, 2));
console.log(JSON.stringify(report, null, 2));
} finally {
clearInterval(keepAlive);
for (const client of clients) await client.$client.end({ timeout: 0 });
}