Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat(secret-value-tracking): add the backfill run state

Calvin3349d20f81a2
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index 5b295b7bfe..4cb28cf4d8 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -179,6 +179,10 @@ export const KeyStorePrefixes = {
// UUIDs and the endpoint segments do not overlap, so one prefix serves both without collision.
InsightsCache: (scopeId: string, endpoint: string) => `insights-cache:${scopeId}:${endpoint}` as const,
+ // Holds a secret value tracking backfill's transient state. Completion is the durable flag on the
+ // organization, so nothing here needs to outlive the run.
+ SecretValueTrackingBackfill: (scopeId: string) => `secret-value-tracking-backfill:${scopeId}` as const,
+
// Braces are a Redis Cluster hash tag: the index zset and every member's payload key must land on
// one slot for the multi-key upsert/delete scripts.
WorkerHeartbeatIndex: (workerType: string) => `worker-heartbeat:{${workerType}}` as const,
@@ -248,6 +252,7 @@ export const KeyStoreTtls = {
EmailDispatchCooldownInSeconds: 60, // 1 minute
EmailDispatchMailboxWindowInSeconds: 86400, // 24 hours
EmailDispatchAbuseProbeInSeconds: 7200, // 2 hours
+ SecretValueTrackingBackfillInSeconds: 172800, // 2 days, long enough to resume a run someone retries the next day
InsightsCacheInSeconds: 300, // 5 minutes
InsightsDuplicationCacheInSeconds: 3600, // 1 hour
InsightsWeeklyHistoryCacheInSeconds: 86400, // 24 hours
diff --git a/backend/src/services/secret-value-tracking/secret-value-tracking-fns.test.ts b/backend/src/services/secret-value-tracking/secret-value-tracking-fns.test.ts
index 3b2e4d588c..5d503bee62 100644
--- a/backend/src/services/secret-value-tracking/secret-value-tracking-fns.test.ts
+++ b/backend/src/services/secret-value-tracking/secret-value-tracking-fns.test.ts
@@ -1,4 +1,7 @@
-import { advanceCursor, needsBackfill } from "./secret-value-tracking-fns";
+import { JobState } from "@app/queue/queue-service";
+
+import { advanceCursor, needsBackfill, resolveRunStatus } from "./secret-value-tracking-fns";
+import { TBackfillRunState } from "./secret-value-tracking-types";
const PROJECTS = ["p1", "p2"];
const FOLDERS = { p1: ["f1", "f2"], p2: ["f3"] };
@@ -149,3 +152,56 @@ describe("needsBackfill", () => {
);
});
});
+
+const NOW = new Date("2026-09-24T12:00:00.000Z");
+const minutesAgo = (n: number) => new Date(NOW.getTime() - n * 60_000).toISOString();
+
+const running = (lastProgressAt: string): TBackfillRunState => ({
+ status: "running",
+ cursor: null,
+ projectsTotal: 3,
+ projectsDone: 1,
+ secretsProcessed: 10,
+ lastProgressAt
+});
+
+describe("resolveRunStatus", () => {
+ test("the flag being set means completed, whatever the key says", () => {
+ expect(resolveRunStatus(running(minutesAgo(1)), true, NOW)).toEqual({ status: JobState.Completed });
+ });
+
+ test("no key and no flag means the backfill was never run", () => {
+ expect(resolveRunStatus(null, false, NOW)).toEqual({ status: JobState.NotFound });
+ });
+
+ test("a run that progressed recently is pending", () => {
+ expect(resolveRunStatus(running(minutesAgo(1)), false, NOW)).toEqual({ status: JobState.Pending });
+ });
+
+ test("a recorded failure reports its error", () => {
+ expect(
+ resolveRunStatus({ ...running(minutesAgo(1)), status: "failed", error: "kms unavailable" }, false, NOW)
+ ).toEqual({ status: JobState.Failed, message: "kms unavailable" });
+ });
+
+ test("a run with no progress for longer than the window is stalled", () => {
+ const result = resolveRunStatus(running(minutesAgo(30)), false, NOW);
+ expect(result.status).toBe(JobState.Failed);
+ expect(result.message).toMatch(/stopped responding/i);
+ });
+
+ // The boundary must be decisive rather than flapping between running and stalled.
+ test("exactly at the staleness boundary the run still counts as pending", () => {
+ expect(resolveRunStatus(running(minutesAgo(15)), false, NOW)).toEqual({ status: JobState.Pending });
+ });
+
+ test("one second past the boundary the run is stalled", () => {
+ const justPast = new Date(NOW.getTime() - (15 * 60_000 + 1000)).toISOString();
+ expect(resolveRunStatus(running(justPast), false, NOW).status).toBe(JobState.Failed);
+ });
+
+ // An unreadable timestamp must not throw into the status endpoint.
+ test("an unparseable lastProgressAt reads as stalled rather than throwing", () => {
+ expect(resolveRunStatus({ ...running(""), lastProgressAt: "not-a-date" }, false, NOW).status).toBe(JobState.Failed);
+ });
+});
diff --git a/backend/src/services/secret-value-tracking/secret-value-tracking-fns.ts b/backend/src/services/secret-value-tracking/secret-value-tracking-fns.ts
index c3d7aab93e..446840c609 100644
--- a/backend/src/services/secret-value-tracking/secret-value-tracking-fns.ts
+++ b/backend/src/services/secret-value-tracking/secret-value-tracking-fns.ts
@@ -1,4 +1,13 @@
-import { TAdvanceCursorInput, TAdvanceCursorResult, TBackfillCursor } from "./secret-value-tracking-types";
+import { JobState } from "@app/queue/queue-service";
+
+import {
+ TAdvanceCursorInput,
+ TAdvanceCursorResult,
+ TBackfillCursor,
+ TBackfillRunState
+} from "./secret-value-tracking-types";
+
+export const BACKFILL_STALE_AFTER_MS = 15 * 60 * 1000;
const startOfFolder = (projectId: string, folderId: string): TBackfillCursor => ({
projectId,
@@ -81,3 +90,25 @@ export const needsBackfill = (row: {
secretValueOrgBlindIndex?: string | null;
encryptedValue?: Buffer | null;
}) => Boolean(row.encryptedValue) && (!row.secretValueBlindIndex || !row.secretValueOrgBlindIndex);
+
+// Completion lives on the durable flag rather than in the run state, so a key that outlives a
+// finished run can never contradict it.
+export const resolveRunStatus = (
+ state: TBackfillRunState | null,
+ flagEnabled: boolean,
+ now: Date
+): { status: JobState; message?: string } => {
+ if (flagEnabled) return { status: JobState.Completed };
+ if (!state) return { status: JobState.NotFound };
+ if (state.status === "failed") return { status: JobState.Failed, message: state.error ?? "Unknown error" };
+
+ const lastProgress = new Date(state.lastProgressAt).getTime();
+ if (Number.isNaN(lastProgress) || now.getTime() - lastProgress > BACKFILL_STALE_AFTER_MS) {
+ return {
+ status: JobState.Failed,
+ message: "The backfill stopped responding. Start it again to resume from where it left off."
+ };
+ }
+
+ return { status: JobState.Pending };
+};
diff --git a/backend/src/services/secret-value-tracking/secret-value-tracking-state.ts b/backend/src/services/secret-value-tracking/secret-value-tracking-state.ts
new file mode 100644
index 0000000000..1ddf04242c
--- /dev/null
+++ b/backend/src/services/secret-value-tracking/secret-value-tracking-state.ts
@@ -0,0 +1,87 @@
+import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";
+import { logger } from "@app/lib/logger";
+
+import { BACKFILL_STALE_AFTER_MS } from "./secret-value-tracking-fns";
+import { TBackfillRunState } from "./secret-value-tracking-types";
+
+type TSecretValueTrackingStateFactoryDep = {
+ keyStore: Pick<TKeyStoreFactory, "getItemPrimary" | "setItemWithExpiry" | "setItemWithExpiryNX" | "deleteItem">;
+};
+
+export const secretValueTrackingStateFactory = ({ keyStore }: TSecretValueTrackingStateFactoryDep) => {
+ // Reads the primary rather than a replica: a chunk writes its cursor immediately before queueing
+ // its successor, so a replica read can hand the next chunk the cursor it already worked through.
+ const read = async (scopeId: string): Promise<TBackfillRunState | null> => {
+ const raw = await keyStore.getItemPrimary(KeyStorePrefixes.SecretValueTrackingBackfill(scopeId));
+ if (!raw) return null;
+
+ try {
+ const parsed = JSON.parse(raw) as TBackfillRunState;
+ // An unreadable key means no run in progress, which the status endpoint can answer, rather
+ // than an exception it cannot.
+ if (typeof parsed?.lastProgressAt !== "string" || typeof parsed?.status !== "string") return null;
+ return parsed;
+ } catch (error) {
+ logger.warn(error, `Secret value tracking backfill state unreadable [scopeId=${scopeId}]`);
+ return null;
+ }
+ };
+
+ const write = async (scopeId: string, state: TBackfillRunState) => {
+ await keyStore.setItemWithExpiry(
+ KeyStorePrefixes.SecretValueTrackingBackfill(scopeId),
+ KeyStoreTtls.SecretValueTrackingBackfillInSeconds,
+ JSON.stringify(state)
+ );
+ };
+
+ const clear = async (scopeId: string) => {
+ await keyStore.deleteItem(KeyStorePrefixes.SecretValueTrackingBackfill(scopeId));
+ };
+
+ const isStalled = (state: TBackfillRunState) => {
+ if (state.status === "failed") return true;
+ const lastProgress = new Date(state.lastProgressAt).getTime();
+ return Number.isNaN(lastProgress) || Date.now() - lastProgress > BACKFILL_STALE_AFTER_MS;
+ };
+
+ // Taking over a stalled run keeps its cursor, so retrying a backfill that died hours ago resumes
+ // instead of walking the whole scope again.
+ const claim = async (scopeId: string, projectsTotal: number) => {
+ const fresh: TBackfillRunState = {
+ status: "running",
+ cursor: null,
+ projectsTotal,
+ projectsDone: 0,
+ secretsProcessed: 0,
+ lastProgressAt: new Date().toISOString()
+ };
+
+ const claimed = await keyStore.setItemWithExpiryNX(
+ KeyStorePrefixes.SecretValueTrackingBackfill(scopeId),
+ KeyStoreTtls.SecretValueTrackingBackfillInSeconds,
+ JSON.stringify(fresh)
+ );
+ if (claimed) return true;
+
+ const existing = await read(scopeId);
+ if (!existing) {
+ await write(scopeId, fresh);
+ return true;
+ }
+
+ if (!isStalled(existing)) return false;
+
+ await write(scopeId, {
+ ...fresh,
+ cursor: existing.cursor,
+ projectsDone: existing.projectsDone,
+ secretsProcessed: existing.secretsProcessed
+ });
+ return true;
+ };
+
+ return { read, write, clear, claim };
+};
+
+export type TSecretValueTrackingStateFactory = ReturnType<typeof secretValueTrackingStateFactory>;