Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
5a4deba
fix(mcp): name the reason on the workflow MCP serve route's malformed…
waleedlatif1 Nov 28, 2026
e460b2f
fix(neo4j): connect TLS sessions to the validated address (#10481)
waleedlatif1 Nov 28, 2026
7f5e81c
feat(library): Make.com Pricing: Credits, Plans, and When AI Agents C…
waleedlatif1 Nov 28, 2026
ab6b5c1
feat(library): Which AI Agent Platforms Do Teams Actually Use in Prod…
waleedlatif1 Nov 28, 2026
dd56f17
docs(library): update crewai-vs-langgraph-vs-autogen (#10486)
waleedlatif1 Nov 28, 2026
57085b9
docs(library): update best-vellum-alternatives-2026 (#10487)
waleedlatif1 Nov 28, 2026
a677c4f
feat(library): Gumloop Pricing: Plans, Credits, and Costs for Scaling…
waleedlatif1 Nov 28, 2026
d5206f0
feat(library): LangChain vs LlamaIndex: Which Is Better for Productio…
waleedlatif1 Nov 28, 2026
55de486
feat(library): Microsoft Power Automate Pricing: Costs for IT and Aut…
waleedlatif1 Nov 28, 2026
2d2e434
docs(library): update langchain-vs-langgraph (#10491)
waleedlatif1 Nov 28, 2026
3ba16d1
fix(mcp): answer 400 when MCP OAuth URL is refused by egress policy (…
waleedlatif1 Nov 28, 2026
a14df32
fix(neo4j): keep the TLS relay's error handling for its whole lifetim…
waleedlatif1 Nov 28, 2026
e24dcc5
fix(realtime): cap batch operation frames and persist positions in on…
waleedlatif1 Nov 28, 2026
93b7597
fix(chat): stop email OTP verification from revealing the allow-list …
waleedlatif1 Nov 28, 2026
09b16ff
fix(realtime): disconnect sockets whose session has ended (#10496)
waleedlatif1 Nov 28, 2026
84873a3
improvement(comparisons): answer-first Sim vs Make page with a worked…
waleedlatif1 Nov 28, 2026
6a5cdee
fix(tables): re-check access on the open table event stream (#10494)
waleedlatif1 Nov 28, 2026
5d500f8
fix(media): cap ffmpeg output size while writing, not after (#10500)
waleedlatif1 Nov 28, 2026
9a198d0
fix(realtime): cap batch-add-blocks per message and per workflow (#10…
waleedlatif1 Nov 28, 2026
4e67e08
fix(executor): never expand env placeholders carried by run data (#10…
waleedlatif1 Nov 28, 2026
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
80 changes: 78 additions & 2 deletions apps/realtime/src/access-revalidation.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { db } from '@sim/db'
import { session } from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { ROOM_MEMBERSHIP_ACTIONS, satisfiesRoomMembership } from '@sim/platform-authz/room-policy'
import type { AccessRevokedBroadcast } from '@sim/realtime-protocol/events'
Expand All @@ -9,7 +11,8 @@ import {
type RoomType,
roomName,
} from '@sim/realtime-protocol/rooms'
import { sleep } from '@sim/utils/helpers'
import { chunkArray, sleep } from '@sim/utils/helpers'
import { and, gt, inArray } from 'drizzle-orm'
import {
evictSocketFromRoom,
runRoomEvictionHandler,
Expand Down Expand Up @@ -73,6 +76,23 @@ const SCAN_PASS_BUDGET_MS = 20_000

const SCAN_TIMED_OUT = Symbol('scan-timed-out')

/** Keeps each session-liveness query's `IN` list well below Postgres' bind-parameter limit. */
const SESSION_LOOKUP_BATCH_SIZE = 1_000

/** Returns the subset of `sessionIds` that still name an unexpired session row. */
async function findLiveSessionIds(sessionIds: string[]): Promise<Set<string>> {
const live = new Set<string>()
const now = new Date()
for (const batch of chunkArray(sessionIds, SESSION_LOOKUP_BATCH_SIZE)) {
const rows = await db
.select({ id: session.id })
.from(session)
.where(and(inArray(session.id, batch), gt(session.expiresAt, now)))
for (const row of rows) live.add(row.id)
}
return live
}

export interface AccessRevalidationSweep {
/** Stop the periodic sweep (clears the interval). */
stop: () => void
Expand Down Expand Up @@ -125,7 +145,9 @@ function collectScanTargets(io: IRoomManager['io']): ScanTarget[] {
* no longer satisfies the room, closing the gap left by the join-only access
* check. Without it, a member removed or downgraded mid-session keeps live
* collaborative access (including durable document writes) for the whole lifetime
* of an already-open socket.
* of an already-open socket. Each pass first disconnects sockets whose Better Auth
* session has ended (signed out, revoked, or expired), since the handshake is the
* only other place the credential is checked.
*
* Blip-safety: eviction fires *only* when {@link resolveCurrentRoomPermission}
* resolves to a permission that does not satisfy the room's membership level,
Expand Down Expand Up @@ -290,7 +312,61 @@ export function startAccessRevalidationSweep(roomManager: IRoomManager): AccessR
}
}

/** Set while a session lookup is outstanding, so a timed-out query is never stacked with another. */
let sessionLookupRunning = false

/**
* Disconnects every socket whose handshake session no longer exists or has
* expired. Like the permission scan, only a successful query result acts: a
* failed or timed-out lookup leaves every socket connected until the next pass.
*/
async function disconnectEndedSessions(): Promise<void> {
if (sessionLookupRunning) {
logger.warn('Skipping session liveness check; previous lookup still running')
return
}
const sockets = [...io.sockets.sockets.values()].filter(
(socket): socket is AuthenticatedSocket & { sessionId: string } =>
Boolean((socket as AuthenticatedSocket).sessionId)
)
if (sockets.length === 0) return

sessionLookupRunning = true
const lookup = findLiveSessionIds([...new Set(sockets.map((socket) => socket.sessionId))])
lookup
.catch(() => {})
.finally(() => {
sessionLookupRunning = false
})

let live: Set<string> | typeof SCAN_TIMED_OUT
try {
live = await Promise.race([
lookup,
sleep(SCAN_SOCKET_TIMEOUT_MS).then((): typeof SCAN_TIMED_OUT => SCAN_TIMED_OUT),
])
} catch (error) {
logger.warn('Session liveness check failed; leaving sockets connected', error)
return
}
if (live === SCAN_TIMED_OUT) {
logger.warn('Session liveness check timed out; leaving sockets connected')
return
}

for (const socket of sockets) {
if (live.has(socket.sessionId)) continue
logger.info('Disconnecting socket whose session ended', {
socketId: socket.id,
userId: socket.userId,
})
socket.disconnect(true)
}
}

async function scanMemberships(): Promise<void> {
await disconnectEndedSessions()

const targets = collectScanTargets(io)
if (targets.length === 0) return

Expand Down
187 changes: 187 additions & 0 deletions apps/realtime/src/database/batch-add-cap.integration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
/** Real PostgreSQL coverage: a realtime batch add never grows a workflow past the shared block cap, nor leaves subflow rows without their block. */
import { mkdir, writeFile } from 'node:fs/promises'
import { dirname, resolve } from 'node:path'
import { db } from '@sim/db'
import {
user,
workflow,
workflowBlocks,
workflowEdges,
workflowSubflows,
workspace,
} from '@sim/db/schema'
import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures'
import { BLOCKS_OPERATIONS, OPERATION_TARGETS } from '@sim/realtime-protocol/constants'
import { WorkflowOperationSchema } from '@sim/realtime-protocol/schemas'
import { getErrorMessage } from '@sim/utils/errors'
import { generateId } from '@sim/utils/id'
import { MAX_WORKFLOW_BLOCKS, MAX_WORKFLOW_EDGES } from '@sim/workflow-types/workflow'
import { count, eq } from 'drizzle-orm'
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'
import { persistWorkflowOperation } from '@/database/operations'

const userId = generateId()
const workspaceId = generateId()
const workflowId = generateId()
const existingIds = Array.from({ length: MAX_WORKFLOW_BLOCKS - 1 }, () => generateId())
const checks: { name: string; status: 'passed' | 'failed'; durationMs: number; error?: string }[] =
[]

/** Registers a test and records its status and duration in the suite report. */
function check(name: string, run: () => Promise<void>) {
it(name, async () => {
const started = performance.now()
try {
await run()
checks.push({ name, status: 'passed', durationMs: performance.now() - started })
} catch (error) {
checks.push({
name,
status: 'failed',
durationMs: performance.now() - started,
error: getErrorMessage(error),
})
throw error
}
})
}

function payloadBlock(id: string) {
return { id, type: 'function', name: id, position: { x: 0, y: 0 }, subBlocks: {} }
}

function batchAdd(payload: Record<string, unknown>) {
return {
operation: BLOCKS_OPERATIONS.BATCH_ADD_BLOCKS,
target: OPERATION_TARGETS.BLOCKS,
payload,
timestamp: Date.now(),
}
}

function persist(payload: Record<string, unknown>) {
return persistWorkflowOperation(workflowId, { ...batchAdd(payload), userId })
}

async function countRows(
table: typeof workflowBlocks | typeof workflowEdges | typeof workflowSubflows
) {
const [row] = await db.select({ n: count() }).from(table).where(eq(table.workflowId, workflowId))
return row.n
}

describe('realtime batch-add block cap against PostgreSQL', () => {
beforeAll(async () => {
const now = new Date()
await db.insert(user).values({
id: userId,
name: 'Cap fixture',
email: `${userId}@batch-add-cap.test`,
emailVerified: true,
createdAt: now,
updatedAt: now,
})
await insertWorkspaceFixture(db, {
id: workspaceId,
name: 'Cap target',
ownerId: userId,
billedAccountUserId: userId,
})
await db.insert(workflow).values({
id: workflowId,
userId,
workspaceId,
name: 'Nearly full',
lastSynced: now,
createdAt: now,
updatedAt: now,
})
})

beforeEach(async () => {
await db.delete(workflowSubflows).where(eq(workflowSubflows.workflowId, workflowId))
await db.delete(workflowEdges).where(eq(workflowEdges.workflowId, workflowId))
await db.delete(workflowBlocks).where(eq(workflowBlocks.workflowId, workflowId))
await db.insert(workflowBlocks).values(
existingIds.map((id) => ({
id,
workflowId,
type: 'function',
name: id,
positionX: '0',
positionY: '0',
}))
)
})

afterAll(async () => {
const reportPath =
process.env.REALTIME_BATCH_ADD_CAP_REPORT_PATH ??
resolve('test-results/realtime-batch-add-cap.json')
await mkdir(dirname(reportPath), { recursive: true })
await writeFile(reportPath, JSON.stringify({ checks }, null, 2))
await deleteWorkspaceFixture(db, eq(workspace.ownerId, userId))
await db.delete(user).where(eq(user.id, userId))
})

check('a single message over the cap fails protocol validation', async () => {
const blocks = Array.from({ length: MAX_WORKFLOW_BLOCKS + 1 }, () => payloadBlock(generateId()))
const edges = Array.from({ length: MAX_WORKFLOW_EDGES + 1 }, () => ({
id: generateId(),
source: 'a',
target: 'b',
}))
const loops = Object.fromEntries(blocks.map((block) => [block.id, {}]))

expect(WorkflowOperationSchema.safeParse(batchAdd({ blocks })).success).toBe(false)
expect(WorkflowOperationSchema.safeParse(batchAdd({ blocks: [], edges })).success).toBe(false)
expect(WorkflowOperationSchema.safeParse(batchAdd({ blocks: [], loops })).success).toBe(false)
expect(
WorkflowOperationSchema.safeParse(batchAdd({ blocks: blocks.slice(1), edges: [] })).success
).toBe(true)
})

check('a batch that would push the workflow past the cap writes nothing', async () => {
const [first, second] = [generateId(), generateId()]
const result = await persist({
blocks: [payloadBlock(first), payloadBlock(second)],
edges: [{ id: generateId(), source: first, target: second }],
})

expect(result).toEqual({ reconcile: true })
expect(await countRows(workflowBlocks)).toBe(MAX_WORKFLOW_BLOCKS - 1)
expect(await countRows(workflowEdges)).toBe(0)
})

check('re-sent existing blocks do not count toward the cap', async () => {
const added = generateId()
const result = await persist({
blocks: [...existingIds.slice(0, 10).map(payloadBlock), payloadBlock(added)],
})

expect(result).toEqual({ reconcile: false })
expect(await countRows(workflowBlocks)).toBe(MAX_WORKFLOW_BLOCKS)
})

check('loop and parallel configs land only for a stored or added block', async () => {
const loopId = generateId()
const orphan = await persist({
blocks: [],
loops: { [generateId()]: { nodes: [] } },
parallels: { [generateId()]: { nodes: [] } },
})
expect(orphan).toEqual({ reconcile: true })
expect(await countRows(workflowSubflows)).toBe(0)

const added = await persist({
blocks: [{ ...payloadBlock(loopId), type: 'loop' }],
loops: { [loopId]: { nodes: [], iterations: 4, loopType: 'for' } },
})
expect(added).toEqual({ reconcile: false })
expect(await countRows(workflowSubflows)).toBe(1)

const existing = await persist({ blocks: [], loops: { [existingIds[0]]: { nodes: [] } } })
expect(existing).toEqual({ reconcile: false })
expect(await countRows(workflowSubflows)).toBe(2)
})
})
Loading
Loading