mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 11:47:42 +01:00
## 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>
672 lines
20 KiB
TypeScript
672 lines
20 KiB
TypeScript
import { createHash, randomUUID } from "node:crypto";
|
|
import { and, eq, inArray, sql } from "drizzle-orm";
|
|
import type { Db } from "@paperclipai/db";
|
|
import {
|
|
channels,
|
|
companies,
|
|
issueBatchIdempotencyKeys,
|
|
issueRelations,
|
|
issues,
|
|
primeDatabaseWorkTransactionId,
|
|
projects,
|
|
} from "@paperclipai/db";
|
|
import {
|
|
applyKvLabelMutation,
|
|
KvLabelMutationSchema,
|
|
validateAndSortBatchPlan,
|
|
type BatchCreatedTaskItem,
|
|
type BatchCreateIssuesResult,
|
|
type BoardEventView,
|
|
type IssueScope,
|
|
} from "@paperclipai/shared";
|
|
import { badRequest, conflict, unprocessable } from "../errors.js";
|
|
import {
|
|
createActivityDetailsRedactor,
|
|
logActivity,
|
|
publishActivity,
|
|
type ActivityPublication,
|
|
} from "./activity-log.js";
|
|
import {
|
|
attachTagLabels,
|
|
ensureChannel,
|
|
resolveAssigneeAgent,
|
|
} from "./headless-channels.js";
|
|
import {
|
|
appendBoardEvent,
|
|
appendBoardEvents,
|
|
assertIssueChannelScopeAccess,
|
|
assertProjectReadAccess,
|
|
buildNextIssueCounterSql,
|
|
enforceHeadlessScopes,
|
|
loadHeadlessIssueViews,
|
|
publishCommittedBoardEvent,
|
|
resolveIssueByIdOrIdentifier,
|
|
resolveProjectReference,
|
|
touchChannelsLastActivity,
|
|
type HeadlessActorContext,
|
|
} from "./headless-common.js";
|
|
import {
|
|
assertSchemaExists,
|
|
formatBlocksAsFencedJson,
|
|
validateSchemaBlocks,
|
|
} from "./headless-schemas.js";
|
|
|
|
function canonicalizeValue(value: unknown): unknown {
|
|
if (Array.isArray(value)) {
|
|
return value.map(canonicalizeValue);
|
|
}
|
|
if (typeof value === "object" && value !== null) {
|
|
const obj = value as Record<string, unknown>;
|
|
const sorted: Record<string, unknown> = {};
|
|
for (const key of Object.keys(obj).sort()) {
|
|
const v = obj[key];
|
|
if (v !== undefined) {
|
|
sorted[key] = canonicalizeValue(v);
|
|
}
|
|
}
|
|
return sorted;
|
|
}
|
|
return value;
|
|
}
|
|
|
|
function hashCanonicalRequest(rawInput: unknown): string {
|
|
const canonical = JSON.stringify(canonicalizeValue(rawInput));
|
|
return createHash("sha256").update(canonical).digest("hex");
|
|
}
|
|
|
|
function assertNoReservedLabelKeys(rawMutation: unknown): void {
|
|
if (!rawMutation || typeof rawMutation !== "object") return;
|
|
const mut = rawMutation as Record<string, unknown>;
|
|
if (mut.set && typeof mut.set === "object" && !Array.isArray(mut.set)) {
|
|
for (const key of Object.keys(mut.set)) {
|
|
if (key.startsWith("paperclip.")) {
|
|
throw badRequest("Label keys starting with 'paperclip.' are reserved", {
|
|
error: "reserved_label",
|
|
code: "reserved_label",
|
|
key,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
if (Array.isArray(mut.unset)) {
|
|
for (const key of mut.unset) {
|
|
if (typeof key === "string" && key.startsWith("paperclip.")) {
|
|
throw badRequest("Label keys starting with 'paperclip.' are reserved", {
|
|
error: "reserved_label",
|
|
code: "reserved_label",
|
|
key,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
export async function mutateIssueKvLabels(
|
|
db: Db,
|
|
issueRef: string,
|
|
actor: HeadlessActorContext,
|
|
rawMutation: unknown,
|
|
): Promise<{ id: string; kvLabels: Record<string, string>; cursor: string }> {
|
|
enforceHeadlessScopes(actor, { action: "label" });
|
|
assertNoReservedLabelKeys(rawMutation);
|
|
|
|
const parsed = KvLabelMutationSchema.safeParse(rawMutation);
|
|
if (!parsed.success) {
|
|
throw badRequest(
|
|
parsed.error.issues
|
|
.map((i) => `${i.path.join(".") || "$"}: ${i.message}`)
|
|
.join("; "),
|
|
{
|
|
error: "validation_error",
|
|
code: "validation_error",
|
|
issues: parsed.error.issues,
|
|
},
|
|
);
|
|
}
|
|
|
|
const target = await resolveIssueByIdOrIdentifier(db, issueRef, actor.companyId);
|
|
|
|
const publications: ActivityPublication[] = [];
|
|
let committedEvent!: BoardEventView;
|
|
|
|
const result = await db.transaction(async (tx) => {
|
|
const [locked] = await tx
|
|
.select()
|
|
.from(issues)
|
|
.where(and(eq(issues.id, target.id), eq(issues.companyId, actor.companyId)))
|
|
.for("update");
|
|
|
|
if (!locked) {
|
|
throw conflict("Issue disappeared during transaction");
|
|
}
|
|
|
|
const { channelPath } = await assertIssueChannelScopeAccess(tx, locked, actor);
|
|
if (!locked.channelId) {
|
|
enforceHeadlessScopes(actor, { action: "label" });
|
|
}
|
|
|
|
const currentKvLabels = (locked.kvLabels ?? {}) as Record<string, string>;
|
|
const applied = applyKvLabelMutation(currentKvLabels, parsed.data);
|
|
if (!applied.ok) {
|
|
throw conflict("Label Compare-And-Swap precondition failed", {
|
|
error: "label_conflict",
|
|
code: "label_conflict",
|
|
conflictingKeys: applied.conflictingKeys,
|
|
currentLabels: currentKvLabels,
|
|
});
|
|
}
|
|
|
|
const now = new Date();
|
|
await tx
|
|
.update(issues)
|
|
.set({
|
|
kvLabels: applied.labels,
|
|
updatedAt: now,
|
|
})
|
|
.where(eq(issues.id, locked.id));
|
|
|
|
await touchChannelsLastActivity(tx, [locked.channelId], now);
|
|
|
|
await logActivity(
|
|
tx as unknown as Db,
|
|
{
|
|
companyId: actor.companyId,
|
|
actorType: actor.principalType === "agent" ? "agent" : "user",
|
|
actorId:
|
|
actor.principalType === "agent"
|
|
? actor.agentId!
|
|
: (actor.userId ?? "local-board"),
|
|
agentId: actor.agentId,
|
|
issueId: locked.id,
|
|
responsibleUserIdOverride: actor.responsibleUserId,
|
|
action: "issue.kv_labels_updated",
|
|
entityType: "issue",
|
|
entityId: locked.id,
|
|
details: {
|
|
previous: currentKvLabels,
|
|
current: applied.labels,
|
|
},
|
|
},
|
|
publications,
|
|
);
|
|
|
|
committedEvent = await appendBoardEvent(tx, {
|
|
companyId: actor.companyId,
|
|
type: "labels.changed",
|
|
channelId: locked.channelId,
|
|
channelPath,
|
|
issueId: locked.id,
|
|
identifier: locked.identifier ?? locked.id,
|
|
actor,
|
|
payload: {
|
|
previous: currentKvLabels,
|
|
current: applied.labels,
|
|
},
|
|
});
|
|
|
|
return {
|
|
id: locked.id,
|
|
kvLabels: applied.labels,
|
|
cursor: committedEvent.cursor,
|
|
};
|
|
});
|
|
|
|
for (const pub of publications) {
|
|
publishActivity(pub);
|
|
}
|
|
publishCommittedBoardEvent(committedEvent);
|
|
|
|
return result;
|
|
}
|
|
|
|
export async function createBatchIssuesPlan(
|
|
db: Db,
|
|
companyId: string,
|
|
actor: HeadlessActorContext,
|
|
rawInput: unknown,
|
|
): Promise<BatchCreateIssuesResult> {
|
|
const plan = validateAndSortBatchPlan(rawInput);
|
|
if (!plan.ok) {
|
|
const { ok: _ok, message: _msg, ...planDetails } = plan;
|
|
throw unprocessable(plan.message, {
|
|
error: plan.code,
|
|
...planDetails,
|
|
});
|
|
}
|
|
|
|
enforceHeadlessScopes(actor, {
|
|
action: "tasks.create",
|
|
channelPath: plan.channel,
|
|
});
|
|
|
|
const requestHash = hashCanonicalRequest(rawInput);
|
|
const activityRedactor = await createActivityDetailsRedactor(db);
|
|
const publications: ActivityPublication[] = [];
|
|
const committedEvents: BoardEventView[] = [];
|
|
|
|
const result = await db.transaction(async (tx) => {
|
|
if (plan.idempotencyKey) {
|
|
// Serialize concurrent requests sharing the same (companyId, idempotencyKey)
|
|
// before reading or writing any tasks so losers never commit duplicates.
|
|
await tx.execute(
|
|
sql`SELECT pg_advisory_xact_lock(hashtext(${companyId}), hashtext(${plan.idempotencyKey}))`,
|
|
);
|
|
const [existingIdemp] = await tx
|
|
.select()
|
|
.from(issueBatchIdempotencyKeys)
|
|
.where(
|
|
and(
|
|
eq(issueBatchIdempotencyKeys.companyId, companyId),
|
|
eq(issueBatchIdempotencyKeys.idempotencyKey, plan.idempotencyKey),
|
|
),
|
|
)
|
|
.limit(1);
|
|
|
|
if (existingIdemp) {
|
|
if (existingIdemp.requestHash === requestHash) {
|
|
return {
|
|
...(existingIdemp.responsePayload as unknown as BatchCreateIssuesResult),
|
|
idempotentReplay: true,
|
|
};
|
|
}
|
|
throw conflict("Idempotency key already used with a different plan payload", {
|
|
error: "idempotency_conflict",
|
|
code: "idempotency_conflict",
|
|
idempotencyKey: plan.idempotencyKey,
|
|
});
|
|
}
|
|
}
|
|
|
|
const channel = plan.channel
|
|
? await ensureChannel(tx, companyId, actor, { path: plan.channel })
|
|
: null;
|
|
|
|
let planDefaultProjectId: string | null = channel?.defaultProjectId ?? null;
|
|
if (plan.projectId !== undefined) {
|
|
planDefaultProjectId =
|
|
plan.projectId === null
|
|
? null
|
|
: await resolveProjectReference(tx, companyId, plan.projectId, actor);
|
|
} else if (planDefaultProjectId) {
|
|
await assertProjectReadAccess(tx, companyId, planDefaultProjectId, actor);
|
|
}
|
|
|
|
// Pre-resolve external dependencies
|
|
const externalIssueByRef = new Map<string, typeof issues.$inferSelect>();
|
|
for (const task of plan.tasks) {
|
|
for (const extRef of task.externalNeeds) {
|
|
if (!externalIssueByRef.has(extRef)) {
|
|
const extIssue = await resolveIssueByIdOrIdentifier(
|
|
tx,
|
|
extRef,
|
|
companyId,
|
|
);
|
|
await assertIssueChannelScopeAccess(tx, extIssue, actor);
|
|
externalIssueByRef.set(extRef, extIssue);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Validate blocks, resultSchema, projectId, and assignees for all tasks before writing
|
|
const resolvedTaskConfigs: Array<{
|
|
projectId: string | null;
|
|
assigneeAgentId: string | null;
|
|
resultSchemaRef: string | null;
|
|
}> = [];
|
|
|
|
for (const task of plan.tasks) {
|
|
await validateSchemaBlocks(tx, companyId, task.blocks);
|
|
const resultSchemaRef = task.resultSchema
|
|
? await assertSchemaExists(tx, companyId, task.resultSchema)
|
|
: null;
|
|
|
|
let taskProjectId = planDefaultProjectId;
|
|
if (task.projectId === null) {
|
|
taskProjectId = null;
|
|
} else if (task.projectId !== undefined) {
|
|
taskProjectId = await resolveProjectReference(
|
|
tx,
|
|
companyId,
|
|
task.projectId,
|
|
actor,
|
|
);
|
|
}
|
|
|
|
const assigneeAgentId = await resolveAssigneeAgent(tx, companyId, {
|
|
assigneeAgentId: task.assigneeAgentId,
|
|
for: task.for,
|
|
});
|
|
|
|
resolvedTaskConfigs.push({
|
|
projectId: taskProjectId,
|
|
assigneeAgentId,
|
|
resultSchemaRef,
|
|
});
|
|
}
|
|
|
|
const referencedProjectIds = Array.from(
|
|
new Set(
|
|
resolvedTaskConfigs
|
|
.map((c) => c.projectId)
|
|
.filter((id): id is string => Boolean(id)),
|
|
),
|
|
);
|
|
const privateProjectIds = new Set<string>();
|
|
if (referencedProjectIds.length > 0) {
|
|
const projRows = await tx
|
|
.select({ id: projects.id, visibility: projects.visibility })
|
|
.from(projects)
|
|
.where(
|
|
and(
|
|
eq(projects.companyId, companyId),
|
|
inArray(projects.id, referencedProjectIds),
|
|
),
|
|
);
|
|
for (const p of projRows) {
|
|
if (p.visibility === "private") privateProjectIds.add(p.id);
|
|
}
|
|
}
|
|
|
|
const now = new Date();
|
|
const nextBatchCounterExpr = buildNextIssueCounterSql(
|
|
companyId,
|
|
plan.tasks.length,
|
|
);
|
|
|
|
const [companyRow] = await tx
|
|
.update(companies)
|
|
.set({
|
|
issueCounter: nextBatchCounterExpr,
|
|
updatedAt: now,
|
|
})
|
|
.where(eq(companies.id, companyId))
|
|
.returning({
|
|
issueCounter: companies.issueCounter,
|
|
issuePrefix: companies.issuePrefix,
|
|
xid: sql<string>`pg_current_xact_id()::text`,
|
|
});
|
|
|
|
if (companyRow?.xid) {
|
|
primeDatabaseWorkTransactionId(tx, companyRow.xid);
|
|
}
|
|
|
|
const firstIssueNumber = companyRow!.issueCounter - plan.tasks.length + 1;
|
|
|
|
const createdByKey = new Map<string, typeof issues.$inferSelect>();
|
|
const createdRows: Array<typeof issues.$inferSelect> = [];
|
|
const pendingEvents: Array<{
|
|
issueId: string;
|
|
identifier: string;
|
|
key: string | null;
|
|
type: "task.created" | "task.ready";
|
|
payload: Record<string, unknown>;
|
|
isTaskCreated?: boolean;
|
|
}> = [];
|
|
const cursorByIssueId = new Map<string, string>();
|
|
const keyByIssueId = new Map<string, string | null>();
|
|
|
|
for (let i = 0; i < plan.tasks.length; i += 1) {
|
|
const task = plan.tasks[i]!;
|
|
const cfg = resolvedTaskConfigs[i]!;
|
|
const issueNumber = firstIssueNumber + i;
|
|
const identifier = `${companyRow!.issuePrefix}-${issueNumber}`;
|
|
const scope: IssueScope =
|
|
(task.board ?? plan.board) ? "board" : channel ? "channel" : "board";
|
|
const description =
|
|
task.description !== null
|
|
? task.description
|
|
: task.blocks.length > 0
|
|
? formatBlocksAsFencedJson(task.blocks)
|
|
: null;
|
|
const taskVisibility: "open" | "private" =
|
|
channel?.visibility === "private" ||
|
|
(cfg.projectId !== null && privateProjectIds.has(cfg.projectId))
|
|
? "private"
|
|
: "open";
|
|
const taskIssueId = randomUUID();
|
|
const privacyRootIssueId = taskVisibility === "private" ? taskIssueId : null;
|
|
|
|
const [inserted] = await tx
|
|
.insert(issues)
|
|
.values({
|
|
id: taskIssueId,
|
|
companyId,
|
|
projectId: cfg.projectId,
|
|
channelId: channel?.id ?? null,
|
|
visibility: taskVisibility,
|
|
privacyRootIssueId,
|
|
title: task.title,
|
|
description,
|
|
status: "todo",
|
|
scope,
|
|
priority: task.priority,
|
|
assigneeAgentId: cfg.assigneeAgentId,
|
|
createdByAgentId: actor.agentId,
|
|
createdByUserId: actor.agentId ? null : actor.userId,
|
|
createdByProfile: actor.actorProfile,
|
|
responsibleUserId: actor.responsibleUserId,
|
|
kvLabels: task.labels,
|
|
schemaBlocks: task.blocks,
|
|
resultSchemaRef: cfg.resultSchemaRef,
|
|
issueNumber,
|
|
identifier,
|
|
originKind: "manual",
|
|
createdAt: now,
|
|
updatedAt: now,
|
|
})
|
|
.returning();
|
|
|
|
createdRows.push(inserted!);
|
|
keyByIssueId.set(inserted!.id, task.key);
|
|
if (task.key) {
|
|
createdByKey.set(task.key, inserted!);
|
|
}
|
|
|
|
const attachedTagNames =
|
|
task.tagLabels.length > 0
|
|
? await attachTagLabels(tx, companyId, inserted!.id, task.tagLabels)
|
|
: [];
|
|
|
|
const blockerIds: string[] = [];
|
|
let hasOpenBlocker = false;
|
|
|
|
for (const localKey of task.localNeeds) {
|
|
const blocker = createdByKey.get(localKey)!;
|
|
blockerIds.push(blocker.id);
|
|
hasOpenBlocker = true;
|
|
}
|
|
for (const extRef of task.externalNeeds) {
|
|
const ext = externalIssueByRef.get(extRef)!;
|
|
if (!blockerIds.includes(ext.id)) {
|
|
blockerIds.push(ext.id);
|
|
}
|
|
if (ext.status !== "done" && ext.status !== "cancelled") {
|
|
hasOpenBlocker = true;
|
|
}
|
|
}
|
|
|
|
if (blockerIds.length > 0) {
|
|
await tx
|
|
.insert(issueRelations)
|
|
.values(
|
|
blockerIds.map((blockerId) => ({
|
|
companyId,
|
|
issueId: blockerId,
|
|
relatedIssueId: inserted!.id,
|
|
type: "blocks" as const,
|
|
createdByAgentId: actor.agentId,
|
|
createdByUserId: actor.agentId ? null : actor.userId,
|
|
})),
|
|
)
|
|
.onConflictDoNothing({
|
|
target: [
|
|
issueRelations.companyId,
|
|
issueRelations.issueId,
|
|
issueRelations.relatedIssueId,
|
|
issueRelations.type,
|
|
],
|
|
});
|
|
}
|
|
|
|
await logActivity(
|
|
tx as unknown as Db,
|
|
{
|
|
companyId,
|
|
actorType: actor.principalType === "agent" ? "agent" : "user",
|
|
actorId:
|
|
actor.principalType === "agent"
|
|
? actor.agentId!
|
|
: (actor.userId ?? "local-board"),
|
|
agentId: actor.agentId,
|
|
issueId: inserted!.id,
|
|
responsibleUserIdOverride: actor.responsibleUserId,
|
|
action: "issue.created",
|
|
entityType: "issue",
|
|
entityId: inserted!.id,
|
|
details: {
|
|
identifier,
|
|
channel: channel?.path ?? null,
|
|
batchKey: task.key,
|
|
blockedByIssueIds: blockerIds,
|
|
},
|
|
},
|
|
publications,
|
|
{ redactor: activityRedactor },
|
|
);
|
|
|
|
pendingEvents.push({
|
|
issueId: inserted!.id,
|
|
identifier,
|
|
key: task.key ?? null,
|
|
type: "task.created",
|
|
isTaskCreated: true,
|
|
payload: {
|
|
key: task.key,
|
|
title: task.title,
|
|
...(description ? { description: description.slice(0, 4000) } : {}),
|
|
labels: task.labels,
|
|
kvLabels: task.labels,
|
|
tagLabels: attachedTagNames,
|
|
blockedByIssueIds: blockerIds,
|
|
},
|
|
});
|
|
|
|
if (!hasOpenBlocker && cfg.assigneeAgentId === null) {
|
|
pendingEvents.push({
|
|
issueId: inserted!.id,
|
|
identifier,
|
|
key: task.key ?? null,
|
|
type: "task.ready",
|
|
payload: {
|
|
key: task.key,
|
|
kvLabels: task.labels,
|
|
tagLabels: attachedTagNames,
|
|
},
|
|
});
|
|
}
|
|
}
|
|
|
|
await touchChannelsLastActivity(tx, [channel?.id], now);
|
|
|
|
const appendedBatchEvents = await appendBoardEvents(
|
|
tx,
|
|
pendingEvents.map((evInput) => ({
|
|
companyId,
|
|
type: evInput.type,
|
|
channelId: channel?.id ?? null,
|
|
channelPath: channel?.path ?? null,
|
|
issueId: evInput.issueId,
|
|
identifier: evInput.identifier,
|
|
actor,
|
|
payload: evInput.payload,
|
|
})),
|
|
);
|
|
for (let i = 0; i < appendedBatchEvents.length; i += 1) {
|
|
const evt = appendedBatchEvents[i]!;
|
|
committedEvents.push(evt);
|
|
cursorByIssueId.set(pendingEvents[i]!.issueId, evt.cursor);
|
|
}
|
|
|
|
const issueViews = await loadHeadlessIssueViews(tx, createdRows);
|
|
const items: BatchCreatedTaskItem[] = issueViews.map((issueView) => {
|
|
const cursor = cursorByIssueId.get(issueView.id) ?? issueView.cursor;
|
|
return {
|
|
key: keyByIssueId.get(issueView.id) ?? null,
|
|
id: issueView.id,
|
|
identifier: issueView.identifier,
|
|
cursor,
|
|
issue: {
|
|
...issueView,
|
|
cursor,
|
|
},
|
|
};
|
|
});
|
|
|
|
const latestCursor =
|
|
committedEvents[committedEvents.length - 1]?.cursor ?? "evt_0";
|
|
const batchResult: BatchCreateIssuesResult = {
|
|
tasks: items,
|
|
cursor: latestCursor,
|
|
idempotentReplay: false,
|
|
};
|
|
|
|
if (plan.idempotencyKey) {
|
|
const [insertedKey] = await tx
|
|
.insert(issueBatchIdempotencyKeys)
|
|
.values({
|
|
companyId,
|
|
idempotencyKey: plan.idempotencyKey,
|
|
requestHash,
|
|
responsePayload: batchResult as unknown as Record<string, unknown>,
|
|
})
|
|
.onConflictDoNothing({
|
|
target: [
|
|
issueBatchIdempotencyKeys.companyId,
|
|
issueBatchIdempotencyKeys.idempotencyKey,
|
|
],
|
|
})
|
|
.returning();
|
|
|
|
if (!insertedKey) {
|
|
const [raced] = await tx
|
|
.select()
|
|
.from(issueBatchIdempotencyKeys)
|
|
.where(
|
|
and(
|
|
eq(issueBatchIdempotencyKeys.companyId, companyId),
|
|
eq(issueBatchIdempotencyKeys.idempotencyKey, plan.idempotencyKey),
|
|
),
|
|
)
|
|
.limit(1);
|
|
if (raced && raced.requestHash === requestHash) {
|
|
return {
|
|
...(raced.responsePayload as unknown as BatchCreateIssuesResult),
|
|
idempotentReplay: true,
|
|
};
|
|
}
|
|
throw conflict(
|
|
"Idempotency key already used with a different plan payload",
|
|
{
|
|
error: "idempotency_conflict",
|
|
code: "idempotency_conflict",
|
|
idempotencyKey: plan.idempotencyKey,
|
|
},
|
|
);
|
|
}
|
|
}
|
|
|
|
return batchResult;
|
|
});
|
|
|
|
if (!result.idempotentReplay) {
|
|
for (const pub of publications) {
|
|
publishActivity(pub);
|
|
}
|
|
for (const evt of committedEvents) {
|
|
publishCommittedBoardEvent(evt);
|
|
}
|
|
}
|
|
|
|
return result;
|
|
}
|