Files
PaperClipAI/server/src/services/headless-board-event-stream.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

849 lines
23 KiB
TypeScript

import { and, asc, eq, gt, inArray } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
boardEvents,
channels,
issueLabels,
issues,
labels,
} from "@paperclipai/db";
import {
boardEventTypeSchema,
formatEventCursor,
isUuidLike,
matchesLabelFilter,
normalizeChannelPath,
normalizeIssueIdentifier,
parseEventCursor,
parseLabelFilterExpr,
parseSchemaRef,
type BoardEventType,
type BoardEventView,
type LabelFilterExpr,
type SchemaBlock,
} from "@paperclipai/shared";
import { badRequest } from "../errors.js";
import { issueReadSqlCondition, type AuthorizationActor } from "./authorization.js";
import {
buildAuthActorFromHeadless,
canAccessChannel,
enforceHeadlessScopes,
findInaccessibleChannelIds,
getLatestCompanyEventCursor,
subscribeCompanyBoardEvents,
type DbOrTx,
type HeadlessActorContext,
} from "./headless-common.js";
export type IssueLabelSnapshot = {
kvLabels: Record<string, string>;
tagLabels: string[];
};
export type IssueLabelCache = Map<string, IssueLabelSnapshot>;
export interface BoardEventFilterInput {
channel?: string;
issueId?: string;
event?: BoardEventType[];
label?: string[];
mentions?: string;
schema?: string;
after?: string;
}
export interface ParsedBoardEventFilters {
afterSeq: number;
hasExplicitAfter: boolean;
channelNorm: { path: string; isSubtreePrefix: boolean } | null;
issueUuid: string | null;
issueIdentifierUpper: string | null;
eventTypes: Set<BoardEventType> | null;
labelExprs: LabelFilterExpr[];
mentionsName: string | null;
schemaFilter: { name: string; version: null | number } | null;
}
function escapeRegExp(input: string): string {
return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function isChannelAllowedByScopes(
actor: HeadlessActorContext,
channelPath: string,
): boolean {
try {
enforceHeadlessScopes(actor, { channelPath });
return true;
} catch {
return false;
}
}
function isStringRecord(val: unknown): val is Record<string, string> {
return Boolean(val) && typeof val === "object" && !Array.isArray(val);
}
function extractIssuePayloadKvLabels(
ev: BoardEventView,
): Record<string, string> | null {
if (ev.type === "labels.changed" && isStringRecord(ev.payload.current)) {
return ev.payload.current;
}
if (isStringRecord(ev.payload.kvLabels)) return ev.payload.kvLabels;
if (isStringRecord(ev.payload.current)) return ev.payload.current;
if (
(ev.type === "thread.posted" ||
ev.type === "task.created" ||
ev.type === "task.ready") &&
isStringRecord(ev.payload.labels)
) {
return ev.payload.labels;
}
return null;
}
function extractPayloadTagLabels(
payload: Record<string, unknown>,
): string[] | undefined {
return Array.isArray(payload.tagLabels)
? payload.tagLabels.filter((x): x is string => typeof x === "string")
: undefined;
}
export function parseBoardEventFilters(
filters: BoardEventFilterInput,
): ParsedBoardEventFilters {
let afterSeq = 0;
let hasExplicitAfter = false;
if (filters.after !== undefined && filters.after.trim() !== "") {
const parsed = parseEventCursor(filters.after);
if (parsed === null) {
throw badRequest(
`Invalid cursor "${filters.after}": expected evt_<non-negative-integer>`,
);
}
afterSeq = parsed;
hasExplicitAfter = true;
}
let channelNorm: { path: string; isSubtreePrefix: boolean } | null = null;
if (filters.channel && filters.channel.trim() !== "") {
try {
channelNorm = normalizeChannelPath(filters.channel, {
allowSubtreePrefix: true,
});
} catch (err) {
throw badRequest(err instanceof Error ? err.message : "Invalid channel");
}
}
let issueUuid: string | null = null;
let issueIdentifierUpper: string | null = null;
if (filters.issueId && filters.issueId.trim() !== "") {
const trimmed = filters.issueId.trim();
if (isUuidLike(trimmed)) {
issueUuid = trimmed.toLowerCase();
} else {
issueIdentifierUpper = (
normalizeIssueIdentifier(trimmed) ?? trimmed
).toUpperCase();
}
}
let eventTypes: Set<BoardEventType> | null = null;
if (filters.event && filters.event.length > 0) {
eventTypes = new Set();
for (const raw of filters.event) {
const parsed = boardEventTypeSchema.safeParse(raw);
if (!parsed.success) {
throw badRequest(`Invalid board event type "${raw}"`);
}
eventTypes.add(parsed.data);
}
}
const labelExprs: LabelFilterExpr[] = [];
if (filters.label && filters.label.length > 0) {
for (const raw of filters.label) {
try {
labelExprs.push(parseLabelFilterExpr(raw));
} catch (err) {
throw badRequest(
err instanceof Error ? err.message : "Invalid label filter",
);
}
}
}
let mentionsName: string | null = null;
if (filters.mentions && filters.mentions.trim() !== "") {
mentionsName = filters.mentions.trim().replace(/^@/, "").toLowerCase();
}
let schemaFilter: { name: string; version: number | null } | null = null;
if (filters.schema && filters.schema.trim() !== "") {
const rawSchema = filters.schema.trim();
if (rawSchema.includes("@")) {
try {
const parsed = parseSchemaRef(rawSchema);
schemaFilter = { name: parsed.name, version: parsed.version };
} catch (err) {
throw badRequest(
err instanceof Error ? err.message : "Invalid schema filter",
);
}
} else {
schemaFilter = { name: rawSchema, version: null };
}
}
return {
afterSeq,
hasExplicitAfter,
channelNorm,
issueUuid,
issueIdentifierUpper,
eventTypes,
labelExprs,
mentionsName,
schemaFilter,
};
}
export async function getCurrentCompanyMaxEventSeq(
dbOrTx: DbOrTx,
companyId: string,
): Promise<number> {
const cursor = await getLatestCompanyEventCursor(dbOrTx, companyId);
return parseEventCursor(cursor) ?? 0;
}
function serializeBoardEventRow(
row: typeof boardEvents.$inferSelect,
): BoardEventView {
const seq = Number(row.seq);
return {
cursor: formatEventCursor(seq),
seq,
type: row.eventType,
companyId: row.companyId,
channel: row.channelPath ?? null,
issueId: row.issueId ?? null,
identifier: row.identifier ?? null,
actor: {
type: row.actorType,
id: row.actorId ?? null,
name: row.actorName ?? null,
profile: row.actorProfile ?? null,
},
payload: (row.payload ?? {}) as Record<string, unknown>,
createdAt: row.createdAt.toISOString(),
};
}
function matchesNonDbEventFilters(
ev: BoardEventView,
parsed: ParsedBoardEventFilters,
): boolean {
if (ev.seq <= parsed.afterSeq) return false;
if (parsed.eventTypes && !parsed.eventTypes.has(ev.type)) {
return false;
}
if (parsed.channelNorm) {
if (!ev.channel) return false;
if (parsed.channelNorm.isSubtreePrefix) {
if (
ev.channel !== parsed.channelNorm.path &&
!ev.channel.startsWith(`${parsed.channelNorm.path}/`)
) {
return false;
}
} else if (ev.channel !== parsed.channelNorm.path) {
return false;
}
}
if (parsed.issueUuid) {
if (!ev.issueId || ev.issueId.toLowerCase() !== parsed.issueUuid) {
return false;
}
} else if (parsed.issueIdentifierUpper) {
if (
!ev.identifier ||
ev.identifier.toUpperCase() !== parsed.issueIdentifierUpper
) {
return false;
}
}
if (parsed.mentionsName) {
const mentionRegex = new RegExp(
`(^|\\s)@${escapeRegExp(parsed.mentionsName)}(\\b|$)`,
"i",
);
const candidateTexts = [
ev.payload.text,
ev.payload.body,
ev.payload.title,
ev.payload.message,
ev.payload.description,
].filter((v): v is string => typeof v === "string");
if (!candidateTexts.some((txt) => mentionRegex.test(txt))) {
return false;
}
}
if (parsed.schemaFilter) {
const blocks = Array.isArray(ev.payload.blocks)
? (ev.payload.blocks as Array<Partial<SchemaBlock>>)
: [];
const matched = blocks.some(
(b) =>
b &&
b.schema === parsed.schemaFilter!.name &&
(parsed.schemaFilter!.version === null ||
b.version === parsed.schemaFilter!.version),
);
if (!matched) {
return false;
}
}
return true;
}
function canBypassEventChannelPrivacy(
companyId: string,
actor: HeadlessActorContext,
): boolean {
return (
actor.companyId === companyId &&
(actor.isInstanceAdmin || actor.principalType === "local_trusted")
);
}
async function canActorAccessEventChannel(
db: Db,
companyId: string,
actor: HeadlessActorContext,
channelPath: string | null,
cache?: Map<string, boolean>,
): Promise<boolean> {
if (!channelPath) return true;
if (!isChannelAllowedByScopes(actor, channelPath)) return false;
if (canBypassEventChannelPrivacy(companyId, actor)) {
return true;
}
const cached = cache?.get(channelPath);
if (cached !== undefined) return cached;
const [ch] = await db
.select({
id: channels.id,
companyId: channels.companyId,
visibility: channels.visibility,
createdByUserId: channels.createdByUserId,
createdByAgentId: channels.createdByAgentId,
})
.from(channels)
.where(and(eq(channels.companyId, companyId), eq(channels.path, channelPath)))
.limit(1);
const allowed = ch ? await canAccessChannel(db, ch, actor) : true;
cache?.set(channelPath, allowed);
return allowed;
}
function findHistoricalKvLabelsBeforeLaterChange(
events: BoardEventView[],
fromIndex: number,
issueId: string,
lookaheadEvents?: BoardEventView[],
): Record<string, string> | undefined {
for (let j = fromIndex + 1; j < events.length; j += 1) {
const later = events[j]!;
if (
later.type === "labels.changed" &&
later.issueId === issueId &&
isStringRecord(later.payload.previous)
) {
return later.payload.previous;
}
}
if (lookaheadEvents) {
for (let j = 0; j < lookaheadEvents.length; j += 1) {
const later = lookaheadEvents[j]!;
if (
later.type === "labels.changed" &&
later.issueId === issueId &&
isStringRecord(later.payload.previous)
) {
return later.payload.previous;
}
}
}
return undefined;
}
async function loadCurrentIssueLabelSnapshot(
db: Db,
issueId: string,
): Promise<IssueLabelSnapshot> {
const [issueRow] = await db
.select({ kvLabels: issues.kvLabels })
.from(issues)
.where(eq(issues.id, issueId))
.limit(1);
const tagRows = await db
.select({ name: labels.name })
.from(issueLabels)
.innerJoin(labels, eq(issueLabels.labelId, labels.id))
.where(eq(issueLabels.issueId, issueId));
return {
kvLabels: (issueRow?.kvLabels ?? {}) as Record<string, string>,
tagLabels: tagRows.map((t) => t.name),
};
}
async function eventMatchesLabelFilters(
db: Db,
ev: BoardEventView,
labelExprs: LabelFilterExpr[],
batchFallbackCache?: IssueLabelCache,
historicalKvLabelsOverride?: Record<string, string>,
): Promise<boolean> {
if (ev.type === "labels.changed" && ev.issueId) {
batchFallbackCache?.delete(ev.issueId);
}
if (labelExprs.length === 0) return true;
let kvLabels =
extractIssuePayloadKvLabels(ev) ?? historicalKvLabelsOverride ?? null;
let tagLabels = extractPayloadTagLabels(ev.payload);
const unresolvedExistsExpr = labelExprs.some(
(expr) =>
expr.kind === "exists" &&
(kvLabels === null ||
!Object.prototype.hasOwnProperty.call(kvLabels, expr.key)),
);
const needsTagLookup = tagLabels === undefined && unresolvedExistsExpr;
if ((kvLabels === null || needsTagLookup) && ev.issueId) {
let fallback = batchFallbackCache?.get(ev.issueId);
if (!fallback) {
fallback = await loadCurrentIssueLabelSnapshot(db, ev.issueId);
if (historicalKvLabelsOverride === undefined) {
batchFallbackCache?.set(ev.issueId, fallback);
}
}
if (kvLabels === null) {
kvLabels = fallback.kvLabels;
}
if (tagLabels === undefined) {
tagLabels = fallback.tagLabels;
}
}
const effectiveKv = kvLabels ?? {};
return labelExprs.every((expr) =>
matchesLabelFilter(effectiveKv, tagLabels, expr),
);
}
export async function eventMatchesFiltersAndAccess(
db: Db,
companyId: string,
actor: HeadlessActorContext,
ev: BoardEventView,
parsed: ParsedBoardEventFilters,
channelCache?: Map<string, boolean>,
batchFallbackCache?: IssueLabelCache,
readableIssueIds?: Set<string>,
authActor?: AuthorizationActor,
historicalKvLabelsOverride?: Record<string, string>,
): Promise<boolean> {
if (!matchesNonDbEventFilters(ev, parsed)) {
if (ev.type === "labels.changed" && ev.issueId) {
batchFallbackCache?.delete(ev.issueId);
}
return false;
}
if (!(await canActorAccessEventChannel(db, companyId, actor, ev.channel, channelCache))) {
if (ev.type === "labels.changed" && ev.issueId) {
batchFallbackCache?.delete(ev.issueId);
}
return false;
}
if (ev.issueId) {
if (readableIssueIds) {
if (!readableIssueIds.has(ev.issueId)) {
if (ev.type === "labels.changed") {
batchFallbackCache?.delete(ev.issueId);
}
return false;
}
} else {
const effectiveAuthActor = authActor ?? buildAuthActorFromHeadless(actor);
const readCondition = await issueReadSqlCondition(db, effectiveAuthActor);
const [readable] = await db
.select({ id: issues.id })
.from(issues)
.where(
and(
eq(issues.companyId, companyId),
eq(issues.id, ev.issueId),
readCondition,
),
)
.limit(1);
if (!readable) {
if (ev.type === "labels.changed") {
batchFallbackCache?.delete(ev.issueId);
}
return false;
}
}
}
return eventMatchesLabelFilters(
db,
ev,
parsed.labelExprs,
batchFallbackCache,
historicalKvLabelsOverride,
);
}
async function prepareBatchAccessMaps(
db: Db,
companyId: string,
actor: HeadlessActorContext,
events: BoardEventView[],
parsed: ParsedBoardEventFilters,
effectiveAuthActor: AuthorizationActor,
channelCache?: Map<string, boolean>,
): Promise<{
batchChannelAccess: Map<string, boolean>;
readableIssueIds: Set<string>;
}> {
const batchChannelAccess = channelCache ?? new Map<string, boolean>();
const scopeEligible = events.filter(
(ev) =>
matchesNonDbEventFilters(ev, parsed) &&
(!ev.channel || isChannelAllowedByScopes(actor, ev.channel)),
);
if (scopeEligible.length === 0) {
return { batchChannelAccess, readableIssueIds: new Set() };
}
if (canBypassEventChannelPrivacy(companyId, actor)) {
for (const ev of scopeEligible) {
if (ev.channel) batchChannelAccess.set(ev.channel, true);
}
} else {
const uncheckedPaths = Array.from(
new Set(
scopeEligible
.map((ev) => ev.channel)
.filter(
(ch): ch is string => Boolean(ch) && !batchChannelAccess.has(ch!),
),
),
);
if (uncheckedPaths.length > 0) {
const chRows = await db
.select({
id: channels.id,
companyId: channels.companyId,
path: channels.path,
visibility: channels.visibility,
createdByUserId: channels.createdByUserId,
createdByAgentId: channels.createdByAgentId,
})
.from(channels)
.where(
and(
eq(channels.companyId, companyId),
inArray(channels.path, uncheckedPaths),
),
);
const inaccessibleIds = new Set(
await findInaccessibleChannelIds(db, companyId, actor, chRows),
);
for (const ch of chRows) {
batchChannelAccess.set(ch.path, !inaccessibleIds.has(ch.id));
}
for (const path of uncheckedPaths) {
if (!batchChannelAccess.has(path)) {
batchChannelAccess.set(path, true);
}
}
}
}
const distinctIssueIds = Array.from(
new Set(
scopeEligible
.filter((ev) => (ev.channel ? batchChannelAccess.get(ev.channel) !== false : true))
.map((ev) => ev.issueId)
.filter((id): id is string => Boolean(id)),
),
);
const readableIssueIds = new Set<string>();
if (distinctIssueIds.length > 0) {
const readCondition = await issueReadSqlCondition(db, effectiveAuthActor);
const readableRows = await db
.select({ id: issues.id })
.from(issues)
.where(
and(
eq(issues.companyId, companyId),
inArray(issues.id, distinctIssueIds),
readCondition,
),
);
for (const r of readableRows) {
readableIssueIds.add(r.id);
}
}
return { batchChannelAccess, readableIssueIds };
}
export async function filterBoardEventsBatchForSubscriber(
db: Db,
companyId: string,
actor: HeadlessActorContext,
events: BoardEventView[],
parsed: ParsedBoardEventFilters,
authActor?: AuthorizationActor,
channelCache?: Map<string, boolean>,
lookaheadEvents?: BoardEventView[],
): Promise<BoardEventView[]> {
if (events.length === 0) return [];
const effectiveAuthActor = authActor ?? buildAuthActorFromHeadless(actor);
const { batchChannelAccess, readableIssueIds } = await prepareBatchAccessMaps(
db,
companyId,
actor,
events,
parsed,
effectiveAuthActor,
channelCache,
);
const batchFallbackCache: IssueLabelCache = new Map();
const matched: BoardEventView[] = [];
for (let i = 0; i < events.length; i += 1) {
const ev = events[i]!;
const historicalKv =
parsed.labelExprs.length > 0 &&
ev.issueId &&
extractIssuePayloadKvLabels(ev) === null
? findHistoricalKvLabelsBeforeLaterChange(
events,
i,
ev.issueId,
lookaheadEvents,
)
: undefined;
const ok = await eventMatchesFiltersAndAccess(
db,
companyId,
actor,
ev,
parsed,
batchChannelAccess,
batchFallbackCache,
readableIssueIds,
effectiveAuthActor,
historicalKv,
);
if (ok) {
matched.push(ev);
}
}
return matched;
}
export async function queryBoardEventsAfter(
db: Db,
companyId: string,
actor: HeadlessActorContext,
filtersOrParsed: BoardEventFilterInput | ParsedBoardEventFilters,
opts: { limit?: number; authActor?: AuthorizationActor } = {},
): Promise<BoardEventView[]> {
enforceHeadlessScopes(actor, { action: "events.read" });
const parsed =
"afterSeq" in filtersOrParsed
? filtersOrParsed
: parseBoardEventFilters(filtersOrParsed);
const limit = Math.min(Math.max(1, opts.limit ?? 100), 500);
const effectiveAuthActor = opts.authActor ?? buildAuthActorFromHeadless(actor);
const channelCache = new Map<string, boolean>();
const results: BoardEventView[] = [];
let cursorSeq = parsed.afterSeq;
const batchSize = 200;
while (results.length < limit) {
const conditions = [
eq(boardEvents.companyId, companyId),
gt(boardEvents.seq, cursorSeq),
];
if (parsed.eventTypes && parsed.eventTypes.size > 0) {
const sqlEventTypes: BoardEventType[] =
parsed.labelExprs.length > 0 && !parsed.eventTypes.has("labels.changed")
? [...parsed.eventTypes, "labels.changed"]
: Array.from(parsed.eventTypes);
conditions.push(inArray(boardEvents.eventType, sqlEventTypes));
}
if (parsed.issueUuid) {
conditions.push(eq(boardEvents.issueId, parsed.issueUuid));
}
const rows = await db
.select()
.from(boardEvents)
.where(and(...conditions))
.orderBy(asc(boardEvents.seq))
.limit(batchSize);
if (rows.length === 0) break;
const batchEvents = rows.map(serializeBoardEventRow);
cursorSeq = Math.max(cursorSeq, batchEvents[batchEvents.length - 1]!.seq);
const matchedBatch = await filterBoardEventsBatchForSubscriber(
db,
companyId,
actor,
batchEvents,
parsed,
effectiveAuthActor,
channelCache,
);
for (const ev of matchedBatch) {
results.push(ev);
if (results.length >= limit) break;
}
if (rows.length < batchSize) break;
}
return results;
}
export async function waitForBoardEvent(
db: Db,
companyId: string,
actor: HeadlessActorContext,
filters: BoardEventFilterInput,
opts: {
timeoutMs?: number;
signal?: AbortSignal;
authActor?: AuthorizationActor;
onResolvedCursor?: (cursor: string) => void;
} = {},
): Promise<BoardEventView | null> {
enforceHeadlessScopes(actor, { action: "events.read" });
const parsed = parseBoardEventFilters(filters);
const timeoutMs = Math.min(Math.max(0, opts.timeoutMs ?? 30_000), 120_000);
const effectiveAuthActor = opts.authActor ?? buildAuthActorFromHeadless(actor);
const channelCache = new Map<string, boolean>();
const buffered: BoardEventView[] = [];
let checkingInitial = true;
let resolveWaiter: ((ev: BoardEventView | null) => void) | null = null;
const unsubscribe = subscribeCompanyBoardEvents(companyId, (ev) => {
if (checkingInitial) {
buffered.push(ev);
return;
}
if (ev.seq <= parsed.afterSeq) return;
void eventMatchesFiltersAndAccess(
db,
companyId,
actor,
ev,
parsed,
channelCache,
undefined,
undefined,
effectiveAuthActor,
)
.then((ok) => {
if (ok && resolveWaiter) {
const resolveFn = resolveWaiter;
resolveWaiter = null;
resolveFn(ev);
}
})
.catch(() => {});
});
try {
if (parsed.hasExplicitAfter) {
opts.onResolvedCursor?.(formatEventCursor(parsed.afterSeq));
const existing = await queryBoardEventsAfter(db, companyId, actor, parsed, {
limit: 1,
authActor: effectiveAuthActor,
});
if (existing.length > 0) {
return existing[0]!;
}
} else {
parsed.afterSeq = await getCurrentCompanyMaxEventSeq(db, companyId);
opts.onResolvedCursor?.(formatEventCursor(parsed.afterSeq));
}
while (buffered.length > 0) {
const ev = buffered.shift()!;
if (
await eventMatchesFiltersAndAccess(
db,
companyId,
actor,
ev,
parsed,
channelCache,
undefined,
undefined,
effectiveAuthActor,
)
) {
return ev;
}
}
if (timeoutMs <= 0 || opts.signal?.aborted) {
return null;
}
return await new Promise<BoardEventView | null>((resolve) => {
let settled = false;
const finish = (result: BoardEventView | null) => {
if (settled) return;
settled = true;
clearTimeout(timer);
opts.signal?.removeEventListener("abort", onAbort);
resolveWaiter = null;
resolve(result);
};
const onAbort = () => finish(null);
resolveWaiter = finish;
checkingInitial = false;
const timer = setTimeout(() => finish(null), timeoutMs);
opts.signal?.addEventListener("abort", onAbort, { once: true });
});
} finally {
unsubscribe();
}
}