Skip to content

Commit 0d48835

Browse files
committed
fix(redis): resolve rate-limit storage lazily and address review findings
1 parent 5288a0e commit 0d48835

34 files changed

Lines changed: 479 additions & 88 deletions

File tree

‎.claude/rules/sim-testing.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,10 @@ contracts, and demonstrated regressions.
4646
`vi.mock` in the file.
4747
- `TEST_DATABASE_URL` must be loopback and its database name must contain a `test` segment
4848
(`sim_test`); `TEST_REDIS_URL` must be loopback. `packages/db/testing/test-infrastructure.ts` owns
49-
those checks. Isolate with a unique schema or generated IDs, and clean up in `afterAll`.
49+
those checks. `apps/sim` integration setup runs `FLUSHDB` before every file, so its
50+
`TEST_REDIS_URL` must also select a non-zero database (`redis://127.0.0.1:6379/15`); never
51+
point it at a Redis holding data you want to keep. Isolate with a unique schema or generated
52+
IDs, and clean up in `afterAll`.
5053
- Integration files run one at a time against one shared database. A new `*.integration.ts` is
5154
picked up by CI with no workflow change, and the run writes the JSON report configured in
5255
`vitest.shared.ts`, which CI uploads. Never exclude a failing suite from the run in

‎.cursor/rules/sim-testing.mdc‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,10 @@ contracts, and demonstrated regressions.
4343
`vi.mock` in the file.
4444
- `TEST_DATABASE_URL` must be loopback and its database name must contain a `test` segment
4545
(`sim_test`); `TEST_REDIS_URL` must be loopback. `packages/db/testing/test-infrastructure.ts` owns
46-
those checks. Isolate with a unique schema or generated IDs, and clean up in `afterAll`.
46+
those checks. `apps/sim` integration setup runs `FLUSHDB` before every file, so its
47+
`TEST_REDIS_URL` must also select a non-zero database (`redis://127.0.0.1:6379/15`); never
48+
point it at a Redis holding data you want to keep. Isolate with a unique schema or generated
49+
IDs, and clean up in `afterAll`.
4750
- Integration files run one at a time against one shared database. A new `*.integration.ts` is
4851
picked up by CI with no workflow change, and the run writes the JSON report configured in
4952
`vitest.shared.ts`, which CI uploads. Never exclude a failing suite from the run in

‎.github/workflows/checks.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ jobs:
122122
--health-retries 10
123123
env:
124124
TEST_DATABASE_URL: postgresql://postgres:postgres@127.0.0.1:5432/sim_test
125-
TEST_REDIS_URL: redis://127.0.0.1:6379
125+
TEST_REDIS_URL: redis://127.0.0.1:6379/15
126126
DATABASE_URL: postgresql://postgres:postgres@127.0.0.1:5432/sim_test
127127
BETTER_AUTH_SECRET: oauth-postgres-ci-secret-at-least-32-characters
128128
NEXT_PUBLIC_APP_URL: https://test.sim.ai

‎apps/docs/content/docs/platform/self-hosting/redis.mdx‎

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,30 @@ There are no PostgreSQL or in-memory fallbacks: each of these runs only on Redis
2222
| Execution progress markers | Event buffers and progress for running executions |
2323
| Distributed execution limits | Per-deployment concurrency and provider admission limits |
2424
| CLI pairing-code approval store | API-key login through pairing; OAuth login uses a separate path |
25+
| OAuth flow state | Short-lived state for in-progress OAuth, MCP OAuth, and Slack OAuth connections |
26+
| Pending webhook verifications | Challenge state while a provider verifies a newly registered webhook |
27+
| Distributed locks | Leases that keep a job, schedule, or stream on one replica at a time |
2528
| Collaborative document store (realtime) | Shared state for collaboratively edited documents |
2629

2730
<Callout type="error">
2831
The app checks `REDIS_URL` when it starts and refuses to boot when it is missing or is not a `redis://` or `rediss://` URL. `next build` does not need Redis, so an image builds without it; the running server does not.
2932
</Callout>
3033

