⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
fix(worker): don't count a rate-limited tick as a failed attempt (#494)
Thomas Gallaway48b2426de65e
diff --git a/apps/worker/AGENTS.md b/apps/worker/AGENTS.mdindex 0dd6fc8c..9f162ba1 100644--- a/apps/worker/AGENTS.md+++ b/apps/worker/AGENTS.md@@ -37,8 +37,8 @@ running to completion in one.config types, how to build its reader, and its issue-key prefix for Rewrite. Anew source adds an entry here; the phases do not change.- `import-retry.ts` — what a failed tick does: a rate limit is waited out and- never fails the job by itself, any other error retries with backoff until- `MAX_ATTEMPTS` in a row.+ does not count toward the attempt limit (the claim's bump is undone), any+ other error retries with backoff until `MAX_ATTEMPTS` in a row.- `plane-adapter.ts` — the only implementation today. HTTP against a Planeinstance via `pinnedFetch`, using the credential decrypted from the job row(base URL, workspace slug, API key — never from env, since this has to workdiff --git a/apps/worker/src/__tests__/integration/import-store.test.ts b/apps/worker/src/__tests__/integration/import-store.test.tsindex 0a327232..06204758 100644--- a/apps/worker/src/__tests__/integration/import-store.test.ts+++ b/apps/worker/src/__tests__/integration/import-store.test.ts@@ -19,6 +19,8 @@ import { eq } from 'drizzle-orm';import { encryptSecret } from '@repo/crypto';import { getObject } from '@repo/storage';import { readerForJob, sourceProjectKeyForJob } from '../../import-sources';+import { tickErrorOutcome } from '../../import-retry';+import { SourceRateLimitedError } from '../../reader';import { PlaneReader } from '../../plane-adapter';import {claimDueImportJobs,@@ -27,6 +29,7 @@ import {createLocalIssueAndRecord,createLocalAttachmentAndRecord,findImportRecord,+ retryImportJobLater,AttachmentRejectedError,type NewLocalIssue,} from '../../import-store';@@ -136,6 +139,59 @@ describe('claimDueImportJobs', () => {});});+async function claimJob(jobId: number): Promise<number> {+ await db+ .update(importJob)+ .set({ nextAttemptAt: new Date(Date.now() - 1000) })+ .where(eq(importJob.id, jobId));+ const claimed = await claimDueImportJobs(1000);+ return claimed.find((j) => j.id === jobId)!.attempts;+}++async function attemptsOf(jobId: number): Promise<number> {+ const [row] = await db.select().from(importJob).where(eq(importJob.id, jobId));+ return row!.attempts;+}++describe('retryImportJobLater', () => {+ it('undoes the claim bump when the tick does not count as an attempt', async () => {+ const { projectId, userId } = await makeProject();+ const jobId = await makeImportJob(projectId, userId);++ expect(await claimJob(jobId)).toBe(1);+ await retryImportJobLater(jobId, 1000, 'rate limited', false);+ expect(await attemptsOf(jobId)).toBe(0);++ expect(await claimJob(jobId)).toBe(1);+ await retryImportJobLater(jobId, 1000, 'HTTP 502', true);+ expect(await attemptsOf(jobId)).toBe(1);+ });++ it('never takes attempts below zero', async () => {+ const { projectId, userId } = await makeProject();+ const jobId = await makeImportJob(projectId, userId);++ await retryImportJobLater(jobId, 1000, 'rate limited', false);+ expect(await attemptsOf(jobId)).toBe(0);+ });++ it('keeps a rate-limited run from exhausting the attempt limit', async () => {+ const { projectId, userId } = await makeProject();+ const jobId = await makeImportJob(projectId, userId);++ for (let i = 0; i < 10; i++) {+ const attempts = await claimJob(jobId);+ const outcome = tickErrorOutcome(new SourceRateLimitedError(1000), attempts);+ if (outcome.action !== 'retry') throw new Error('rate limit must retry');+ await retryImportJobLater(jobId, outcome.delayMs, outcome.lastError, outcome.countsAsAttempt);+ }+ expect(await attemptsOf(jobId)).toBe(0);++ const attempts = await claimJob(jobId);+ expect(tickErrorOutcome(new Error('HTTP 502'), attempts).action).toBe('retry');+ });+});+describe('decryptImportCredential', () => {it('resumes a Plane job the api created, mid-phase, with the same reader and key', async () => {const { projectId, userId } = await makeProject();diff --git a/apps/worker/src/__tests__/unit/import-retry.test.ts b/apps/worker/src/__tests__/unit/import-retry.test.tsindex 4556d871..c18daec2 100644--- a/apps/worker/src/__tests__/unit/import-retry.test.ts+++ b/apps/worker/src/__tests__/unit/import-retry.test.ts@@ -8,6 +8,7 @@ describe('tickErrorOutcome', () => {action: 'retry',delayMs: 45_000,lastError: 'rate limited',+ countsAsAttempt: false,});});@@ -22,6 +23,7 @@ describe('tickErrorOutcome', () => {expect(outcome).toMatchObject({action: 'retry',lastError: 'Plane request failed: HTTP 502',+ countsAsAttempt: true,});const delayMs = (outcome as { delayMs: number }).delayMs;expect(delayMs).toBeGreaterThanOrEqual(30_000);diff --git a/apps/worker/src/import-retry.ts b/apps/worker/src/import-retry.tsindex 296547a4..bf8bbdd7 100644--- a/apps/worker/src/import-retry.ts+++ b/apps/worker/src/import-retry.ts@@ -9,13 +9,24 @@ export const MAX_ATTEMPTS = 10;const RATE_LIMITED = 'rate limited';export type TickErrorOutcome =- { action: 'retry'; delayMs: number; lastError: string } | { action: 'fail'; lastError: string };+ | { action: 'retry'; delayMs: number; lastError: string; countsAsAttempt: boolean }+ | { action: 'fail'; lastError: string };export function tickErrorOutcome(error: unknown, attempts: number): TickErrorOutcome {if (error instanceof SourceRateLimitedError) {- return { action: 'retry', delayMs: error.retryAfterMs, lastError: RATE_LIMITED };+ return {+ action: 'retry',+ delayMs: error.retryAfterMs,+ lastError: RATE_LIMITED,+ countsAsAttempt: false,+ };}const message = error instanceof Error ? error.message : String(error);if (attempts >= MAX_ATTEMPTS) return { action: 'fail', lastError: message };- return { action: 'retry', delayMs: equalJitterBackoffMs(attempts), lastError: message };+ return {+ action: 'retry',+ delayMs: equalJitterBackoffMs(attempts),+ lastError: message,+ countsAsAttempt: true,+ };}diff --git a/apps/worker/src/import-store.ts b/apps/worker/src/import-store.tsindex 15748a94..966a145f 100644--- a/apps/worker/src/import-store.ts+++ b/apps/worker/src/import-store.ts@@ -177,16 +177,19 @@ export async function failImportJob(jobId: number, error: string): Promise<void>}// A transient failure (rate limited, a network error, an unreachable-// instance): reschedule rather than fail the job outright.+// instance): reschedule rather than fail the job outright. A tick that does not+// count as an attempt (a rate limit) gives back the bump its claim made.export async function retryImportJobLater(jobId: number,delayMs: number,error: string,+ countsAsAttempt: boolean,): Promise<void> {const delaySeconds = Math.max(1, Math.ceil(delayMs / 1000));await db.update(importJob).set({+ ...(countsAsAttempt ? {} : { attempts: sql`greatest(${importJob.attempts} - 1, 0)` }),nextAttemptAt: sql`now() + make_interval(secs => ${delaySeconds})`,lastError: error.slice(0, 500),updatedAt: new Date(),diff --git a/apps/worker/src/import-worker.ts b/apps/worker/src/import-worker.tsindex 0337fb4a..ed457779 100644--- a/apps/worker/src/import-worker.ts+++ b/apps/worker/src/import-worker.ts@@ -91,7 +91,7 @@ async function handleTickError(job: ClaimedImportJob, error: unknown): Promise<vawait failImportJob(job.id, outcome.lastError);return;}- await retryImportJobLater(job.id, outcome.delayMs, outcome.lastError);+ await retryImportJobLater(job.id, outcome.delayMs, outcome.lastError, outcome.countsAsAttempt);}function buildReader(job: ClaimedImportJob): SourceReader {diff --git a/apps/worker/src/reader.ts b/apps/worker/src/reader.tsindex 10635731..5ebe6652 100644--- a/apps/worker/src/reader.ts+++ b/apps/worker/src/reader.ts@@ -9,8 +9,8 @@ import type {} from './canonical';// Thrown by a source adapter when the source's rate limit is reached. The worker-// reschedules the job after retryAfterMs: a rate limit is waited out and never-// fails the job by itself.+// reschedules the job after retryAfterMs; a rate limit is waited out and does not+// count toward the attempt limit.export class SourceRateLimitedError extends Error {constructor(public readonly retryAfterMs: number,diff --git a/docs/dev/plane-import.md b/docs/dev/plane-import.mdindex 7726f834..2ca77879 100644--- a/docs/dev/plane-import.md+++ b/docs/dev/plane-import.md@@ -164,10 +164,11 @@ attachment) are a distinct path, not covered by this — see "Inline images" in`rateLimitBackoffMs` (`plane-adapter.ts`) reads `x-ratelimit-remaining`/`x-ratelimit-reset`/a 429 off every response; hitting the limit throws `SourceRateLimitedError` (`reader.ts`).`tickErrorOutcome` (`import-retry.ts`) only decides what a failed tick does — for a rate-limit, retry after the reset with `last_error` `'rate limited'` — and `handleTickError`-(`import-worker.ts`) reschedules the job via `retryImportJobLater`, so a rate limit is waited-out and never fails the job by itself. `import_job.last_error` is cleared the moment a claim-starts a new attempt, as well as on success and on completion (`import-store.ts`'s+limit, retry after the reset with `last_error` `'rate limited'`, not counted as an attempt —+and `handleTickError` (`import-worker.ts`) reschedules the job via `retryImportJobLater`,+which gives back the claim's `attempts` bump, so a rate limit never counts toward+`MAX_ATTEMPTS`. `import_job.last_error` is cleared the moment a claim starts a new attempt, as+well as on success and on completion (`import-store.ts`'s`claimDueImportJobs`/`saveImportJobCursor`/`advanceImportJobPhase`/`completeImportJob`), so anon-null `lastError` on a still-`pending` job reliably means "currently waiting out a retry,"never "an attempt is in flight" — which is what the Settings page's warning banner reads.