Skip to content

Commit 529c3f9

Browse files
committed
improvement(redis): address review threads and simplify the leftovers of the fallback removal
1 parent bf26737 commit 529c3f9

57 files changed

Lines changed: 615 additions & 482 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ contracts, and demonstrated regressions.
3434
| Suffix | Needs | Run with | In CI |
3535
|--------|-------|----------|-------|
3636
| `*.test.ts(x)` | nothing; global mocks from `vitest.setup.ts` | `bun run --cwd <workspace> test` | `test` jobs |
37-
| `*.integration.ts` | real PostgreSQL (`TEST_DATABASE_URL`), Redis (`TEST_REDIS_URL`, required) | `bun run --cwd <workspace> test --mode integration` | `integration` jobs, by glob (sharded per provisioning path) |
37+
| `*.integration.ts` | real PostgreSQL (`TEST_DATABASE_URL`) and Redis (`TEST_REDIS_URL`: required by `apps/sim` and `apps/realtime`; `packages/db` runs without it locally and requires it in CI) | `bun run --cwd <workspace> test --mode integration` | `integration` jobs, by glob (sharded per provisioning path) |
3838
| `*.live.test.ts` | provider APIs, hosted sandboxes, local runtimes, or sibling checkouts | `bun run --cwd apps/sim test --mode live <file>` | never |
3939
| `apps/desktop/e2e/*.spec.ts` | the packaged Electron app | Playwright | desktop E2E workflow |
4040
| `apps/sim/scripts/test-*-e2e.ts` | a running app over HTTP | its `package.json` script when one exists (`bun run test:scim:e2e`; `test:workflow-version-compare:e2e` adds `--no-env-file`), else `bun scripts/test-<suite>-e2e.ts` from apps/sim | `e2e` jobs (`.github/scripts/http-e2e.sh`) |

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ contracts, and demonstrated regressions.
3131
| Suffix | Needs | Run with | In CI |
3232
|--------|-------|----------|-------|
3333
| `*.test.ts(x)` | nothing; global mocks from `vitest.setup.ts` | `bun run --cwd <workspace> test` | `test` jobs |
34-
| `*.integration.ts` | real PostgreSQL (`TEST_DATABASE_URL`), Redis (`TEST_REDIS_URL`, required) | `bun run --cwd <workspace> test --mode integration` | `integration` jobs, by glob (sharded per provisioning path) |
34+
| `*.integration.ts` | real PostgreSQL (`TEST_DATABASE_URL`) and Redis (`TEST_REDIS_URL`: required by `apps/sim` and `apps/realtime`; `packages/db` runs without it locally and requires it in CI) | `bun run --cwd <workspace> test --mode integration` | `integration` jobs, by glob (sharded per provisioning path) |
3535
| `*.live.test.ts` | provider APIs, hosted sandboxes, local runtimes, or sibling checkouts | `bun run --cwd apps/sim test --mode live <file>` | never |
3636
| `apps/desktop/e2e/*.spec.ts` | the packaged Electron app | Playwright | desktop E2E workflow |
3737
| `apps/sim/scripts/test-*-e2e.ts` | a running app over HTTP | its `package.json` script when one exists (`bun run test:scim:e2e`; `test:workflow-version-compare:e2e` adds `--no-env-file`), else `bun scripts/test-<suite>-e2e.ts` from apps/sim | `e2e` jobs (`.github/scripts/http-e2e.sh`) |

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

Lines changed: 60 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ vi.mock('redis', async () => {
88
})
99

1010
import { FileDocStore, REDIS_AGENT_ORIGIN, REDIS_ORIGIN } from '@/handlers/file-doc-store'
11-
import { createBacking, fakeRedis } from '@/handlers/fixtures/redis.fixture'
11+
import { type Backing, createBacking, fakeRedis } from '@/handlers/fixtures/redis.fixture'
1212