31-
Everything Sim keeps in Redis is cache, coordination state, or an in-flight event — never committed data, which lives in PostgreSQL and object storage. Persistence is therefore not required. Losing or restarting the instance is not free, though: cancellation markers and the cross-pod half of execution streaming live here, so active runs stop streaming and a cancellation issued across the gap may not land. Completed work is unaffected.
34+
Everything Sim keeps in Redis is cache, coordination state, or an in-flight event — never committed data, which lives in PostgreSQL and object storage. Persistence is therefore not required. Losing or restarting the instance is not free, though:
35+
36+
- Active runs stop streaming, and a cancellation issued across the gap may not land, because cancellation markers and the cross-pod half of execution streaming live here.
37+
- Pending email OTPs stop working and must be requested again.
38+
- OAuth, MCP OAuth, and Slack OAuth connections in progress fail and must be started again.
39+
- Pending webhook verifications are lost.
40+
- Rate-limit buckets reset.
41+
42+
Completed work is unaffected.
43+
44+
### Eviction policy
45+
46+
Use `maxmemory-policy noeviction`, as the bundled Helm Redis does, and size the instance so it never fills. Alert on memory use well before the limit: with `noeviction`, a full Redis rejects writes instead of silently dropping keys.
47+
48+
Most managed services default to an evicting policy such as `volatile-lru` or `allkeys-lru`. Under memory pressure, `volatile-*` policies evict only keys with a TTL and `allkeys-*` policies evict any key. Either way, the short-lived keys Sim depends on are at risk: OTPs, OAuth state, locks, and rate-limit buckets. An evicted key looks like an expired code, a failed OAuth connection, a duplicated job, or a reset limit. Change the policy in the service's parameter group or configuration.
3249

3350
## Configuration
3451

@@ -45,14 +62,24 @@ Both the app and the realtime service need it and must point at the same instanc
4562

4663
`docker-compose.prod.yml` already includes a `redis:7-alpine` service and wires `REDIS_URL=redis://redis:6379` into both the app and realtime containers. No additional Redis URL is needed for that bundled instance.
4764

65+
That service sets no `maxmemory`, so Redis can grow until the host runs out of memory. Watch its memory use on a long-running host.
66+
4867
The port is deliberately not published to the host, so a Redis already running locally will not collide. Override `REDIS_URL` in `.env` to point at an external instance instead.
4968

5069
</Tab>
5170
<Tab value="Kubernetes (Helm)">
5271

5372
The chart deploys Redis by default, matching the Compose stack. No additional Redis URL is needed for that bundled instance.
5473

55-
For production, prefer a managed instance — disable the bundled one and supply a URL. With `redis.enabled: false`, the chart refuses to render unless `REDIS_URL` comes from `app.env`, a pre-created `app.secrets.existingSecret`, or `externalSecrets.remoteRefs.app.REDIS_URL`:
74+
For production, prefer a managed instance — disable the bundled one and supply a URL. With `redis.enabled: false`, the chart refuses to render unless `REDIS_URL` reaches every enabled app and realtime pod. Accepted sources:
75+
76+
- `app.env.REDIS_URL` or `realtime.env.REDIS_URL`, written into the app Secret that both pods load
77+
- A top-level `extraEnvVars` entry named `REDIS_URL`, such as one with `valueFrom.secretKeyRef`, which is set on both pods
78+
- A pre-created `app.secrets.existingSecret`, which the chart trusts because it cannot read it
79+
- `externalSecrets.remoteRefs.app.REDIS_URL` when External Secrets is enabled
80+
- `app.envDefaults.REDIS_URL` covers only the app pod, and `realtime.envDefaults.REDIS_URL` only the realtime pod, so set both when both are enabled
81+
82+
The simplest form:
5683

