Files
PaperClipAI/server/src/services/activity-log.ts
T
DottaandPaperclip c47452699a perf(server): speed up headless channel posts, replies, and SSE bursts (#23426)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Headless channels, threads, and SSE streams let agents and tools
exchange high-rate status updates and structured messages
> - A local headless benchmark on `origin/master` (`828b8c2a2a`) showed
channel posts at 226 req/s (`c=1`) and 342–346 req/s (`c=32`), with
database tuple scans growing linearly with company issue count and live
SSE streams falling behind under burst
> - CPU, heap, and PostgreSQL profiling traced the bottlenecks to an
unindexed `O(N)` `MAX(issue_number)` scan per post, redundant SQL
round-trips and uncached transactional `instance_settings` reads inside
the company row lock, upfront `FOR UPDATE` locks on normal replies,
serial per-event SSE database checks, and routing through 64 unrelated
Express sub-routers
> - This pull request adds an online-compatible `issues(company_id,
issue_number)` index so `MAX(issue_number)` floor checks run as `O(log
N)` index-only probes inside the `companies` counter update, eliminates
redundant channel/view/savepoint queries, locks parent issues on replies
only when `clientRequestId` or `after` is supplied, mounts headless
routers early, and extracts a unified bounded SSE/replay filter pipeline
with creation-time `kvLabels`/`tagLabels` snapshots and pre-change label
history lookup
> - The benefit is 2.09x to 2.67x higher channel post throughput (473
req/s at `c=1`, 885–924 req/s at `c=32`), 1.75x higher reply throughput
(1,221 req/s at `c=32`), 55.5% less heap allocation, `O(log N)`
index-only counter floor checks as issue count grows, and 100% real-time
SSE delivery under burst

## Linked Issues or Issue Description

**What existing behavior does this improve?**

`POST /api/companies/:companyId/channels/posts`, `POST
/api/companies/:companyId/issues/batch`, `POST
/api/issues/:id/comments`, and `GET
/api/companies/:companyId/events/stream` throughput, tail latency, heap
allocation, and database scalability.

**Subsystem affected**

- `packages/db/ — Drizzle schema & migrations`
- `server/ — REST API & orchestration services`

**Current behavior**

On `origin/master` (`828b8c2a2a`, Node `v26.4.0`, `darwin-arm64`, local
`embedded-postgres` with 2 live SSE subscribers):
- `createChannelPost` and `createBatchIssuesPlan` run `SELECT
coalesce(max(issue_number), 0) FROM issues WHERE company_id = $1` on
every call without an index on `(company_id, issue_number)`, scanning
every issue row in the company (`2,029` tuples/request at ~2,400
issues).
- `ensureChannel` ignores the channel row already fetched by
`assertChannelPathWritePreconditions`, runs `INSERT ... ON CONFLICT DO
NOTHING`, and selects the channel a second time.
- `createChannelPost` holds the `companies` row lock while calling
`logActivity(tx, ...)` (which skips the `instance_settings` read-through
cache on `PgTransaction` handles and opens a nested `SAVEPOINT` +
`SELECT pg_current_xact_id()`), running two round-trips in
`appendBoardEvent`, and re-querying four tables in
`loadHeadlessIssueView`.
- `POST /api/issues/:id/comments` selects all 89 `issues` columns via an
unindexed `upper(identifier)` scan when given an identifier and
unconditionally acquires `SELECT ... FOR UPDATE` on `issues` even when
neither `idempotencyKey`/`clientRequestId` nor `after` is supplied.
- `GET /api/companies/:companyId/events/stream` evaluates live events
one at a time with serial `channels` and `issues` queries per event per
subscriber and misses creation-time `labels`/`tagLabels` snapshots
during `?label=` filtering, delivering only ~302–373 of 1,000 events
during a 1,000-message burst.
- `headlessChannelsSchemasRoutes` and `headlessQueuesEventsRoutes` sit
behind 64 unrelated `api.use(...)` Express sub-routers (`15%` CPU in
`path-to-regexp` and `router`).

**Proposed behavior**

- Add an online-compatible `CREATE INDEX CONCURRENTLY IF NOT EXISTS
"issues_company_issue_number_idx" ON "issues" USING btree ("company_id",
"issue_number")` migration (`0513_closed_wither.sql`) and compute
`greatest(companies.issue_counter, coalesce((select
max(issues.issue_number) from issues where issues.company_id = $1), 0))
+ count` directly in `UPDATE companies`, preserving exact monotonic
counter floors (including lone backdated imports) via an `O(log N)`
index-only backward probe in a single round-trip.
- Return the existing channel directly in `ensureChannel` when
`allowUpdateExisting` is false, serialize newly created
`HeadlessIssueView` objects in memory, sort tag labels canonically
before `ON CONFLICT DO NOTHING` upserts, and combine
`pg_advisory_xact_lock` + `INSERT INTO board_events` into one SQL
statement.
- Pre-create `createActivityDetailsRedactor(db)` before transactions so
the 2-second `instance_settings` cache applies, prime
`pg_current_xact_id()` on existing `RETURNING` clauses, and skip nested
`db.transaction` savepoints in `persistActivity` when `db` is already a
`PgTransaction` while preserving `databaseWorkContext` attribution.
- Probe `eq(issues.identifier, normalizedUpper)` first so identifier
lookups use `issues_identifier_idx`, project only the 11 required
columns in issue route interceptors, narrow `--as` profile collision
checks to non-terminated company agents with JS `.trim()` +
`deriveAgentUrlKey` parity, and acquire `FOR UPDATE` on comment creation
only when `clientRequestId` or `after` is present.
- Extract `server/src/services/headless-board-event-stream.ts` and stamp
commit-time `kvLabels` and `tagLabels` snapshots onto issue-scoped event
payloads inside `appendBoardEvent`, so `queryBoardEventsAfter`,
`waitForBoardEvent`, and `filterBoardEventsBatchForSubscriber` share a
single stateless `eventMatchesFiltersAndAccess` verdict pipeline without
cross-batch label caches.
- Mount `headlessChannelsSchemasRoutes` and `headlessQueuesEventsRoutes`
right after `headlessIdentityRoutes` with `headlessHeartbeat` wired in
`server/src/app.ts`.

**Measured performance impact**

- `POST /channels/posts` (`c=1`): `226.4` -> `473.1 req/s` (`2.09x`),
p50 `4.27ms` -> `2.05ms`, p99 `6.98ms` -> `3.15ms`
- `POST /channels/posts` (`c=32`, single channel): `346.4` -> `885.5
req/s` (`2.56x`), p50 `91.8ms` -> `35.4ms`
- `POST /channels/posts` (`c=32`, 16 channels + 2 live SSE clients):
`342.4` -> `924.6 req/s` (`2.70x`), p50 `93.3ms` -> `33.2ms`, live SSE
events delivered during run `302` -> `1,000 / 1,000`
- `POST /issues/:id/comments` (`c=32`): `696.2` -> `1,221.6 req/s`
(`1.75x`), p50 `44.9ms` -> `25.3ms`
- Profiled 1,500 mixed messages (`c=32`): heap allocated `2,369 MB` ->
`1,054 MB` (`-55.5%`).

**Breaking changes**

None. All request/response schemas, status codes, idempotency conflict
rules, `after` stale-cursor checks, gapless `board_events.seq` commit
ordering, and private channel/issue revocation rules remain unchanged.

## What Changed

- Added `issues_company_issue_number_idx` in
`packages/db/src/schema/issues.ts`,
`packages/db/src/migrations/0513_closed_wither.sql` (`CREATE INDEX
CONCURRENTLY IF NOT EXISTS`), and `MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS`
in `packages/db/src/client.ts`.
- Updated `server/src/services/headless-common.ts`,
`server/src/services/headless-channels.ts`, and
`server/src/services/headless-labels-batch.ts` to compute exact indexed
`MAX(issue_number)` counter floors inside `UPDATE companies`, return
existing channels early in `ensureChannel`, prime transaction XIDs, sort
tag label names before upsert, serialize newly created
`HeadlessIssueView` responses in memory, include `kvLabels` and
`tagLabels` snapshots on creation/ready board events, and combine
`pg_advisory_xact_lock` + `INSERT INTO board_events` into a single
round-trip.
- Updated `server/src/services/activity-log.ts` to accept an optional
pre-built `ActivityDetailsRedactor` and skip nested `db.transaction`
savepoints when `persistActivity` runs on an existing `PgTransaction`
while preserving `databaseWorkContext` attribution.
- Updated `server/src/routes/headless-channels-schemas.ts` to use
`resolveIssueCommentTarget`, pre-create the activity redactor on `db`,
prime transaction XIDs on comment inserts, and lock the parent issue
`FOR UPDATE` only when `clientRequestId` or `after` is supplied.
- Extracted `server/src/services/headless-board-event-stream.ts`
(re-exported from
`server/src/services/headless-events-schedules-interactions.ts`) and
updated `server/src/services/headless-common.ts`,
`server/src/routes/headless-queues-events.ts`, and `server/src/app.ts`
to stamp commit-time `kvLabels` and `tagLabels` snapshots in
`appendBoardEvent`, unify single-event, replay, and batched SSE
filtering without cross-batch label caches, and mount headless routers
early with `headlessHeartbeat`.
- Added regression tests in
`server/src/__tests__/headless-channels-schemas-batch.test.ts` (drifted
`issueCounter` + lone backdated `#95` floor, concurrent tag upserts, and
tab/CJK `--as` profile parity) and
`server/src/__tests__/headless-queues-leases-events.test.ts` (live SSE
burst ordering, cold-cache `?label=urgent` `exists` tag +
`labels.changed` interleaving + unlabeled `comment.posted`, and
immediate private-channel revocation).

## Verification

- `pnpm --filter @paperclipai/db run check:migrations && pnpm --filter
@paperclipai/db exec vitest run src/migration-snapshot-drift.test.ts`
(passed, 0 blocked migrations)
- `cd server && node scripts/typecheck-layers.mjs` (0 errors across all
7 layers)
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/activity-log-responsible-user.test.ts
src/__tests__/headless-channels-schemas-batch.test.ts
src/__tests__/headless-queues-leases-events.test.ts
src/__tests__/headless-task-workflows.test.ts
src/__tests__/experimental-channels-viewer.test.ts` (5 files, 41/41
tests passed)

## Risks

- Low risk. Migration `0513_closed_wither.sql` uses `CREATE INDEX
CONCURRENTLY IF NOT EXISTS` and is registered in
`MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS`, so online rollouts do not block
reads or writes on `issues`. Live SSE micro-batching re-evaluates
channel and issue visibility fresh on every drained batch without
cross-batch permission caching, preserving immediate membership
revocation.

## Model Used

- Google Gemini (Antigravity agentic coding assistant, extended thinking
mode with shell, profiling, and test execution tools)

## 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 (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [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-12-02 01:47:17 +00:00

281 lines
11 KiB
TypeScript

import { isDashboardActivity } from "./responsibility-privacy.js";
import { notifyActiveRunSilence } from "./live-run-recovery-notifications.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
import { beginRunPhase } from "./execution-preparation-timing.js";
import type { ActivityPublication } from "../types/activity-publication.js";
export type { ActivityPublication } from "../types/activity-publication.js";
import { randomUUID } from "node:crypto";
import { and, eq, is } from "drizzle-orm";
import { PgTransaction } from "drizzle-orm/pg-core";
import type { Db } from "@paperclipai/db";
import { activityLog, agentApiKeys, companies, heartbeatRuns, issues } from "@paperclipai/db";
import { isUuidLike, PLUGIN_EVENT_TYPES, type PluginEventType } from "@paperclipai/shared";
import type { PluginEvent } from "@paperclipai/plugin-sdk";
import { publishLiveEvent } from "./live-events.js";
import { redactCurrentUserValue } from "../log-redaction.js";
import { sanitizeRecord } from "../redaction.js";
import { logger } from "../middleware/logger.js";
import type { PluginEventBus } from "./plugin-event-bus.js";
import { instanceSettingsService } from "./instance-settings.js";
const PLUGIN_EVENT_SET: ReadonlySet<string> = new Set(PLUGIN_EVENT_TYPES);
const ACTIVITY_ACTION_TO_PLUGIN_EVENT: Readonly<Record<string, PluginEventType>> = {
issue_comment_added: "issue.comment.created",
issue_comment_created: "issue.comment.created",
issue_document_created: "issue.document.created",
issue_document_updated: "issue.document.updated",
issue_document_deleted: "issue.document.deleted",
issue_blockers_updated: "issue.relations.updated",
approval_approved: "approval.decided",
approval_rejected: "approval.decided",
approval_revision_requested: "approval.decided",
budget_soft_threshold_crossed: "budget.incident.opened",
budget_hard_threshold_crossed: "budget.incident.opened",
budget_incident_resolved: "budget.incident.resolved",
};
let _pluginEventBus: PluginEventBus | null = null;
/** Wire the plugin event bus so domain events are forwarded to plugins. */
export function setPluginEventBus(bus: PluginEventBus): void {
if (_pluginEventBus) {
logger.warn("setPluginEventBus called more than once, replacing existing bus");
}
_pluginEventBus = bus;
}
function eventTypeForActivityAction(action: string): PluginEventType | null {
if (PLUGIN_EVENT_SET.has(action)) return action as PluginEventType;
return ACTIVITY_ACTION_TO_PLUGIN_EVENT[action.replaceAll(".", "_")] ?? null;
}
export function publishPluginDomainEvent(event: PluginEvent): void {
if (!_pluginEventBus) return;
void _pluginEventBus.emit(event).then(({ errors }) => {
for (const { pluginId, error } of errors) {
logger.warn({ pluginId, eventType: event.eventType, err: error }, "plugin event handler failed");
}
}).catch(() => {});
}
export interface LogActivityInput {
companyId: string;
actorType: "agent" | "user" | "system" | "plugin";
actorId: string;
action: string;
entityType: string;
entityId: string;
agentId?: string | null;
runId?: string | null;
agentApiKeyId?: string | null;
issueId?: string | null;
details?: Record<string, unknown> | null;
responsibleUserIdOverride?: string | null;
authorization?: { action: string; operation: string; reason: string };
}
export type ActivityDetailsRedactor = (
details: Record<string, unknown> | null,
) => Record<string, unknown> | null;
export interface PersistActivityOptions {
redactor?: ActivityDetailsRedactor;
}
export async function createActivityDetailsRedactor(db: Db): Promise<ActivityDetailsRedactor> {
const currentUserRedactionOptions = {
enabled: (await instanceSettingsService(db).getGeneral()).censorUsernameInLogs,
};
return (details: Record<string, unknown> | null) => (
details ? redactCurrentUserValue(sanitizeRecord(details), currentUserRedactionOptions) : null
);
}
export async function redactActivityDetails(db: Db, details: Record<string, unknown> | null) {
if (!details) return null;
return (await createActivityDetailsRedactor(db))(details);
}
function readNonEmptyString(value: unknown) {
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
}
export async function resolveResponsibleUserIdForActivity(db: Db, input: LogActivityInput) {
if (input.responsibleUserIdOverride !== undefined) {
return readNonEmptyString(input.responsibleUserIdOverride);
}
if (input.actorType === "user") return readNonEmptyString(input.actorId);
const runId = readNonEmptyString(input.runId);
if (runId && isUuidLike(runId)) {
const run = await db
.select({ responsibleUserId: heartbeatRuns.responsibleUserId })
.from(heartbeatRuns)
.where(and(eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.id, runId)))
.then((rows) => rows[0] ?? null);
const runResponsibleUserId = readNonEmptyString(run?.responsibleUserId);
if (runResponsibleUserId) return runResponsibleUserId;
}
const issueIdCandidate = readNonEmptyString(input.issueId)
?? (input.entityType === "issue" ? readNonEmptyString(input.entityId) : null);
const issueId = isUuidLike(issueIdCandidate) ? issueIdCandidate : null;
if (issueId) {
const issue = await db
.select({
responsibleUserId: issues.responsibleUserId,
createdByUserId: issues.createdByUserId,
})
.from(issues)
.where(and(eq(issues.companyId, input.companyId), eq(issues.id, issueId)))
.then((rows) => rows[0] ?? null);
const issueResponsibleUserId = readNonEmptyString(issue?.responsibleUserId)
?? readNonEmptyString(issue?.createdByUserId);
if (issueResponsibleUserId) return issueResponsibleUserId;
}
const agentApiKeyId = readNonEmptyString(input.agentApiKeyId);
const agentId = readNonEmptyString(input.agentId);
if (agentApiKeyId && isUuidLike(agentApiKeyId)) {
const apiKey = await db
.select({ responsibleUserId: agentApiKeys.responsibleUserId })
.from(agentApiKeys)
.where(and(
eq(agentApiKeys.companyId, input.companyId),
eq(agentApiKeys.id, agentApiKeyId),
...(agentId && isUuidLike(agentId) ? [eq(agentApiKeys.agentId, agentId)] : []),
))
.then((rows) => rows[0] ?? null);
const apiKeyResponsibleUserId = readNonEmptyString(apiKey?.responsibleUserId);
if (apiKeyResponsibleUserId) return apiKeyResponsibleUserId;
}
const company = await db
.select({ defaultResponsibleUserId: companies.defaultResponsibleUserId })
.from(companies)
.where(eq(companies.id, input.companyId))
.then((rows) => rows[0] ?? null);
return readNonEmptyString(company?.defaultResponsibleUserId);
}
export function publishActivity(publication: ActivityPublication) {
const finish = beginRunPhase("execution.realtime");
try {
if (isDashboardActivity(publication.payload.entityType)) {
// The company bus carries only an invalidation. Each viewer fetches their own data.
publishLiveEvent({
companyId: publication.companyId,
type: "activity.logged",
payload: { action: "responsibility.dashboard_changed", entityType: "responsibility" },
});
return;
}
publishLiveEvent({
companyId: publication.companyId,
type: "activity.logged",
payload: publication.payload,
});
if (publication.pluginEvent) publishPluginDomainEvent(publication.pluginEvent);
} finally { finish(); }
}
export async function persistActivity(
db: Db,
input: LogActivityInput,
receipt?: { id: string },
options?: PersistActivityOptions,
) {
const rawDetails = input.authorization
? {
...input.details,
permissionDecision: input.authorization,
...(input.agentApiKeyId ? { agentApiKeyId: input.agentApiKeyId } : {}),
}
: (input.details ?? null);
const redactedDetails = options?.redactor
? options.redactor(rawDetails)
: await redactActivityDetails(db, rawDetails);
const responsibleUserId = await resolveResponsibleUserIdForActivity(db, input);
const insert = (runner: Db) => runner.insert(activityLog).values({
...(receipt ? { id: receipt.id } : {}),
companyId: input.companyId,
actorType: input.actorType,
actorId: input.actorId,
action: input.action,
entityType: input.entityType,
entityId: input.entityId,
agentId: input.agentId ?? null,
runId: input.runId ?? null,
responsibleUserId,
details: redactedDetails,
}).returning({ id: activityLog.id });
const insertIssueActivity = async (runner: Db) => {
await notifyDeliveryWork(runner, DELIVERY_QUEUES.mcpEvents, `task:${input.entityId}`);
if (input.runId && input.action === "issue.updated" && ["done", "cancelled"].includes(String(input.details?.status)))
await notifyActiveRunSilence(runner, { companyId: input.companyId, runId: input.runId });
return insert(runner);
};
const [activity] = input.entityType === "issue"
? (is(db, PgTransaction)
? await insertIssueActivity(db)
: await db.transaction(async tx => insertIssueActivity(tx as unknown as Db)))
: await insert(db);
const payload = {
issueId: input.issueId ?? (input.entityType === "issue" ? input.entityId : null),
actorType: input.actorType,
actorId: input.actorId,
action: input.action,
entityType: input.entityType,
entityId: input.entityId,
agentId: input.agentId ?? null,
runId: input.runId ?? null,
responsibleUserId,
details: redactedDetails,
};
const pluginEventType = eventTypeForActivityAction(input.action);
const pluginEvent: PluginEvent | null = pluginEventType
? {
eventId: randomUUID(),
eventType: pluginEventType,
occurredAt: new Date().toISOString(),
actorId: input.actorId,
actorType: input.actorType,
entityId: input.entityId,
entityType: input.entityType,
companyId: input.companyId,
payload: {
...redactedDetails,
agentId: input.agentId ?? null,
runId: input.runId ?? null,
responsibleUserId,
},
}
: null;
return {
activity,
publication: {
companyId: input.companyId,
payload,
pluginEvent,
} satisfies ActivityPublication,
};
}
export async function logActivity(
db: Db,
input: LogActivityInput,
postCommitPublications?: ActivityPublication[],
options?: PersistActivityOptions,
) {
const { activity, publication } = await persistActivity(db, input, undefined, options);
if (postCommitPublications) {
postCommitPublications.push(publication);
} else {
publishActivity(publication);
}
return activity;
}