Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- Made the default home page configurable with `DEFAULT_HOME_VIEW_PAGE`, defaulting to Code Search and supporting Ask. [#1677](https://github.com/sourcebot-dev/sourcebot/pull/1677)
- Require authentication for the streaming and blocking Ask APIs in Public SaaS deployments. [#1679](https://github.com/sourcebot-dev/sourcebot/pull/1679)
- Bounded BullMQ job retention to keep Redis memory from growing with repo count, retaining only the latest job per repo, connection, and account. [#1693](https://github.com/sourcebot-dev/sourcebot/pull/1693)
Comment thread
brendan-kellam marked this conversation as resolved.
Resolved

## [5.1.14] - 2026-09-17

Expand Down
9 changes: 6 additions & 3 deletions packages/backend/src/connectionSyncWorkload.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,12 @@ vi.mock("@sourcebot/shared", () => ({
jobOptions: {
attempts: 2,
backoff: { type: "exponential", delayMs: 5000 },
keepJobs: {
completed: { count: 50 },
failed: { count: 50 },
retention: {
mode: "window",
Comment thread
brendan-kellam marked this conversation as resolved.
Resolved
keepJobs: {
completed: { count: 50 },
failed: { count: 50 },
},
},
keepLogs: 500,
},
Expand Down
57 changes: 54 additions & 3 deletions packages/backend/src/jobManager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ const mocks = vi.hoisted(() => {
upsertJobScheduler: vi.fn(),
getJobSchedulerIds: vi.fn(),
removeJobScheduler: vi.fn(),
trackLatestJob: vi.fn(async () => null),
producerClose: vi.fn(),
workerClose: vi.fn(),
executionLockUsing: vi.fn(),
Expand Down Expand Up @@ -54,6 +55,7 @@ vi.mock("@sourcebot/shared", () => ({
upsertJobScheduler = mocks.upsertJobScheduler;
getJobSchedulerIds = mocks.getJobSchedulerIds;
removeJobScheduler = mocks.removeJobScheduler;
trackLatestJob = mocks.trackLatestJob;
close = mocks.producerClose;
getQueue = vi.fn(() => ({
getJobCounts: vi.fn(),
Expand Down Expand Up @@ -113,9 +115,12 @@ const createWorkload = (
jobOptions: {
attempts: 2,
backoff: { type: "exponential", delayMs: 5000 },
keepJobs: {
completed: { count: 50 },
failed: { count: 50 },
retention: {
mode: "window",
Comment thread
brendan-kellam marked this conversation as resolved.
Resolved
keepJobs: {
completed: { count: 50 },
failed: { count: 50 },
},
},
keepLogs: 500,
},
Expand Down Expand Up @@ -297,6 +302,52 @@ describe("BullMQJobManager lifecycle", () => {
});
});

test("tracks the latest job for its resource after onStarted and before processing", async () => {
const calls: string[] = [];
mocks.trackLatestJob.mockImplementation(async () => {
calls.push("tracked");
return "job-0";
});
const workload = createWorkload({
onStarted: vi.fn(async () => {
calls.push("started");
}),
process: vi.fn(async () => {
calls.push("processed");
return { outcome: "SUCCESS" };
}),
});
const manager = new BullMQJobManager({} as Redis);
manager.register(workload);
await manager.start();

await mocks.workers[0].processor({ ...job, attemptsMade: 0 });

expect(calls).toEqual(["started", "tracked", "processed"]);
expect(mocks.trackLatestJob).toHaveBeenCalledWith(
workload.queueSpec,
data,
"job-1",
);
});

test("still processes the job when tracking the latest job fails", async () => {
mocks.trackLatestJob.mockRejectedValue(new Error("redis unavailable"));
Comment thread
brendan-kellam marked this conversation as resolved.
Resolved
const workload = createWorkload();
const manager = new BullMQJobManager({} as Redis);
manager.register(workload);
await manager.start();

await expect(
mocks.workers[0].processor({ ...job, attemptsMade: 0 }),
).resolves.toEqual({ outcome: "SUCCESS" });
expect(workload.process).toHaveBeenCalledTimes(1);
expect(mocks.logger.warn).toHaveBeenCalledWith(
expect.stringContaining("Failed to track latest job"),
expect.any(Error),
);
});

test("runs onStarted and processing while the execution lock is held", async () => {
const calls: string[] = [];
const workloadSignal = new AbortController().signal;
Expand Down
31 changes: 31 additions & 0 deletions packages/backend/src/jobManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
DataOf,
JobEnqueueOptions,
QueueName,
QueueSpec,
ResultOf,
Schedule,
scheduleToMs,
Expand Down Expand Up @@ -150,6 +151,9 @@ export class BullMQJobManager implements JobManager {

const process = async (signal: AbortSignal) => {
await workload.onStarted?.(lifecycleContext);
// After onStarted so the parent's `latest...JobId` pointer has
// moved to this job before its predecessor is removed.
await this.trackLatestJob(spec, job);
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Comment thread
brendan-kellam marked this conversation as resolved.
Resolved
return workload.process({
...lifecycleContext,
signal,
Expand Down Expand Up @@ -257,6 +261,33 @@ export class BullMQJobManager implements JobManager {
}
}

private async trackLatestJob<TName extends QueueName>(
spec: QueueSpec<TName>,
job: Job,
): Promise<void> {
if (!job.id) {
return;
}
try {
const removedJobId = await this.bullmqClient.trackLatestJob(
spec,
job.data,
job.id,
);
if (removedJobId) {
logger.debug(
`Removed job ${removedJobId} superseded by ${job.id} on "${spec.name}"`,
);
}
} catch (error) {
// Retention is best-effort; the age backstop still bounds the queue.
logger.warn(
`Failed to track latest job ${job.id} on "${spec.name}"`,
error,
);
}
}

private getWorkload<TName extends QueueName>(
workloadName: TName,
): Workload<TName> {
Expand Down
96 changes: 89 additions & 7 deletions packages/shared/src/bullmqClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ const mocks = vi.hoisted(() => ({
{ key: "scheduler-2" },
]),
removeJobScheduler: vi.fn(async () => true),
removeJob: vi.fn(async () => undefined),
multiExec: vi.fn(async () => [[null, null], [null, "OK"]]),
multiSet: vi.fn(),
}));

vi.mock("bullmq", () => ({
Expand All @@ -32,7 +35,23 @@ vi.mock("./jobLogger.js", () => ({
}));

import { BullMQClient } from "./bullmqClient.js";
import { CONNECTION_QUEUE, type QueueSpec } from "./queue.js";
import {
ATTACHMENT_PRUNE_QUEUE,
CONNECTION_QUEUE,
type QueueSpec,
} from "./queue.js";

const createRedis = () => {
const multi = {
get: vi.fn(() => multi),
set: vi.fn((...args: unknown[]) => {
mocks.multiSet(...args);
return multi;
}),
exec: mocks.multiExec,
};
return { multi: vi.fn(() => multi) } as unknown as Redis;
};

describe("BullMQClient", () => {
beforeEach(() => {
Expand Down Expand Up @@ -202,14 +221,77 @@ describe("BullMQClient", () => {
delay: 30_000,
jitter: 0.5,
},
removeOnComplete: { age: 1_209_600 },
removeOnFail: { age: 1_209_600 },
removeOnComplete: { age: 604_800 },
removeOnFail: { age: 604_800 },
keepLogs: 500,
},
}),
);
});

describe("trackLatestJob", () => {
test("records the new job and removes the one it supersedes", async () => {
mocks.multiExec.mockResolvedValue([[null, "job-1"], [null, "OK"]]);
mocks.getJob.mockResolvedValue({ id: "job-1", remove: mocks.removeJob });
const client = new BullMQClient(createRedis());

await expect(
client.trackLatestJob(CONNECTION_QUEUE, { connectionId: 42 }, "job-2"),
).resolves.toBe("job-1");

expect(mocks.multiSet).toHaveBeenCalledWith(
"sourcebot:latest-job:connection-sync:connection:42",
"job-2",
"EX",
604_800,
);
expect(mocks.getJob).toHaveBeenCalledWith("job-1");
expect(mocks.removeJob).toHaveBeenCalledTimes(1);
});

test("keeps the record when there is no previous job", async () => {
mocks.multiExec.mockResolvedValue([[null, null], [null, "OK"]]);
const client = new BullMQClient(createRedis());

await expect(
client.trackLatestJob(CONNECTION_QUEUE, { connectionId: 42 }, "job-2"),
).resolves.toBeNull();
expect(mocks.getJob).not.toHaveBeenCalled();
});

test("does not remove the job on a retry of the same job", async () => {
mocks.multiExec.mockResolvedValue([[null, "job-2"], [null, "OK"]]);
const client = new BullMQClient(createRedis());

await expect(
client.trackLatestJob(CONNECTION_QUEUE, { connectionId: 42 }, "job-2"),
).resolves.toBeNull();
expect(mocks.getJob).not.toHaveBeenCalled();
expect(mocks.removeJob).not.toHaveBeenCalled();
});

test("leaves a superseded job that cannot be removed to the age backstop", async () => {
mocks.multiExec.mockResolvedValue([[null, "job-1"], [null, "OK"]]);
mocks.removeJob.mockRejectedValueOnce(new Error("Job job-1 is locked"));
Comment thread
brendan-kellam marked this conversation as resolved.
Resolved
mocks.getJob.mockResolvedValue({ id: "job-1", remove: mocks.removeJob });
const client = new BullMQClient(createRedis());

await expect(
client.trackLatestJob(CONNECTION_QUEUE, { connectionId: 42 }, "job-2"),
).resolves.toBeNull();
});

test("is a no-op for queues with window retention", async () => {
const redis = createRedis();
const client = new BullMQClient(redis);

await expect(
client.trackLatestJob(ATTACHMENT_PRUNE_QUEUE, {}, "job-2"),
).resolves.toBeNull();
expect(redis.multi).not.toHaveBeenCalled();
});
});

test("adds enqueue priority to immediate jobs", async () => {
const client = new BullMQClient({} as Redis);

Expand Down Expand Up @@ -309,8 +391,8 @@ describe("BullMQClient", () => {
delay: 30_000,
jitter: 0.5,
},
removeOnComplete: { age: 1_209_600 },
removeOnFail: { age: 1_209_600 },
removeOnComplete: { age: 604_800 },
removeOnFail: { age: 604_800 },
keepLogs: 500,
},
},
Expand Down Expand Up @@ -346,8 +428,8 @@ describe("BullMQClient", () => {
delay: 30_000,
jitter: 0.5,
},
removeOnComplete: { age: 1_209_600 },
removeOnFail: { age: 1_209_600 },
removeOnComplete: { age: 604_800 },
removeOnFail: { age: 604_800 },
keepLogs: 500,
},
},
Expand Down
Loading
Loading