Files
PaperClipAI/server/src/services/activity-log.ts
DottaandPaperclip debfa75a7a perf(server): coalesce concurrent channel posts and replies with debounced activity (#23448)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Headless channels and thread replies let many agents publish
concurrent updates, tasks, and replies into shared company streams while
preserving gapless company identifiers and commit-ordered board events
> - After PR #23426 removed per-request query overhead, a fresh local
headless benchmark on merged `origin/master` (`ab2183aaed`) showed
concurrent post throughput hitting a serialization wall at 770–805 req/s
(`c=32`) and degrading to 653 req/s (`p99 = 295.9ms`) at `c=64` on a
single channel
> - Profiling showed why: every concurrent post or reply entered its own
database transaction and blocked sequentially on `UPDATE companies`,
`UPDATE channels`, and `pg_advisory_xact_lock('board_events',
company_id)`, pinning PostgreSQL pool connections and performing N
separate WAL flushes for N concurrent arrivals
> - This pull request adds adaptive in-process group commit for
non-idempotent channel posts and normal thread comments, a 250ms
debounce on `channels.last_activity_at` updates, and multi-row
`activity_log` and `board_events` batch helpers
> - The benefit is zero batching delay when idle (`442.7 req/s`, `p50 =
2.12ms` at `c=1`), `2.40x–2.55x` higher post throughput at `c=32`
(`1,849–2,055 req/s`), `3.11x–3.79x` higher post throughput at `c=64`
(`2,475–2,501 req/s`, `p99` down 85.5%), and `2.24x` higher hot-thread
reply throughput (`1,588 req/s`, `p99` down 73%), while keeping gapless
`<PREFIX>-<N>` identifiers and monotonic `evt_<seq>` cursors

## Linked Issues or Issue Description

Refs #23426

**What existing behavior does this improve?**

`POST /api/companies/:companyId/channels/posts`, `POST
/api/companies/:companyId/issues/batch`, `PATCH
/api/issues/:id/kv-labels`, and `POST /api/issues/:id/comments`
throughput, tail latency, and PostgreSQL connection-pool efficiency
under high concurrency.

**Subsystem affected**

- `server/ — REST API & orchestration services`

**Current behavior**

On `origin/master` (`ab2183aaed`, Node `v26.4.0`, `darwin-arm64`, local
`embedded-postgres` with 2 live SSE subscribers):
- Every concurrent `POST /api/companies/:companyId/channels/posts` call
opens an independent database transaction and contends on the single
`companies` counter row, the `channels` row (`SET last_activity_at =
now()`), and the per-company `board_events` advisory lock.
- At `c=32`, post throughput caps at `770.1 req/s` on a single channel
and `804.5 req/s` across 16 channels; at `c=64`, single-channel post
throughput drops to `653.1 req/s` with `p99 = 295.91ms` because waiting
write transactions exhaust the database connection pool.
- Concurrent replies on a single hot thread (`c=32`) serialize on
unconditional `UPDATE channels SET last_activity_at = now()` and
`board_events` advisory locks, capping at `710.1 req/s` (`p99 =
84.47ms`).

**Proposed behavior**

- Add `touchChannelsLastActivity` (250ms staleness guard with ascending
`channels.id` `FOR NO KEY UPDATE` lock ordering) and `appendBoardEvents`
(single `pg_advisory_xact_lock` + ordered multi-row `INSERT INTO
board_events ... RETURNING` sorted by `seq`) in
`server/src/services/headless-board-events-write.ts`, plus
`logActivitiesBatch` in `server/src/services/activity-log.ts`.
- Add `server/src/services/adaptive-company-batcher.ts`,
`server/src/services/headless-post-group-commit.ts`, and
`server/src/services/headless-comment-group-commit.ts` with a
self-cleaning `WeakMap`-backed per-company batcher
(`MAX_COALESCED_BATCH_SIZE = 64`, `MAX_PENDING_PER_COMPANY = 1024`):
- When no batch is in flight (`c=1`), the request dispatches immediately
with zero artificial timer delay.
- While one batch transaction is executing on a single database
connection for that company, concurrent arrivals queue in memory
(bounded with `429` backpressure above `1024`) and execute together in
the next multi-row transaction using real wall-clock `new Date()`
timestamps, `issues.issueNumber` thread tie-breaking in
`listChannelThreads`, and RFC-valid sub-millisecond ordered UUIDs
(`mintTimeOrderedUuid`) across both coalesced and serialized comment
paths.
- Shared `validateChannelPathWriteFromMap` checks per-item channel
access, archived-channel, project access, and assignee rules before
counter allocation so rejected siblings never abort valid siblings or
leave gaps in `<PREFIX>-<N>` issue numbers, and post-commit event
publication runs strictly outside the transaction fallback scope.
- Requests with `idempotencyKey`, `clientRequestId`, or `after` continue
through their dedicated serialized concurrency checks.

**Reason and benefit**

Matched 7-scenario local headless benchmark (`origin/master`
`ab2183aaed` vs `perf/channel-group-commit`, 2 live SSE subscribers
active throughout, 0 errors, 100% live SSE delivery):

| Scenario | Merged `master` (`req/s`) | Group Commit (`req/s`) |
Speedup | `master` `p99` | Group Commit `p99` |
| --- | ---: | ---: | ---: | ---: | ---: |
| 1. Sequential channel posts (`c=1`, 300 msgs) | 451.4 | 442.7 | 0.98x
(no idle delay) | 4.06 ms | 3.79 ms |
| 2. Single-channel posts (`c=32`, 1,000 msgs) | 770.1 | 1,849.2 |
**2.40x** | 89.23 ms | 34.67 ms |
| 3. 16-channel posts (`c=32`, 1,000 msgs) | 804.5 | 2,054.6 | **2.55x**
| 71.76 ms | 22.73 ms |
| 4. 16-thread replies (`c=32`, 1,000 msgs) | 1,045.7 | 1,486.6 |
**1.42x** | 59.53 ms | 28.91 ms |
| 5. Single hot-thread replies (`c=32`, 500 msgs) | 710.1 | 1,588.3 |
**2.24x** | 84.47 ms | 22.70 ms |
| 6. Single-channel posts (`c=64`, 2,000 msgs) | 653.1 | 2,474.7 |
**3.79x** | 295.91 ms | 42.80 ms |
| 7. 16-channel posts (`c=64`, 2,000 msgs) | 803.4 | 2,501.3 | **3.11x**
| 124.65 ms | 32.72 ms |

**Breaking changes**

None. All endpoints, request/response shapes, gapless `<PREFIX>-<N>`
identifiers, commit-ordered `evt_<seq>` cursors, idempotency semantics,
`after` optimistic concurrency checks, and channel/project/issue privacy
checks remain unchanged. `channels.lastActivityAt` updates at most once
per 250ms window under sustained traffic on the same channel.

**Additional context**

Builds on #23426 without schema migrations or external coordination
dependencies.

## What Changed

- Extracted shared activity preparation, row mapping
(`buildActivityLogRow`), side-effect notification, and publication
helpers in `server/src/services/activity-log.ts` and added
`logActivitiesBatch` for single-statement multi-row `activity_log`
inserts.
- Extracted `server/src/services/headless-board-events-write.ts`
(re-exported from `server/src/services/headless-common.ts`) with
`mintTimeOrderedUuid`, `touchChannelsLastActivity` (250ms debounce with
canonical ascending `channels.id` `FOR NO KEY UPDATE` lock ordering),
listener-isolated `subscribeCompanyBoardEvents`, and `appendBoardEvents`
(single `pg_advisory_xact_lock` acquisition with ordered multi-row
`INSERT INTO board_events ... RETURNING` sorted by `seq`).
- Extracted `server/src/services/headless-channel-write-helpers.ts`
(re-exported from `server/src/services/headless-channels.ts`) so channel
path validation, `ensureChannel`, tag upserts, and assignee resolution
are shared via normal imports without per-item callback plumbing.
- Added `server/src/services/adaptive-company-batcher.ts`,
`server/src/services/headless-post-group-commit.ts`, and
`server/src/services/headless-comment-group-commit.ts` implementing
bounded per-company write coalescing (`MAX_COALESCED_BATCH_SIZE = 64`,
`MAX_PENDING_PER_COMPANY = 1024`), post-lock wall-clock `new Date()` +
`mintTimeOrderedUuid` sampling so batches waiting behind `companies` or
`issues` row locks always receive newer `(createdAt, id)` tuples,
UUID-keyed comment `RETURNING` joins, per-item validation isolation, and
post-commit event publication strictly outside the transaction fallback
boundary.
- Updated `createChannelPost` and `listChannelThreads` in
`server/src/services/headless-channels.ts`,
`server/src/services/headless-labels-batch.ts`, and
`server/src/routes/headless-channels-schemas.ts` to tie-break equal
`createdAt` rows on `issues.issueNumber` and use
`touchChannelsLastActivity`, `appendBoardEvents`, `mintTimeOrderedUuid`,
and `executeCoalescedHeadlessComment`.
- Added regression tests in
`server/src/__tests__/adaptive-company-batcher.test.ts`,
`server/src/__tests__/headless-channels-schemas-batch.test.ts` (16-way
mixed burst with pinned per-request statuses, wall-clock bounds,
`issueNumber` thread/after ordering, real PostgreSQL insert-error solo
fallback on both posts and comments, coalesced comment batches waiting
behind active `FOR UPDATE` serialized locks, deterministic 250ms
`lastActivityAt` skip/update assertions, and post-commit throwing
subscriber isolation), and
`server/src/__tests__/activity-log-responsible-user.test.ts`
(`logActivitiesBatch` redaction, `responsibleUserId` attribution, and
`mcpEvents` work signaling).

## Verification

- `cd server && node scripts/typecheck-layers.mjs` (0 errors across all
7 layers)
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/adaptive-company-batcher.test.ts
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` (6 files, 47/47
tests passed)
- Matched 7-scenario local headless benchmark on `origin/master`
(`ab2183aaed`) vs `perf/channel-group-commit` with 2 live SSE
subscribers (`0` errors, `100%` SSE event delivery across all runs)

## Risks

- Low risk. No database migrations or API contract changes. Coalesced
batches hold canonical lock order (`companies -> issues -> channels ->
labels -> issue_labels -> board_events` for posts; `issues ->
issue_comments -> channels -> board_events` for comments), isolate
read-only validation errors per item before minting issue numbers,
delete idle per-company queue state immediately, and fall back to solo
execution if an unexpected database error occurs on a multi-item batch.

## 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 06:13:26 -06:00

380 lines
13 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(); }
}
async function prepareActivityRow(
db: Db,
input: LogActivityInput,
redactor?: ActivityDetailsRedactor,
) {
const rawDetails = input.authorization
? {
...input.details,
permissionDecision: input.authorization,
...(input.agentApiKeyId ? { agentApiKeyId: input.agentApiKeyId } : {}),
}
: (input.details ?? null);
const redactedDetails = redactor
? redactor(rawDetails)
: await redactActivityDetails(db, rawDetails);
const responsibleUserId = await resolveResponsibleUserIdForActivity(db, input);
return { input, redactedDetails, responsibleUserId };
}
async function notifyIssueActivitySideEffects(runner: Db, input: LogActivityInput) {
if (input.entityType !== "issue") return;
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,
});
}
}
function buildActivityPublication(
input: LogActivityInput,
redactedDetails: Record<string, unknown> | null,
responsibleUserId: string | null,
): ActivityPublication {
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 {
companyId: input.companyId,
payload,
pluginEvent,
};
}
function buildActivityLogRow(
prepared: Awaited<ReturnType<typeof prepareActivityRow>>,
receipt?: { id: string },
) {
const { input, redactedDetails, responsibleUserId } = prepared;
return {
...(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,
};
}
export async function persistActivity(
db: Db,
input: LogActivityInput,
receipt?: { id: string },
options?: PersistActivityOptions,
) {
const prepared = await prepareActivityRow(
db,
input,
options?.redactor,
);
const insert = (runner: Db) =>
runner
.insert(activityLog)
.values(buildActivityLogRow(prepared, receipt))
.returning({ id: activityLog.id });
const insertIssueActivity = async (runner: Db) => {
await notifyIssueActivitySideEffects(runner, input);
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);
return {
activity,
publication: buildActivityPublication(
input,
prepared.redactedDetails,
prepared.responsibleUserId,
),
};
}
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;
}
export async function logActivitiesBatch(
db: Db,
inputs: LogActivityInput[],
postCommitPublications?: ActivityPublication[],
options?: PersistActivityOptions,
) {
if (inputs.length === 0) return [];
if (inputs.length === 1) {
const single = await logActivity(db, inputs[0]!, postCommitPublications, options);
return single ? [single] : [];
}
const redactor = options?.redactor ?? (await createActivityDetailsRedactor(db));
const preparedRows = await Promise.all(
inputs.map((input) => prepareActivityRow(db, input, redactor)),
);
const insertBatch = async (runner: Db) => {
for (const { input } of preparedRows) {
await notifyIssueActivitySideEffects(runner, input);
}
return runner
.insert(activityLog)
.values(preparedRows.map((prepared) => buildActivityLogRow(prepared)))
.returning({ id: activityLog.id });
};
const hasIssueEntity = preparedRows.some(({ input }) => input.entityType === "issue");
const insertedActivities =
hasIssueEntity && !is(db, PgTransaction)
? await db.transaction(async (tx) => insertBatch(tx as unknown as Db))
: await insertBatch(db);
for (const { input, redactedDetails, responsibleUserId } of preparedRows) {
const publication = buildActivityPublication(
input,
redactedDetails,
responsibleUserId,
);
if (postCommitPublications) {
postCommitPublications.push(publication);
} else {
publishActivity(publication);
}
}
return insertedActivities;
}