Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
44 changes: 34 additions & 10 deletions docs/production-incident-baseline.md
Original file line number Diff line number Diff line change
Expand Up @@ -18351,8 +18351,9 @@ Drizzle schema and runtime Zod schemas. Findings and remediations:

## 2026-07-26 — Worker Deployments Stalled Active BullMQ Jobs

- **Status:** Direct fixes merged after full CI; production deployment remains
pending because the first rollout was superseded during the incident above.
- **Status:** Initial lifecycle fixes merged and deployed; a follow-up provider
admission root cause was confirmed from the fixed-release rollout, with its
direct fix validated locally and pending PR/deployment.
- **Symptoms:** Sentry issues
[DOFEK-SERVER-4N](https://east-bay-software.sentry.io/issues/DOFEK-SERVER-4N)
and
Expand All @@ -18374,15 +18375,30 @@ Drizzle schema and runtime Zod schemas. Findings and remediations:
about 22 minutes, while the old provider-deletion loop could run for more
than two hours. Axiom could not be queried because its connected user token
had expired, so Sentry, Docker task state/logs, and Redis metadata supplied
the causal evidence.
the causal evidence. During the serialized `d627cd8` rollout, the reclaimed
one-day Strava job emitted a new
[DOFEK-SERVER-4N](https://east-bay-software.sentry.io/issues/DOFEK-SERVER-4N)
event at `17:18:17Z`, remained at zero percent, and continued renewing its
lock. PostgreSQL had no active application query. Its persisted adaptive
state contained a `200`-request short limit, usage `1`, and one admitted
request at `17:30:21Z`. A 20-second Redis command trace then showed the same
client repeatedly executing `GET`, `WATCH`, and `GET` for the Strava
admission key about every 4.5 seconds without ever reaching `MULTI`/`EXEC`.
The 4.5-second interval exactly matched
`ceil(15 minutes / (200 - 1))`.
Comment thread
qodo-code-review[bot] marked this conversation as resolved.
Resolved
- **Root cause:** Docker Swarm's default 10-second stop grace was incompatible
with BullMQ's graceful close contract, which waits for active jobs, while
provider HTTP requests had no deadline and provider deletion processed every
checkpoint batch inside one multi-hour job. Docker documents the 10-second
default before `SIGKILL`, and BullMQ documents that `Worker.close()` waits for
active work:
<https://docs.docker.com/reference/compose-file/services/#stop_grace_period>
and <https://docs.bullmq.io/guide/workers/graceful-shutdown>.
and <https://docs.bullmq.io/guide/workers/graceful-shutdown>. The follow-up
Strava hang was caused by `admissionDelayMs()` returning a full quota pacing
interval on every atomic claim recheck instead of the time remaining since
the last request. The delay could therefore never reach zero, so the
`WATCH` claim loop slept and retried forever. The inferred-budget soft-cap
branch had the same fixed-delay defect.
- **Fix / mitigation:** Give the worker a durable 30-minute stop grace and the
initial deploy a 35-minute convergence bound; fail rather than continue when
a Swarm update pauses. Apply a shared two-minute provider HTTP deadline with
Expand All @@ -18392,19 +18408,27 @@ Drizzle schema and runtime Zod schemas. Findings and remediations:
deletion-request state authoritative so a completed batch job cannot report
the overall operation complete while its continuation remains active.
Node.js documents the native timeout and signal-composition primitives:
<https://nodejs.org/api/globals.html#class-abortsignal>.
<https://nodejs.org/api/globals.html#class-abortsignal>. The follow-up fix
makes every admission result a remaining eligibility delay: Strava quota
pacing subtracts elapsed time since `lastRequestMs`, and an exhausted
adaptive budget waits only for the remainder of its rolling window. This is
shared provider admission behavior, with no Strava-job bypass or
incident-only flag.
- **Validation:** The timeout regression failed before implementation. After
the fix, 205 focused unit tests passed, the root TypeScript typecheck and
targeted Biome checks passed, and all five real-ClickHouse provider-deletion
integration cases passed, including multiple continuation batches and
bounded projection reads. A focused operation-status regression also verifies
that a dispatched deletion remains running after its root batch completes.
No stall-count increase, forced retry, temporary flag, or incident-only
shutdown branch was added.
- **Remaining risk / follow-up:** Merge through normal CI, deploy, confirm the
old worker reaches `Shutdown complete` without exit 137, verify the timed-out
Strava job retries and completes, observe no fixed-release 4N/2K events
across a subsequent rollout, then resolve both Sentry issues.
shutdown branch was added. The admission regression failed against the
previous implementation; after the fix, 82 focused package/application tests
pass, including an atomic Redis-store case that advances through the exact
persisted production quota shape.
- **Remaining risk / follow-up:** Merge and deploy the admission fix, verify the
reclaimed Strava job completes and subsequent jobs make bounded progress,
observe no fixed-release 4N/2K events across another rollout, then resolve
both Sentry issues.

## 2026-07-26 — Peloton Workout Response Drift Blocked Sync

Expand Down
154 changes: 136 additions & 18 deletions packages/provider-http/src/adaptive-rate-limit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,14 +138,15 @@ describe("admissionDelayMs", () => {
expect(admissionDelayMs(state, 500)).toBe(600);
});

it("adds delay when the inferred budget soft cap is reached", () => {
it("waits for the remaining adaptive window when the inferred budget soft cap is reached", () => {
const state = {
...createInitialAdaptiveState("garmin", "provider", null, 0),
throttleMs: 1000,
inferredBudget: 10,
requestCount: 8,
};
expect(admissionDelayMs(state, 0)).toBe(1000);
expect(admissionDelayMs(state, 1_000)).toBe(ADAPTIVE_RATE_WINDOW_MS - 1_000);
expect(admissionDelayMs(state, ADAPTIVE_RATE_WINDOW_MS)).toBe(0);
});

it("paces step-chain providers by sync job rather than raw HTTP call count", () => {
Expand All @@ -158,7 +159,7 @@ describe("admissionDelayMs", () => {
expect(admissionDelayMs(state, 0)).toBe(0);

const throttled = { ...state, requestCount: 30 };
expect(admissionDelayMs(throttled, 0)).toBe(1000);
expect(admissionDelayMs(throttled, 0)).toBe(ADAPTIVE_RATE_WINDOW_MS);
});

it("derives throttle delay independently from budget pacing", () => {
Expand All @@ -173,34 +174,151 @@ describe("admissionDelayMs", () => {
expect(admissionDelayMs(state, 1_000)).toBe(1_500);
});

it("returns no throttle delay after the interval has elapsed", () => {
const state = {
...createInitialAdaptiveState("garmin", "provider", null, 0),
throttleMs: 1_000,
lastRequestMs: 100,
};
expect(throttleDelayMs(state, 1_500)).toBe(0);
});

it("paces Strava requests when short quota is nearly exhausted", () => {
const state = applyStravaQuota(createInitialAdaptiveState("strava", "provider", null), {
shortLimit: 100,
shortUsage: 99,
dailyLimit: 1000,
dailyUsage: 100,
});
expect(admissionDelayMs(state, Date.now())).toBeGreaterThanOrEqual(state.throttleMs * 4);
const state = applyStravaQuota(
{
...createInitialAdaptiveState("strava", "provider", null, 0),
lastRequestMs: 0,
},
{
shortLimit: 100,
shortUsage: 99,
dailyLimit: 1000,
dailyUsage: 100,
},
);
expect(admissionDelayMs(state, 0)).toBe(state.throttleMs * 4);
expect(admissionDelayMs(state, state.throttleMs * 4)).toBe(0);
});

it("uses the nearly-exhausted Strava tier when exactly two requests remain", () => {
const state = applyStravaQuota(
{
...createInitialAdaptiveState("strava", "provider", null, 0),
lastRequestMs: 0,
},
{
shortLimit: 100,
shortUsage: 98,
dailyLimit: 1000,
dailyUsage: 100,
},
);
expect(admissionDelayMs(state, 0)).toBe(state.throttleMs * 4);
});

it("doubles Strava pacing delay when only a few short-quota requests remain", () => {
const state = applyStravaQuota(createInitialAdaptiveState("strava", "provider", null), {
shortLimit: 100,
shortUsage: 97,
dailyLimit: 1000,
dailyUsage: 100,
});
const state = applyStravaQuota(
{
...createInitialAdaptiveState("strava", "provider", null, 0),
lastRequestMs: 0,
},
{
shortLimit: 100,
shortUsage: 97,
dailyLimit: 1000,
dailyUsage: 100,
},
);
expect(admissionDelayMs(state, 0)).toBe(state.throttleMs * 2);
expect(admissionDelayMs(state, state.throttleMs * 2)).toBe(0);
});

it("uses the low-headroom Strava tier when exactly five requests remain", () => {
const state = applyStravaQuota(
{
...createInitialAdaptiveState("strava", "provider", null, 0),
lastRequestMs: 0,
},
{
shortLimit: 100,
shortUsage: 95,
dailyLimit: 1000,
dailyUsage: 100,
},
);
expect(admissionDelayMs(state, 0)).toBe(state.throttleMs * 2);
});

it("paces Strava requests proportionally when quota headroom remains", () => {
const state = applyStravaQuota(createInitialAdaptiveState("strava", "provider", null), {
const state = applyStravaQuota(
{
...createInitialAdaptiveState("strava", "provider", null, 0),
lastRequestMs: 0,
},
{
shortLimit: 100,
shortUsage: 50,
dailyLimit: 1000,
dailyUsage: 100,
},
);
expect(admissionDelayMs(state, 0)).toBe(18_000);
expect(admissionDelayMs(state, 17_500)).toBe(500);
expect(admissionDelayMs(state, 18_000)).toBe(0);
});

it("subtracts elapsed time from Strava quota pacing with nonzero timestamps", () => {
const state = applyStravaQuota(
{
...createInitialAdaptiveState("strava", "provider", null, 0),
lastRequestMs: 1_000,
},
{
shortLimit: 100,
shortUsage: 50,
dailyLimit: 1000,
dailyUsage: 100,
},
);
expect(admissionDelayMs(state, 5_000)).toBe(14_000);
});

it("applies the full Strava quota interval when no prior request timestamp exists", () => {
const state = applyStravaQuota(createInitialAdaptiveState("strava", "provider", null, 0), {
shortLimit: 100,
shortUsage: 50,
dailyLimit: 1000,
dailyUsage: 100,
});
expect(admissionDelayMs(state, 0)).toBe(18_000);
expect(admissionDelayMs(state, 5_000)).toBe(18_000);
});

it("requires both Strava short-quota fields before applying quota pacing", () => {
const initial = {
...createInitialAdaptiveState("strava", "provider", null, 0),
lastRequestMs: 0,
throttleMs: 1_000,
};
expect(
admissionDelayMs(
{
...initial,
stravaShortLimit: null,
stravaShortUsage: 99,
},
0,
),
).toBe(initial.throttleMs);
expect(
admissionDelayMs(
{
...initial,
stravaShortLimit: 100,
stravaShortUsage: null,
},
0,
),
).toBe(initial.throttleMs);
});

it("ignores Strava pacing for non-Strava providers", () => {
Expand Down
29 changes: 21 additions & 8 deletions packages/provider-http/src/adaptive-rate-limit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,23 +146,27 @@ export function learnInferredBudget(
}

export function admissionDelayMs(state: ProviderAdaptiveRateState, nowMs: number): number {
let delayMs = Math.max(throttleDelayMs(state, nowMs), budgetAdmissionDelayMs(state));
let delayMs = Math.max(throttleDelayMs(state, nowMs), budgetAdmissionDelayMs(state, nowMs));

if (
state.providerId === "strava" &&
state.stravaShortLimit != null &&
state.stravaShortUsage != null
) {
const remaining = state.stravaShortLimit - state.stravaShortUsage;
let quotaIntervalMs: number;
if (remaining <= 2) {
delayMs = Math.max(delayMs, state.throttleMs * 4);
quotaIntervalMs = state.throttleMs * 4;
} else if (remaining <= 5) {
delayMs = Math.max(delayMs, state.throttleMs * 2);
quotaIntervalMs = state.throttleMs * 2;
} else {
const windowMs = 15 * 60 * 1000;
const pacedDelay = Math.ceil(windowMs / remaining);
delayMs = Math.max(delayMs, Math.min(pacedDelay, ADAPTIVE_THROTTLE_MAX_MS));
quotaIntervalMs = Math.min(Math.ceil(windowMs / remaining), ADAPTIVE_THROTTLE_MAX_MS);
}
delayMs = Math.max(
delayMs,
remainingIntervalDelayMs(state.lastRequestMs, quotaIntervalMs, nowMs),
);
}

return delayMs;
Expand All @@ -171,10 +175,19 @@ export function admissionDelayMs(state: ProviderAdaptiveRateState, nowMs: number
export function throttleDelayMs(state: ProviderAdaptiveRateState, nowMs: number): number {
if (state.lastRequestMs == null) return 0;
const elapsed = nowMs - state.lastRequestMs;
return elapsed < state.throttleMs ? state.throttleMs - elapsed : 0;
return Math.max(0, state.throttleMs - elapsed);
}

function budgetAdmissionDelayMs(state: ProviderAdaptiveRateState): number {
function remainingIntervalDelayMs(
lastRequestMs: number | null,
intervalMs: number,
nowMs: number,
): number {
if (lastRequestMs == null) return intervalMs;
return Math.max(0, intervalMs - Math.max(0, nowMs - lastRequestMs));
}
Comment thread
qodo-code-review[bot] marked this conversation as resolved.
Resolved

function budgetAdmissionDelayMs(state: ProviderAdaptiveRateState, nowMs: number): number {
if (state.inferredBudget == null) return 0;

const softCap = Math.floor(state.inferredBudget * ADAPTIVE_BUDGET_SAFETY_RATIO);
Comment thread
qodo-code-review[bot] marked this conversation as resolved.
Resolved
Expand All @@ -185,7 +198,7 @@ function budgetAdmissionDelayMs(state: ProviderAdaptiveRateState): number {
? Math.max(1, Math.floor(softCap / httpRequestsPerSyncJob(state.providerId)))
: softCap;
if (effectiveRequestCount >= effectiveSoftCap) {
return state.throttleMs;
return Math.max(0, state.windowStartMs + ADAPTIVE_RATE_WINDOW_MS - nowMs);
}

return 0;
Expand Down
27 changes: 27 additions & 0 deletions src/lib/provider-adaptive-rate-limit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -627,6 +627,33 @@ describe("RedisAdaptiveRateLimitStore", () => {
expect(mock.execAttempts).toBe(2);
});

it("completes atomic Strava admission after the quota pacing interval elapses", async () => {
vi.stubEnv("VITEST", "");
vi.stubEnv("NODE_ENV", "production");
vi.useFakeTimers();
vi.setSystemTime(20_000);
const mock = createMockRedisAdaptiveStore({ atomic: true });
mock.values.set(
"provider-adaptive-rate:strava:provider",
JSON.stringify({
...createInitialAdaptiveState("strava", "provider", null, 0),
lastRequestMs: 20_000,
stravaShortLimit: 200,
stravaShortUsage: 1,
stravaDailyLimit: 2_000,
stravaDailyUsage: 38,
}),
);

const admission = mock.store.awaitAdmission("strava", "provider", null);
await vi.advanceTimersByTimeAsync(10_000);
await admission;

expect(mock.execAttempts).toBe(1);
vi.useRealTimers();
vi.unstubAllEnvs();
});

it("creates fresh adaptive state when Redis returns null during atomic admission", async () => {
const mock = createMockRedisAdaptiveStore({ atomic: true });

Expand Down
Loading