Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(linear): run rule sync rounds in one request instead of a chain of nested hand-offs (#22263)

Rdmclin2a35afe22cefa
diff --git a/apps/server/src/routers/lambda/__tests__/linear.test.ts b/apps/server/src/routers/lambda/__tests__/linear.test.ts
index bc1ef874f9e..ee5c1817a6a 100644
--- a/apps/server/src/routers/lambda/__tests__/linear.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/linear.test.ts
@@ -4,7 +4,11 @@ import { TRPCClientError } from '@trpc/client';
import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { LinearConnectionModel, LinearSyncRuleModel } from '@/database/models/linear';
+import {
+ LinearConnectionModel,
+ LinearSyncJobModel,
+ LinearSyncRuleModel,
+} from '@/database/models/linear';
import {
asyncTasks,
linearConnections,
@@ -15,7 +19,12 @@ import {
workspaces,
} from '@/database/schemas';
import { continueLinearRuleSyncJob } from '@/server/services/linear/startSyncJob';
-import { LINEAR_SYNC_MAX_ROUNDS, LinearSyncJobService } from '@/server/services/linear/syncJob';
+import {
+ LINEAR_SYNC_MAX_HAND_OFFS,
+ LINEAR_SYNC_MAX_ROUNDS,
+ LINEAR_SYNC_RUN_BUDGET_MS,
+ LinearSyncJobService,
+} from '@/server/services/linear/syncJob';
import { linearRouter } from '../linear';
@@ -312,10 +321,20 @@ describe('linearRouter', () => {
return { id, rule };
};
- /** The service as the async router builds it, able to queue the next round. */
- const routerService = () =>
- new LinearSyncJobService(serverDB, userId, undefined, (taskId, metadata) =>
- continueLinearRuleSyncJob(serverDB, userId, undefined, taskId, metadata),
+ /**
+ * The service as the async router builds it, able to queue the next
+ * round. With no time budget, every round is handed to a new request,
+ * as a run that outlasts one request is.
+ */
+ const routerService = (runBudgetMs = 0, maxHandOffs = Infinity) =>
+ new LinearSyncJobService(
+ serverDB,
+ userId,
+ undefined,
+ (taskId, metadata) =>
+ continueLinearRuleSyncJob(serverDB, userId, undefined, taskId, metadata),
+ runBudgetMs,
+ maxHandOffs,
);
const settle = async () => {
@@ -373,6 +392,121 @@ describe('linearRouter', () => {
expect(saved.lastResult).toMatchObject({ created: 242, truncated: false });
});
+ it('runs the rounds one after another in the same request while it has time', async () => {
+ mocks.syncByFilter
+ .mockResolvedValueOnce(round(100, true, '100'))
+ .mockResolvedValueOnce(round(100, true, '200'))
+ .mockResolvedValueOnce(round(100, true, '300'))
+ .mockResolvedValueOnce(round(100, true, '400'))
+ .mockResolvedValueOnce(round(100, true, '500'))
+ .mockResolvedValueOnce(round(42, false))
+ .mockResolvedValueOnce(round(0, false));
+ const { id, rule } = await startRule();
+
+ await routerService(LINEAR_SYNC_RUN_BUDGET_MS).run(id);
+ await settle();
+
+ // One hand-off, the one that started the run: no chain of requests
+ // each waiting on the next, which the host cuts off a few deep.
+ expect(mocks.runSync).toHaveBeenCalledTimes(1);
+ expect(startAfterOfCalls()).toEqual([
+ undefined,
+ '100',
+ '200',
+ '300',
+ '400',
+ '500',
+ undefined,
+ ]);
+ expect(await caller({ userId }).listSyncJobs({ projectId })).toMatchObject([
+ { error: null, id, result: { created: 542, truncated: false }, status: 'success' },
+ ]);
+ const [saved] = await caller({ userId }).listSyncRules({ projectId });
+ expect(saved).toMatchObject({ id: rule.id, lastResult: { created: 542 } });
+ });
+
+ it('hands a slow run to a new request before a round could outlast this one', async () => {
+ // Each round takes 5 minutes: after the first, two more would not fit
+ // in the budget, so the next round goes to a fresh request.
+ let clock = Date.now();
+ const now = vi.spyOn(Date, 'now').mockImplementation(() => clock);
+ try {
+ mocks.syncByFilter.mockImplementation(async (_t, _f, options) => {
+ clock += 5 * 60 * 1000;
+ return options.startAfter ? round(5, false) : round(100, true, '100');
+ });
+ const { id } = await startRule();
+
+ await routerService(LINEAR_SYNC_RUN_BUDGET_MS).run(id);
+ await settle();
+
+ expect(mocks.syncByFilter).toHaveBeenCalledTimes(1);
+ expect(mocks.runSync).toHaveBeenCalledTimes(2);
+ } finally {
+ now.mockRestore();
+ }
+ // Queued for the next request, with the total so far.
+ expect(await caller({ userId }).listSyncJobs({ projectId })).toMatchObject([
+ { error: null, result: { created: 100 }, status: 'pending' },
+ ]);
+ });
+
+ it(`ends a run that keeps running out of time after ${LINEAR_SYNC_MAX_HAND_OFFS} hand-offs, with issues left`, async () => {
+ // Every round is slow, so each request runs one and hands the run on.
+ let clock = Date.now();
+ const now = vi.spyOn(Date, 'now').mockImplementation(() => clock);
+ let page = 0;
+ mocks.syncByFilter.mockImplementation(async () => {
+ clock += 5 * 60 * 1000;
+ page += 1;
+ return round(100, true, String(page * 100));
+ });
+ let id: string;
+ try {
+ ({ id } = await startRule());
+ const service = routerService(LINEAR_SYNC_RUN_BUDGET_MS, LINEAR_SYNC_MAX_HAND_OFFS);
+ for (let handled = 0; handled < mocks.runSync.mock.calls.length; handled++) {
+ await service.run(mocks.runSync.mock.calls[handled][0].taskId);
+ await settle();
+ }
+ } finally {
+ now.mockRestore();
+ }
+
+ // The click, then three hand-offs: four requests, one round each.
+ expect(mocks.runSync).toHaveBeenCalledTimes(LINEAR_SYNC_MAX_HAND_OFFS + 1);
+ expect(mocks.syncByFilter).toHaveBeenCalledTimes(LINEAR_SYNC_MAX_HAND_OFFS + 1);
+ const [job] = await caller({ userId }).listSyncJobs({ projectId });
+ expect(job).toMatchObject({
+ error: null,
+ id: id!,
+ result: { created: 400, truncated: true },
+ status: 'success',
+ });
+ const [saved] = await caller({ userId }).listSyncRules({ projectId });
+ expect(saved.lastResult).toMatchObject({ created: 400, truncated: true });
+ });
+
+ it('stops after the current round when stopped during a run in one request', async () => {
+ const { id } = await startRule();
+ mocks.syncByFilter
+ .mockResolvedValueOnce(round(100, true, '100'))
+ .mockImplementationOnce(async () => {
+ await caller({ userId }).cancelSync({ jobId: id, projectId });
+ return round(100, true, '200');
+ });
+
+ await routerService(LINEAR_SYNC_RUN_BUDGET_MS).run(id);
+
+ expect(mocks.syncByFilter).toHaveBeenCalledTimes(2);
+ expect(mocks.runSync).toHaveBeenCalledTimes(1);
+ expect(await caller({ userId }).listSyncJobs({ projectId })).toMatchObject([
+ { error: 'canceled', id, result: { created: 200 }, status: 'error' },
+ ]);
+ const [rule] = await caller({ userId }).listSyncRules({ projectId });
+ expect(rule).toMatchObject({ lastResult: null, lastRunAt: null });
+ });
+
it('stops when a round neither creates nor moves on, and asks to run again', async () => {
mocks.syncByFilter
.mockResolvedValueOnce(round(100, true, '100'))
@@ -665,6 +799,37 @@ describe('linearRouter', () => {
});
it('leaves a job the router accepted to the router, even when the response is lost', async () => {
+ // The router claimed the job and is running it; only its answer is lost.
+ mocks.runSync.mockImplementation(async ({ taskId }: { taskId: string }) => {
+ await LinearSyncJobModel.claim(serverDB, { userId, workspaceId: null }, taskId);
+ throw new TRPCClientError('fetch failed');
+ });
+
+ const { id } = await startRule();
+ await settled(1);
+
+ expect(mocks.runSync).toHaveBeenCalledTimes(1);
+ expect(await caller({ userId }).listSyncJobs({ projectId })).toMatchObject([
+ { error: null, id, status: 'processing' },
+ ]);
+ });
+
+ it('fails a job the host answered with an error the router never ran', async () => {
+ mocks.runSync.mockRejectedValue(
+ new TRPCClientError('Service Unavailable', {
+ meta: { response: { status: 503 } },
+ } as any),
+ );
+
+ const { id } = await startRule();
+ await settled(1);
+
+ expect(await caller({ userId }).listSyncJobs({ projectId })).toMatchObject([
+ { error: 'failed', id, status: 'error' },
+ ]);
+ });
+
+ it('leaves a job queued when the connection drops without an answer, so the router can still claim it', async () => {
mocks.runSync.mockRejectedValue(new TRPCClientError('fetch failed'));
const { id } = await startRule();
@@ -675,6 +840,22 @@ describe('linearRouter', () => {
{ error: null, id, status: 'pending' },
]);
});
+
+ it('fails a job the host turned away before the router saw it, instead of leaving it queued', async () => {
+ // Vercel answers a request deep in a chain of requests with a 508
+ // page, which the tRPC client fails to read as JSON.
+ mocks.runSync.mockRejectedValue(
+ TRPCClientError.from(new SyntaxError('Unexpected token \'<\', "<!DOCTYPE "...')),
+ );
+
+ const { id } = await startRule();
+ await settled(1);
+
+ expect(mocks.runSync).toHaveBeenCalledTimes(1);
+ expect(await caller({ userId }).listSyncJobs({ projectId })).toMatchObject([
+ { error: 'failed', id, status: 'error' },
+ ]);
+ });
});
it('keeps a long sync alive, so it is not shown as cut off', async () => {
diff --git a/apps/server/src/services/linear/startSyncJob.ts b/apps/server/src/services/linear/startSyncJob.ts
index 7b039940095..48a6ec81cf3 100644
--- a/apps/server/src/services/linear/startSyncJob.ts
+++ b/apps/server/src/services/linear/startSyncJob.ts
@@ -1,7 +1,6 @@
import type { LinearSyncJobErrorCode, LinearSyncJobMetadata } from '@lobechat/types';
import { AsyncTaskStatus, AsyncTaskType } from '@lobechat/types';
import { TRPCClientError } from '@trpc/client';
-import debug from 'debug';
import { AsyncTaskModel } from '@/database/models/asyncTask';
import { LinearSyncJobModel, LinearSyncRuleModel } from '@/database/models/linear';
@@ -11,8 +10,6 @@ import { after } from '@/server/utils/scheduleAfterResponse';
import { toLinearSyncJobView } from './syncJob';
-const log = debug('lobe-server:linear:sync-job');
-
/**
* Hand-offs per job. Only a hand-off the async router turned away before
* claiming the job (its internal token was rejected) is tried again, with a
@@ -128,7 +125,8 @@ const dispatchJob = async (
// Signs a new internal token, so a retry never resends a rejected one.
asyncCaller = await createAsyncCaller({ userId });
} catch (error) {
- log('trigger sync %s failed: %O', taskId, error);
+ // Logged in production too: a lost hand-off otherwise leaves no trace.
+ console.error('[linear-sync] trigger sync %s failed: %O', taskId, error);
await fail();
return;
}
@@ -136,14 +134,25 @@ const dispatchJob = async (
await asyncCaller.linear.runSync({ taskId, workspaceId });
return;
} catch (error) {
- // Any other failure reached the async router, which owns the job from
- // there; a dropped response (a proxy timing out a long run) is not a
- // failed sync, so only log it.
+ // A dropped response (a proxy timing out a long run) is not a failed
+ // sync: the async router claimed the job and owns it from there. A
+ // request the host answered without running it (e.g. Vercel's 508 on
+ // a deep chain of requests) left the job unclaimed for good, so it is
+ // shown as failed now instead of sitting queued until it times out.
+ // An error without an answer (a dropped connection) may still be on
+ // its way to the router, which must be able to claim it; that job
+ // times out as unclaimed if it never arrives.
if (!isRejectedHandOff(error)) {
- log('async sync %s request failed: %O', taskId, error);
+ console.error('[linear-sync] hand-off of sync %s failed: %O', taskId, error);
+ if (isAnsweredHandOff(error)) await fail();
return;
}
- log('async sync %s hand-off rejected (attempt %d): %O', taskId, attempt, error);
+ console.warn(
+ '[linear-sync] hand-off of sync %s rejected (attempt %d): %O',
+ taskId,
+ attempt,
+ error,
+ );
if (attempt >= MAX_DISPATCH_ATTEMPTS) {
await fail();
return;
@@ -153,6 +162,16 @@ const dispatchJob = async (
});
};
+/**
+ * The host sent an answer, so the request is over: had the router run it, it
+ * would have claimed the job first, and `fail` only touches an unclaimed one.
+ * A tRPC answer carries its response; a host page that is not tRPC JSON (such
+ * as Vercel's 508) fails to parse, which a dropped connection never does.
+ */
+const isAnsweredHandOff = (error: unknown) =>
+ error instanceof TRPCClientError &&
+ (error.meta?.response !== undefined || error.cause instanceof SyntaxError);
+
/** The async router refused the call before running it, so the job is still unclaimed. */
const isRejectedHandOff = (error: unknown) =>
error instanceof TRPCClientError && error.data?.code === 'UNAUTHORIZED';
diff --git a/apps/server/src/services/linear/syncJob.ts b/apps/server/src/services/linear/syncJob.ts
index db73e150b87..6f1a0b0edc4 100644
--- a/apps/server/src/services/linear/syncJob.ts
+++ b/apps/server/src/services/linear/syncJob.ts
@@ -37,6 +37,20 @@ export const LINEAR_SYNC_UNCLAIMED_MS = 2 * 60 * 1000;
* run at about 5,000 new tasks.
*/
export const LINEAR_SYNC_MAX_ROUNDS = 50;
+/**
+ * How long one request may keep running rounds before it hands the run to a
+ * new request; inside the async route's time limit (800s on Vercel). A round
+ * starts only when twice the slowest round so far still fits, so a slow
+ * round near the end goes to a fresh request instead of being cut off.
+ */
+export const LINEAR_SYNC_RUN_BUDGET_MS = 12 * 60 * 1000;
+/**
+ * Times one rule run may hand itself to a new request. Every hand-off extends
+ * a chain of requests started by the user's click, and Vercel never delivered
+ * a fifth one: four requests in all. A run that would need more ends as
+ * finished with issues left (`truncated`), and the next Sync carries on.
+ */
+export const LINEAR_SYNC_MAX_HAND_OFFS = 3;
/**
* The outcome of a run that took several rounds. What a round wrote happens
@@ -150,6 +164,10 @@ export class LinearSyncJobService {
private readonly userId: string,
private readonly workspaceId?: string,
private readonly continueJob?: ContinueLinearSyncJob,
+ /** How long this request keeps starting rounds before handing the run on. */
+ private readonly runBudgetMs: number = LINEAR_SYNC_RUN_BUDGET_MS,
+ /** How many times one run may be handed to a new request. */
+ private readonly maxHandOffs: number = LINEAR_SYNC_MAX_HAND_OFFS,
) {}
/** Run a recorded job to completion (async router side). */
@@ -182,61 +200,109 @@ export class LinearSyncJobService {
if (!failed)
await LinearSyncJobModel.settleStopped(this.db, this.scope, taskId, { duration });
};
+ // Rounds run here, one after another, while the run is within its time
+ // budget. Handing every round to a new async request instead nests each
+ // request inside the previous one (it waits for the next), and the host
+ // refuses a chain a few requests deep (Vercel: 508 INFINITE_LOOP_DETECTED),
+ // which left the run queued until it showed as cut off.
+ let current = metadata;
try {
- const round = await this.execute(metadata);
- const roundResult = withoutResumePoint(round);
- const rounds = (metadata.rounds ?? 0) + 1;
- const result = mergeLinearSyncResults(metadata.result, roundResult, {
- resumed: metadata.cursor !== undefined,
- });
- // A rule run that hit its per-round cap goes on by itself, so the user
- // does not have to press Sync once per hundred issues.
- const proposed =
- this.continueJob && metadata.kind === 'rule'
- ? nextLinearSyncRound(metadata.cursor, round)
- : undefined;
- const next = withinRoundCap(proposed, rounds, metadata.cursor !== undefined);
- const outcome = {
- ...metadata,
- cursor: undefined,
- reconcileOnly: undefined,
- result,
- rounds,
- };
- if (next) {
- log('sync %s continues (round %d, %d created so far)', taskId, rounds, result.created);
- const queued = await this.continueJob!(taskId, {
- ...metadata,
- cursor: next.cursor,
- // Past the cap, the closing pass creates nothing, so the cap holds.
- reconcileOnly: rounds >= LINEAR_SYNC_MAX_ROUNDS || undefined,
+ let slowestRound = 0;
+ for (;;) {
+ const roundStartedAt = Date.now();
+ const round = await this.execute(current);
+ slowestRound = Math.max(slowestRound, Date.now() - roundStartedAt);
+ const roundResult = withoutResumePoint(round);
+ const rounds = (current.rounds ?? 0) + 1;
+ const result = mergeLinearSyncResults(current.result, roundResult, {
+ resumed: current.cursor !== undefined,
+ });
+ // A rule run that hit its per-round cap goes on by itself, so the user
+ // does not have to press Sync once per hundred issues.
+ const proposed =
+ this.continueJob && current.kind === 'rule'
+ ? nextLinearSyncRound(current.cursor, round)
+ : undefined;
+ const next = withinRoundCap(proposed, rounds, current.cursor !== undefined);
+ const outcome = {
+ ...current,
+ cursor: undefined,
+ handOffs: undefined,
+ reconcileOnly: undefined,
result,
rounds,
- });
- if (queued) return;
- }
- // The rule shows its last finished run; a round in between, or a run
- // stopped part-way, leaves the previous one in place. The job turns
- // successful together with that record, or neither changes and the
- // failure below marks the job failed.
- const succeeded = await this.db.transaction(async (tx) => {
- const done = await LinearSyncJobModel.transition(
- tx,
- this.scope,
- taskId,
- [AsyncTaskStatus.Processing],
- { duration: Date.now() - startedAt, metadata: outcome, status: AsyncTaskStatus.Success },
- );
- if (done && metadata.kind === 'rule' && metadata.ruleId) {
- await LinearSyncRuleModel.recordRun(tx, metadata.ruleId, this.scope, result);
+ };
+ if (next) {
+ const following: LinearSyncJobMetadata = {
+ ...current,
+ cursor: next.cursor,
+ // Past the cap, the closing pass creates nothing, so the cap holds.
+ reconcileOnly: rounds >= LINEAR_SYNC_MAX_ROUNDS || undefined,
+ result,
+ rounds,
+ };
+ log('sync %s continues (round %d, %d created so far)', taskId, rounds, result.created);
+ if (Date.now() - startedAt + 2 * slowestRound < this.runBudgetMs) {
+ // Record the total so far, which also checks no stop was requested.
+ const kept = await LinearSyncJobModel.transition(
+ this.db,
+ this.scope,
+ taskId,
+ [AsyncTaskStatus.Processing],
+ { metadata: following },
+ );
+ if (kept) {
+ current = following;
+ continue;
+ }
+ await LinearSyncJobModel.settleStopped(this.db, this.scope, taskId, {
+ duration: Date.now() - startedAt,
+ metadata: outcome,
+ });
+ return;
+ }
+ // Out of time: a new request takes the next round, unless the chain
+ // of requests is as long as the host lets it get. Then the run ends
+ // here with issues left, and the next Sync starts a new chain.
+ const handOffs = current.handOffs ?? 0;
+ if (handOffs < this.maxHandOffs) {
+ const queued = await this.continueJob!(taskId, {
+ ...following,
+ handOffs: handOffs + 1,
+ });
+ if (queued) return;
+ } else {
+ log('sync %s stops after %d hand-offs, issues left', taskId, handOffs);
+ }
}
- return done;
- });
- if (!succeeded) {
- await LinearSyncJobModel.settleStopped(this.db, this.scope, taskId, {
- duration: Date.now() - startedAt,
- metadata: outcome,
+ // The rule shows its last finished run; a round in between, or a run
+ // stopped part-way, leaves the previous one in place. The job turns
+ // successful together with that record, or neither changes and the
+ // failure below marks the job failed.
+ const succeeded = await this.db.transaction(async (tx) => {
+ const done = await LinearSyncJobModel.transition(
+ tx,
+ this.scope,
+ taskId,
+ [AsyncTaskStatus.Processing],
+ {
+ duration: Date.now() - startedAt,
+ metadata: outcome,
+ status: AsyncTaskStatus.Success,
+ },
+ );
+ if (done && current.kind === 'rule' && current.ruleId) {
+ await LinearSyncRuleModel.recordRun(tx, current.ruleId, this.scope, result);
+ }
+ return done;
});
+ if (!succeeded) {
+ await LinearSyncJobModel.settleStopped(this.db, this.scope, taskId, {
+ duration: Date.now() - startedAt,
+ metadata: outcome,
+ });
+ }
+ return;
}
} catch (error) {
const code = toErrorCode(error);
diff --git a/packages/types/src/linear.ts b/packages/types/src/linear.ts
index f093df8a22c..ef93e107e0f 100644
--- a/packages/types/src/linear.ts
+++ b/packages/types/src/linear.ts
@@ -197,6 +197,12 @@ export interface LinearSyncJobMetadata {
* does not reread what earlier rounds covered. Absent: read from the start.
*/
cursor?: string;
+ /**
+ * Times a rule run was handed to a new request because one ran out of time.
+ * Each hand-off is one more request in a chain the host cuts off a few
+ * requests deep, so a run stops handing off after a few.
+ */
+ handOffs?: number;
/** Picked issues (`kind: 'issues'`). */
issueIds?: string[];
kind: 'issues' | 'rule';