1313
const REDIS_URL = 'redis://fake'
1414
const NAME = 'workspace-file-doc:file-1'
@@ -69,9 +69,15 @@ function seedFor(text: string): Uint8Array {
6969

7070
let stores: FileDocStore[] = []
7171

72+
/** The in-memory Redis behind every fake client; each test starts a fresh one. */
73+
function currentBacking(): Backing {
74+
if (!fakeRedis.backing) throw new Error('backing not initialized')
75+
return fakeRedis.backing
76+
}
77+
7278
/** An existing stream from a relay predating generation markers; modern seeds use seedIfEmpty. */
7379
function seedLegacyStream(update = updateFor('')): void {
74-
const backing = fakeRedis.backing!
80+
const backing = currentBacking()
7581
backing.streams.set(`filedoc:stream:${NAME}`, [
7682
{ id: `${++backing.seq}-0`, message: { u: Buffer.from(update).toString('base64') } },
7783
])
@@ -160,19 +166,19 @@ describe('FileDocStore', () => {
160166
const store = await newStore()
161167
const doc = new Y.Doc()
162168
await store.attachRoom(NAME, doc)
163-
fakeRedis.backing!.readerClosed = true
169+
currentBacking().readerClosed = true
164170

165-
fakeRedis.backing!.connects = 0 // ignore the two `init` connects; count only recovery attempts
166-
const before = fakeRedis.backing!.reads
171+
currentBacking().connects = 0 // ignore the two `init` connects; count only recovery attempts
172+
const before = currentBacking().reads
167173
await vi.advanceTimersByTimeAsync(3000)
168-
const attempts = fakeRedis.backing!.reads - before
174+
const attempts = currentBacking().reads - before
169175

170176
// A fixed 500ms retry manages 6 attempts in this window; backing off (500 → 1s → 2s → …)
171177
// manages about 3. The ±20% jitter moves the exact count, so assert that it slowed down.
172178
expect(attempts).toBeGreaterThan(0)
173179
expect(attempts).toBeLessThanOrEqual(4)
174180
// …and it tried to bring the connection back rather than leaving the tailer dead forever.
175-
expect(fakeRedis.backing!.connects).toBeGreaterThan(0)
181+
expect(currentBacking().connects).toBeGreaterThan(0)
176182
doc.destroy()
177183
} finally {
178184
vi.useRealTimers()
@@ -183,7 +189,7 @@ describe('FileDocStore', () => {
183189
const store = new FileDocStore(REDIS_URL)
184190
stores.push(store)
185191
await Promise.all([store.init(), store.init(), store.init()])
186-
expect(fakeRedis.backing!.connects).toBe(2)
192+
expect(currentBacking().connects).toBe(2)
187193
})
188194

189195
/**
@@ -199,8 +205,8 @@ describe('FileDocStore', () => {
199205
await store.init()
200206
await store.attachRoom(NAME, doc)
201207
await vi.advanceTimersByTimeAsync(1000)
202-
expect(fakeRedis.backing!.idleReads).toBeGreaterThan(0)
203-
expect(fakeRedis.backing!.maxInFlightReads).toBe(1)
208+
expect(currentBacking().idleReads).toBeGreaterThan(0)
209+
expect(currentBacking().maxInFlightReads).toBe(1)
204210
} finally {
205211
doc.destroy()
206212
vi.useRealTimers()
@@ -263,7 +269,7 @@ describe('FileDocStore', () => {
263269
userId: 'editor',
264270
connectionId: 'socket-editor',
265271
})
266-
fakeRedis.backing!.streams.delete(`filedoc:stream:${NAME}`)
272+
currentBacking().streams.delete(`filedoc:stream:${NAME}`)
267273

268274
await expect(store.publishAndWait(NAME, delta, generation)).rejects.toThrow('replaced')
269275
await expect(
@@ -278,29 +284,29 @@ describe('FileDocStore', () => {
278284
connectionId: 'socket-editor',
279285
})
280286
).rejects.toThrow('replaced')
281-
expect(fakeRedis.backing!.streams.has(`filedoc:stream:${NAME}`)).toBe(false)
287+
expect(currentBacking().streams.has(`filedoc:stream:${NAME}`)).toBe(false)
282288
})
283289

284290
it('rejects a shared replay if the document generation changes between pages', async () => {
285291
const store = await newStore()
286292
await store.seedIfEmpty(NAME, seedFor('old generation'), 10)
287-
fakeRedis.backing!.onRange = () => {
288-
fakeRedis.backing!.kv.set(`filedoc:generation:${NAME}`, 'new generation')
293+
currentBacking().onRange = () => {
294+
currentBacking().kv.set(`filedoc:generation:${NAME}`, 'new generation')
289295
}
290296
await expect(store.getStreamState(NAME)).rejects.toThrow('replaced')
291297
})
292298

293299
it('fails safely when an uncompacted stream exceeds the replay entry budget', async () => {
294300
const streamKey = `filedoc:stream:${NAME}`
295301
const noop = Buffer.from(updateFor('')).toString('base64')
296-
fakeRedis.backing!.streams.set(
302+
currentBacking().streams.set(
297303
streamKey,
298304
Array.from({ length: 2_001 }, (_, index) => ({
299305
id: `${index + 1}-0`,
300306
message: { u: noop },
301307
}))
302308
)
303-
fakeRedis.backing!.seq = 2_001
309+
currentBacking().seq = 2_001
304310
const store = await newStore()
305311

306312
await expect(store.getStreamState(NAME)).rejects.toThrow('replay exceeded its safety limit')
@@ -309,14 +315,14 @@ describe('FileDocStore', () => {
309315
it('never exposes a partially replayed document when room attachment exceeds its budget', async () => {
310316
const streamKey = `filedoc:stream:${NAME}`
311317
const noop = Buffer.from(updateFor('')).toString('base64')
312-
fakeRedis.backing!.streams.set(
318+
currentBacking().streams.set(
313319
streamKey,
314320
Array.from({ length: 2_001 }, (_, index) => ({
315321
id: `${index + 1}-0`,
316322
message: { u: noop },
317323
}))
318324
)
319-
fakeRedis.backing!.seq = 2_001
325+
currentBacking().seq = 2_001
320326
const store = await newStore()
321327
const doc = new Y.Doc()
322328

@@ -330,24 +336,24 @@ describe('FileDocStore', () => {
330336
it('recovers from compaction that trims unread pages during replay', async () => {
331337
const streamKey = `filedoc:stream:${NAME}`
332338
const noop = Buffer.from(updateFor('')).toString('base64')
333-
fakeRedis.backing!.streams.set(
339+
currentBacking().streams.set(
334340
streamKey,
335341
Array.from({ length: 8 }, (_, index) => ({
336342
id: `${index + 1}-0`,
337343
message: { u: noop },
338344
}))
339345
)
340-
fakeRedis.backing!.seq = 8
341-
fakeRedis.backing!.onRange = (call, key) => {
346+
currentBacking().seq = 8
347+
currentBacking().onRange = (call, key) => {
342348
if (call !== 2 || key !== streamKey) return
343-
fakeRedis.backing!.streams.set(streamKey, [
349+
currentBacking().streams.set(streamKey, [
344350
{
345351
id: '9-0',
346352
message: { u: Buffer.from(updateFor('compacted')).toString('base64'), s: '1' },
347353
},
348354
])
349-
fakeRedis.backing!.seq = 9
350-
fakeRedis.backing!.onRange = undefined
355+
currentBacking().seq = 9
356+
currentBacking().onRange = undefined
351357
}
352358
const store = await newStore()
353359

@@ -370,16 +376,16 @@ describe('FileDocStore', () => {
370376
for (let i = 1; i <= 8; i++)
371377
source.getText('body').insert(source.getText('body').length, String(i))
372378
const snapshot = Y.encodeStateAsUpdate(source)
373-
fakeRedis.backing!.streams.set(streamKey, entries.slice())
379+
currentBacking().streams.set(streamKey, entries.slice())
374380
for (let i = 9; i <= 11; i++)
375381
source.getText('body').insert(source.getText('body').length, String(i))
376-
fakeRedis.backing!.onRange = (_call, key, start) => {
382+
currentBacking().onRange = (_call, key, start) => {
377383
if (key !== streamKey || start !== '(4-0') return
378-
fakeRedis.backing!.streams.set(streamKey, [
384+
currentBacking().streams.set(streamKey, [
379385
...entries.slice(7),
380386
{ id: '12-0', message: { u: Buffer.from(snapshot).toString('base64'), s: '1' } },
381387
])
382-
fakeRedis.backing!.onRange = undefined
388+
currentBacking().onRange = undefined
383389
}
384390
const store = await newStore()
385391
const recovered = new Y.Doc()
@@ -411,8 +417,8 @@ describe('FileDocStore', () => {
411417
}))
412418
entries.push({ id: '401-0', message: { u: Buffer.from(peerUpdates[0]).toString('base64') } })
413419
entries.push({ id: '402-0', message: { u: Buffer.from(peerUpdates[1]).toString('base64') } })
414-
fakeRedis.backing!.streams.set(streamKey, entries)
415-
fakeRedis.backing!.seq = 402
420+
currentBacking().streams.set(streamKey, entries)
421+
currentBacking().seq = 402
416422

417423
const a = await newStore()
418424
// This task has integrated only up to entry 400 (all no-ops) — its local doc is empty and lags the
@@ -438,7 +444,7 @@ describe('FileDocStore', () => {
438444

439445
// The appended snapshot entry must carry the snapshot marker, so a fresh catch-up task treats it as
440446
// edited content (not a bare seed) and persists on last-disconnect.
441-
const stream = fakeRedis.backing!.streams.get(streamKey)!
447+
const stream = currentBacking().streams.get(streamKey)!
442448
expect(stream[stream.length - 1].message.s).toBe('1')
443449
})
444450

@@ -461,7 +467,7 @@ describe('FileDocStore', () => {
461467
// the peer tailer applies it as REDIS_AGENT_ORIGIN — excluded from the relay's edited/persist gate.
462468
a.publish(NAME, updateFor('agent frame'), true)
463469
await vi.waitFor(() => expect(origins).toContain(REDIS_AGENT_ORIGIN), { timeout: 2000 })
464-
const stream = fakeRedis.backing!.streams.get(streamKey)!
470+
const stream = currentBacking().streams.get(streamKey)!
465471
expect(stream.some((e) => e.message.a === '1')).toBe(true)
466472
// The normal edit's entry carries no agent marker.
467473
expect(stream.filter((e) => e.message.a === '1')).toHaveLength(1)
@@ -499,7 +505,7 @@ describe('FileDocStore', () => {
499505
}
500506

501507
await vi.waitFor(() => {
502-
const stream = fakeRedis.backing!.streams.get(`filedoc:stream:${NAME}`)!
508+
const stream = currentBacking().streams.get(`filedoc:stream:${NAME}`)!
503509
expect(stream.length).toBeLessThan(400)
504510
expect(stream.some((entry) => entry.message.c === '1')).toBe(true)
505511
})
@@ -515,7 +521,7 @@ describe('FileDocStore', () => {
515521
it('retries a transient append failure so the edit is not lost from the shared log', async () => {
516522
seedLegacyStream()
517523
const a = await newStore()
518-
fakeRedis.backing!.failXAdd = 2 // first two xAdd attempts throw; the third must succeed
524+
currentBacking().failXAdd = 2 // first two xAdd attempts throw; the third must succeed
519525
a.publish(NAME, updateFor('resilient'))
520526
await vi.waitFor(
521527
async () => {
@@ -542,7 +548,7 @@ describe('FileDocStore', () => {
542548
connectionId: 'socket-editor',
543549
})
544550

545-
expect(fakeRedis.backing!.streams.get(`filedoc:stream:${NAME}`)).toHaveLength(2)
551+
expect(currentBacking().streams.get(`filedoc:stream:${NAME}`)).toHaveLength(2)
546552
})
547553

548554
it('does not drop different payloads that reuse an acknowledged update id', async () => {
@@ -558,7 +564,7 @@ describe('FileDocStore', () => {
558564
connectionId: 'socket-editor',
559565
})
560566

561-
expect(fakeRedis.backing!.streams.get(`filedoc:stream:${NAME}`)).toHaveLength(3)
567+
expect(currentBacking().streams.get(`filedoc:stream:${NAME}`)).toHaveLength(3)
562568
})
563569

564570
it('preserves the inclusive barrier and delta bytes observed during compaction', async () => {
@@ -570,7 +576,7 @@ describe('FileDocStore', () => {
570576
room.uncompactedDeltaBytes = 12 * 1024 * 1024
571577
const retainedBarrierBytes = room.lastDeltaBytes
572578
const lateUpdate = updateFor('concurrent edit')
573-
fakeRedis.backing!.onSnapshot = async () => {
579+
currentBacking().onSnapshot = async () => {
574580
await store.publishAndWait(NAME, lateUpdate)
575581
await store.catchUp(NAME)
576582
}
@@ -588,7 +594,7 @@ describe('FileDocStore', () => {
588594
const replacer = await newStore()
589595
const oldDoc = docWithText('old')
590596
oldDoc.getMap('config').set('docId', 'old-generation')
591-
fakeRedis.backing!.nextIds = ['1000-0', '1000-1', '1000-2']
597+
currentBacking().nextIds = ['1000-0', '1000-1', '1000-2']
592598
await store.seedIfEmpty(NAME, Y.encodeStateAsUpdate(oldDoc), 10)
593599
await store.publishAndWait(NAME, updateFor('first edit'), 'old-generation')
594600
await store.publishAndWait(NAME, updateFor('second edit'), 'old-generation')
@@ -602,31 +608,33 @@ describe('FileDocStore', () => {
602608
freshDoc.getText('body').insert(5, ' accepted edit')
603609
const freshEdit = Y.encodeStateAsUpdate(freshDoc, beforeEdit)
604610
const streamKey = `filedoc:stream:${NAME}`
605-
fakeRedis.backing!.nextIds = ['1000-3', '1000-0', '1000-1']
606-
fakeRedis.backing!.onSnapshot = async () => {
611+
currentBacking().nextIds = ['1000-3', '1000-0', '1000-1']
612+
currentBacking().onSnapshot = async () => {
607613
await replacer.invalidateDocument(NAME, 20)
608614
await replacer.seedIfEmpty(NAME, freshSeed, 20)
609615
await replacer.publishClientUpdateAndWait(NAME, 'fresh-edit', freshEdit, 'new-generation', {
610616
userId: 'editor',
611617
connectionId: 'socket-editor',
612618
})
613-
expect(fakeRedis.backing!.streams.get(streamKey)?.map((entry) => entry.id)).toEqual([
614-
'1000-0',
615-
'1000-1',
616-
])
619+
expect(
620+
currentBacking()
621+
.streams.get(streamKey)
622+
?.map((entry) => entry.id)
623+
).toEqual(['1000-0', '1000-1'])
617624
}
618625

619626
await storeInternals(store).maybeCompact(NAME)
620627

621-
expect(fakeRedis.backing!.streams.get(streamKey)?.map((entry) => entry.id)).toEqual([
622-
'1000-0',
623-
'1000-1',
624-
])
628+
expect(
629+
currentBacking()
630+
.streams.get(streamKey)
631+
?.map((entry) => entry.id)
632+
).toEqual(['1000-0', '1000-1'])
625633
await replacer.publishClientUpdateAndWait(NAME, 'fresh-edit', freshEdit, 'new-generation', {
626634
userId: 'editor',
627635
connectionId: 'socket-editor',
628636
})
629-
expect(fakeRedis.backing!.streams.get(streamKey)).toHaveLength(2)
637+
expect(currentBacking().streams.get(streamKey)).toHaveLength(2)
630638
const persisted = await replacer.getStreamState(NAME)
631639
expect(persisted).not.toBeNull()
632640
const replayed = new Y.Doc()
@@ -682,7 +690,7 @@ describe('FileDocStore', () => {
682690
const tokenA = await a.shouldSeed(NAME)
683691
expect(tokenA).toBeTruthy()
684692
// Simulate A's lock expiring mid-seed so B also wins the freed lock over a still-empty stream.
685-
fakeRedis.backing!.kv.delete(`filedoc:seedlock:${NAME}`)
693+
currentBacking().kv.delete(`filedoc:seedlock:${NAME}`)
686694
const tokenB = await b.shouldSeed(NAME)
687695
expect(tokenB).toBeTruthy()
688696
// Both tasks now race to seed with distinct client ids.
@@ -742,8 +750,8 @@ describe('FileDocStore', () => {
742750
}))
743751
entries.push({ id: '401-0', message: { u: Buffer.from(peerUpdates[0]).toString('base64') } })
744752
entries.push({ id: '402-0', message: { u: Buffer.from(peerUpdates[1]).toString('base64') } })
745-
fakeRedis.backing!.streams.set(streamKey, entries)
746-
fakeRedis.backing!.seq = 402
753+
currentBacking().streams.set(streamKey, entries)
754+
currentBacking().seq = 402
747755

748756
// Two tasks whose local docs lag at DIFFERENT points (400 and 401): both cross the threshold and
749757
// compact concurrently. Each must only trim what its own snapshot subsumes, so the union of both

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -709,8 +709,8 @@ async function runServerSeed(
709709
const store = getFileDocStore()
710710
const deadline = Date.now() + FILE_DOC_TIMEOUTS.seedRequestMs
711711
while (fileDocRooms.get(name) === room && !isDocSeeded(room.doc)) {
712-
// Exactly one task across the cluster builds the seed; the others receive it via the stream (the
713-
// fix for split-brain seeding).
712+
// Exactly one task across the cluster builds the seed (no split-brain); the others receive it
713+
// via the stream.
714714
const token = await store.shouldSeed(name)
715715
if (token) {
716716
await seedUnderLock(name, room, token, actor)

‎apps/realtime/src/index.ts‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,13 +44,10 @@ async function main() {
4444
let httpHandler: ReturnType<typeof createHttpHandler> | undefined
4545
httpServer.on('request', (req, res) => httpHandler?.(req, res))
4646

47-
// Create Socket.IO server with the Redis adapter for cross-pod broadcasting
4847
const io = await createSocketIOServer(httpServer)
4948

50-
// Initialize the Redis-backed room manager
5149
const roomManager = await createRoomManager(io)
5250

53-
// Initialize the shared Yjs backend for collaborative file docs (Redis Streams).
5451
await initFileDocStore(env.REDIS_URL)
5552
registerFileDocPresenceRelay(io)
5653

‎apps/sim/.env.example‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ DATABASE_URL="postgresql://postgres:your_password@localhost:5432/simstudio"
88
# Redis (Required) - rate limiting, OTPs, pub/sub, and realtime coordination. The app refuses to start without it.
99
# Local default: `docker run -d -p 127.0.0.1:6379:6379 redis:7-alpine` (or let `npx sim-setup` manage one).
1010
REDIS_URL=redis://localhost:6379
11-
# REDIS_TLS_SERVERNAME= # Required only for a rediss:// URL that targets a bare IP address (TLS hostname verification)
11+
# REDIS_TLS_SERVERNAME= # Required only for a rediss:// URL that targets a bare IPv4 address (TLS hostname verification)
1212

1313
# Authentication (Required unless DISABLE_AUTH=true)
1414
BETTER_AUTH_SECRET=your_secret_key # Use `openssl rand -hex 32` to generate, or visit https://www.better-auth.com/docs/installation

‎apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/cancel/route.test.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,6 @@ describe('POST /api/v2/workflows/[workflowId]/runs/[runId]/cancel', () => {
106106
new WorkflowRunAlreadyTerminalError({
107107
executionId: RUN_ID,
108108
executionStatus,
109-
redisAvailable: true,
110109
locallyAborted: false,
111110
})
112111
)

0 commit comments

Comments
 (0)