5784
```yaml
5885
redis:

‎apps/docs/scripts/fixtures/content-baseline.json‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -174926,14 +174926,19 @@
174926174926
"bytes": 6715,
174927174927
"frontmatter": {
174928174928
"title": "Redis",
174929-
"description": "When Redis is optional, when it is required, and how to configure it"
174929+
"description": "Why Sim requires Redis, what it backs, and how to configure it"
174930174930
},
174931174931
"headings": [
174932174932
{
174933174933
"title": "What it backs",
174934174934
"url": "#what-it-backs",
174935174935
"depth": 2
174936174936
},
174937+
{
174938+
"title": "Eviction policy",
174939+
"url": "#eviction-policy",
174940+
"depth": 3
174941+
},
174937174942
{
174938174943
"title": "Configuration",
174939174944
"url": "#configuration",
@@ -175024,28 +175029,28 @@
175024175029
"meta": null,
175025175030
"sha256": "eb73d81bd9564fdbb8cd1a57ac1eb1bdd906e057d04d5a6414ddbd7b67ff2cc3",
175026175031
"bytes": 103,
175027-
"line": 27
175032+
"line": 52
175028175033
},
175029175034
{
175030175035
"lang": "yaml",
175031175036
"meta": null,
175032175037
"sha256": "59ac0be78ca58845392d8e9d91445a890fad94ebf9659d1ac2a1c0183e04e0c3",
175033175038
"bytes": 97,
175034-
"line": 49
175039+
"line": 84
175035175040
},
175036175041
{
175037175042
"lang": "bash",
175038175043
"meta": null,
175039175044
"sha256": "75128b92e81c8670e89b93d25c8a6f695fc5ba9bf9e84c21b3a7a8dd45357014",
175040175045
"bytes": 116,
175041-
"line": 87
175046+
"line": 122
175042175047
},
175043175048
{
175044175049
"lang": "bash",
175045175050
"meta": null,
175046175051
"sha256": "f81661b02c93f78580f48d5e525a71d31d59cedd7974bcdcfc00588cf2f070aa",
175047175052
"bytes": 312,
175048-
"line": 96
175053+
"line": 131
175049175054
}
175050175055
],
175051175056
"links": [

‎apps/realtime/src/handlers/file-doc-store.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,34 @@ describe('FileDocStore', () => {
179179
}
180180
})
181181

182+
it('opens one pair of connections when init is called concurrently', async () => {
183+
const store = new FileDocStore(REDIS_URL)
184+
stores.push(store)
185+
await Promise.all([store.init(), store.init(), store.init()])
186+
expect(fakeRedis.backing!.connects).toBe(2)
187+
})
188+
189+
/**
190+
* A restart that lands while the previous reader loop is between reads must retire that loop:
191+
* otherwise it resumes on the new connection and two loops tail the same rooms forever.
192+
*/
193+
it('runs a single reader loop after a shutdown and restart', async () => {
194+
vi.useFakeTimers()
195+
const doc = new Y.Doc()
196+
try {
197+
const store = await newStore()
198+
await store.shutdown()
199+
await store.init()
200+
await store.attachRoom(NAME, doc)
201+
await vi.advanceTimersByTimeAsync(1000)
202+
expect(fakeRedis.backing!.idleReads).toBeGreaterThan(0)
203+
expect(fakeRedis.backing!.maxInFlightReads).toBe(1)
204+
} finally {
205+
doc.destroy()
206+
vi.useRealTimers()
207+
}
208+
})
209+
182210
it('elects exactly one seeder across tasks (no split-brain seed)', async () => {
183211
const a = await newStore()
184212
const b = await newStore()

‎apps/realtime/src/handlers/file-doc-store.ts‎

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -362,13 +362,27 @@ export class FileDocStore {
362362
private read: RedisClientType | null = null
363363
private readonly rooms = new Map<string, StoreRoom>()
364364
private running = false
365+
/**
366+
* Bumped on every start, so a reader loop left over from before a restart exits instead of
367+
* running alongside the new one.
368+
*/
369+
private generation = 0
370+
/** The in-flight start, shared by concurrent {@link init} calls so they open one pair of connections. */
371+
private starting: Promise<void> | null = null
365372
private heartbeat: ReturnType<typeof setInterval> | null = null
366373

367374
constructor(private readonly redisUrl: string) {}
368375

369376
/** Connect the two Redis clients and start the multiplexed reader + TTL heartbeat. Idempotent. */
370377
async init(): Promise<void> {
371378
if (this.running) return
379+
this.starting ??= this.start().finally(() => {
380+
this.starting = null
381+
})
382+
return this.starting
383+
}
384+
385+
private async start(): Promise<void> {
372386
const options = {
373387
url: this.redisUrl,
374388
socket: {
@@ -394,7 +408,7 @@ export class FileDocStore {
394408
this.read.on('error', (err) => logger.error('FileDocStore read client error:', err))
395409
await Promise.all([this.write.connect(), this.read.connect()])
396410
this.running = true
397-
void this.runReader()
411+
void this.runReader(++this.generation)
398412
this.heartbeat = setInterval(() => void this.refreshTtls(), HEARTBEAT_MS)
399413
logger.info('FileDocStore ready — shared Yjs backend over Redis Streams enabled')
400414
}
@@ -1089,10 +1103,10 @@ export class FileDocStore {
10891103
* The single multiplexed tail loop: block-read every locally-open room's stream from its last id and
10901104
* apply new entries. One blocking connection for the whole process regardless of open-file count.
10911105
*/
1092-
private async runReader(): Promise<void> {
1106+
private async runReader(generation: number): Promise<void> {
10931107
let failures = 0
10941108
let blockingBatchIndex = 0
1095-
while (this.running && this.read) {
1109+
while (this.running && this.read && generation === this.generation) {
10961110
const snapshot = new Map(this.rooms)
10971111
if (snapshot.size === 0) {
10981112
await sleep(IDLE_POLL_MS)
@@ -1134,7 +1148,7 @@ export class FileDocStore {
11341148
}
11351149
failures = 0
11361150
} catch (error) {
1137-
if (!this.running) break
1151+
if (!this.running || generation !== this.generation) break
11381152
await this.recoverReader(++failures, error)
11391153
}
11401154
}

‎apps/realtime/src/handlers/file-doc.redis-store.test.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -247,12 +247,12 @@ function requestSyncStep2(handlers: Record<string, Handler>): void {
247247
handlers[FILE_DOC_EVENTS.MESSAGE](encoding.toUint8Array(encoder))
248248
}
249249

250-
describe('file-doc join readiness (shared store enabled)', () => {
250+
describe('file-doc join readiness against the shared store', () => {
251251
/** Every socket the test created, so a room emit can be routed to its members. */
252252
const sockets: FakeSocket[] = []
253253

254-
// One store for the whole file: `initFileDocStore` is idempotent once enabled, so a per-test
255-
// shutdown would leave every later test running against a store with closed clients.
254+
// One store for the whole file: `beforeEach` resets the fake backing, so the tests share one
255+
// started store instead of restarting it around every case.
256256
beforeAll(async () => {
257257
await initFileDocStore('redis://fake')
258258
})

‎apps/realtime/src/handlers/fixtures/redis.fixture.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,9 @@ export interface Backing {
7171
failedReadTimes: number[]
7272
/** Reads that returned (the idle steady state) — the event that ends a failure streak. */
7373
idleReads: number
74+
/** Reads currently awaiting a reply, and the most ever in flight at once: one per reader loop. */
75+
inFlightReads: number
76+
maxInFlightReads: number
7477
/** `connect()` calls, so a test can prove a closed reader is re-opened rather than abandoned. */
7578
connects: number
7679
/** Largest stream range response requested, proving replay is paginated. */
@@ -171,7 +174,13 @@ export function makeClient(): TestRedisClient {
171174
b().idleReads++
172175
return res
173176
}
174-
await sleep(5)
177+
b().inFlightReads++
178+
b().maxInFlightReads = Math.max(b().maxInFlightReads, b().inFlightReads)
179+
try {
180+
await sleep(5)
181+
} finally {
182+
b().inFlightReads--
183+
}
175184
b().idleReads++
176185
return null
177186
},
@@ -335,6 +344,8 @@ export function createBacking(): Backing {
335344
reads: 0,
336345
failedReadTimes: [],
337346
idleReads: 0,
347+
inFlightReads: 0,
348+
maxInFlightReads: 0,
338349
connects: 0,
339350
maxRangeCount: 0,
340351
rangeCalls: 0,

‎apps/sim/app/api/copilot/api-keys/validate/route.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -431,7 +431,7 @@ describe('POST /api/copilot/api-keys/validate billing protocols', () => {
431431
expect(mockResolveBillingAttribution).not.toHaveBeenCalled()
432432
})
433433

434-
it('admits a direct-v1 key without Redis while ignoring a local workspace ID', async () => {
434+
it('admits a direct-v1 key against the account payer, ignoring the workspace ID it sends', async () => {
435435
mockSerializeAccountBillingDecisionHeader.mockImplementation((decision: object) =>
436436
encodeURIComponent(JSON.stringify(decision))
437437
)

0 commit comments

Comments
 (0)