Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 3.8k
improvement(tables): versioned CSV snapshot cache for table mounts + parallel multipart uploader#5108
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Uh oh!
There was an error while loading. Please reload this page.
Merged
improvement(tables): versioned CSV snapshot cache for table mounts + parallel multipart uploader #5108
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
03e7545
improvement(tables): versioned CSV snapshot cache for table mounts + …
TheodoreSpeaks 9492470
chore(db): drop colliding 0239 migration (renumber pending)
TheodoreSpeaks e15064f
Merge remote-tracking branch 'origin/staging' into improvement/table-…
TheodoreSpeaks c340659
chore(db): renumber rows_version migration to 0240 (off staging's 0239)
TheodoreSpeaks b4aab21
improvement(tables): mount snapshots by presigned URL so the sandbox …
TheodoreSpeaks f2e6225
fix(tables): allow url sandbox entries in the function-execute contra…
TheodoreSpeaks 9ea1b23
chore(e2b): log sandbox inputs split by url-fetch vs inline write
TheodoreSpeaks bf6ab96
improvement(tables): order export + snapshot rows by order_key so the…
TheodoreSpeaks File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
201 changes: 201 additions & 0 deletions
201 apps/sim/lib/copilot/tools/handlers/function-execute.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,201 @@ | ||
| /** | ||
| * @vitest-environment node | ||
| */ | ||
| import { beforeEach, describe, expect, it, vi } from 'vitest' | ||
| const { | ||
| mockIsFeatureEnabled, | ||
| mockGetTableById, | ||
| mockListTables, | ||
| mockQueryRows, | ||
| mockGetOrCreateTableSnapshot, | ||
| mockDownloadFile, | ||
| mockGeneratePresignedDownloadUrl, | ||
| mockHasCloudStorage, | ||
| mockExecuteTool, | ||
| } = vi.hoisted(() => ({ | ||
| mockIsFeatureEnabled: vi.fn(), | ||
| mockGetTableById: vi.fn(), | ||
| mockListTables: vi.fn(), | ||
| mockQueryRows: vi.fn(), | ||
| mockGetOrCreateTableSnapshot: vi.fn(), | ||
| mockDownloadFile: vi.fn(), | ||
| mockGeneratePresignedDownloadUrl: vi.fn(), | ||
| mockHasCloudStorage: vi.fn(), | ||
| mockExecuteTool: vi.fn(), | ||
| })) | ||
| vi.mock('@/lib/core/config/feature-flags', () => ({ isFeatureEnabled: mockIsFeatureEnabled })) | ||
| vi.mock('@/lib/table/service', () => ({ | ||
| getTableById: mockGetTableById, | ||
| listTables: mockListTables, | ||
| })) | ||
| vi.mock('@/lib/table/rows/service', () => ({ queryRows: mockQueryRows })) | ||
| vi.mock('@/lib/table/snapshot-cache', () => ({ | ||
| getOrCreateTableSnapshot: mockGetOrCreateTableSnapshot, | ||
| SNAPSHOT_MAX_BYTES: 500 * 1024 * 1024, | ||
| })) | ||
| vi.mock('@/lib/uploads/core/storage-service', () => ({ | ||
| downloadFile: mockDownloadFile, | ||
| generatePresignedDownloadUrl: mockGeneratePresignedDownloadUrl, | ||
| hasCloudStorage: mockHasCloudStorage, | ||
| })) | ||
| vi.mock('@/tools', () => ({ executeTool: mockExecuteTool })) | ||
| // Workspace-file + VFS surfaces are unused on the tables-only path; stub to avoid heavy loads. | ||
| vi.mock('@/lib/uploads/contexts/workspace/workspace-file-manager', () => ({ | ||
| fetchWorkspaceFileBuffer: vi.fn(), | ||
| findWorkspaceFileRecord: vi.fn(), | ||
| getSandboxWorkspaceFilePath: vi.fn(), | ||
| listWorkspaceFiles: vi.fn(), | ||
| })) | ||
| vi.mock('@/lib/uploads/contexts/workspace/workspace-file-folder-manager', () => ({ | ||
| listWorkspaceFileFolders: vi.fn(), | ||
| })) | ||
| vi.mock('@/lib/copilot/vfs/path-utils', () => ({ | ||
| decodeVfsPathSegments: (p: string) => p.split('/'), | ||
| encodeVfsPathSegments: (s: string[]) => s.join('/'), | ||
| })) | ||
| vi.mock('@/lib/copilot/vfs/workflow-alias-resolver', () => ({ | ||
| resolveWorkflowAliasForWorkspace: vi.fn().mockResolvedValue(null), | ||
| })) | ||
| vi.mock('@/lib/copilot/vfs/workflow-aliases', () => ({ | ||
| isPlanAliasPath: () => false, | ||
| workflowAliasSandboxPath: (p: string) => p, | ||
| })) | ||
| import { executeFunctionExecute } from '@/lib/copilot/tools/handlers/function-execute' | ||
| const table = { | ||
| id: 'tbl_1', | ||
| workspaceId: 'ws_1', | ||
| rowCount: 1000, | ||
| schema: { columns: [{ id: 'col_name', name: 'name', type: 'string' }] }, | ||
| } | ||
| const context = { workspaceId: 'ws_1', userId: 'u1' } | ||
| function mountedFiles() { | ||
| const params = mockExecuteTool.mock.calls[0][1] as { | ||
| _sandboxFiles?: Array<{ path: string; type?: string; content?: string; url?: string }> | ||
| } | ||
| return params._sandboxFiles ?? [] | ||
| } | ||
| const snapshotCacheOn = (flag: string) => Promise.resolve(flag === 'table-snapshot-cache') | ||
| describe('executeFunctionExecute table mounts', () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks() | ||
| mockExecuteTool.mockResolvedValue({ success: true }) | ||
| mockGetTableById.mockResolvedValue(table) | ||
| mockIsFeatureEnabled.mockResolvedValue(false) | ||
| mockQueryRows.mockResolvedValue({ rows: [{ data: { name: 'Ada' } }] }) | ||
| mockHasCloudStorage.mockReturnValue(true) | ||
| mockGeneratePresignedDownloadUrl.mockResolvedValue('https://s3.example/presigned?sig=abc') | ||
| }) | ||
| it('flag OFF: drains the table inline via queryRows (existing path)', async () => { | ||
| await executeFunctionExecute({ inputTables: ['tbl_1'] }, context as never) | ||
| expect(mockQueryRows).toHaveBeenCalledTimes(1) | ||
| expect(mockGetOrCreateTableSnapshot).not.toHaveBeenCalled() | ||
| const files = mountedFiles() | ||
| expect(files[0].path).toBe('/home/user/tables/tbl_1.csv') | ||
| expect(files[0].content).toBe('name\nAda') | ||
| }) | ||
| it('flag ON + cloud storage: mounts by presigned URL, no bytes through web', async () => { | ||
| mockIsFeatureEnabled.mockImplementation(snapshotCacheOn) | ||
| mockGetOrCreateTableSnapshot.mockResolvedValue({ | ||
| key: 'table-snapshots/ws_1/tbl_1/v5.csv', | ||
| size: 9, | ||
| version: 5, | ||
| }) | ||
| await executeFunctionExecute({ inputTables: ['tbl_1'] }, context as never) | ||
| expect(mockGetOrCreateTableSnapshot).toHaveBeenCalledTimes(1) | ||
| expect(mockQueryRows).not.toHaveBeenCalled() | ||
| expect(mockDownloadFile).not.toHaveBeenCalled() | ||
| expect(mockGeneratePresignedDownloadUrl).toHaveBeenCalledWith( | ||
| 'table-snapshots/ws_1/tbl_1/v5.csv', | ||
| 'execution', | ||
| expect.any(Number) | ||
| ) | ||
| expect(mountedFiles()[0]).toEqual({ | ||
| type: 'url', | ||
| path: '/home/user/tables/tbl_1.csv', | ||
| url: 'https://s3.example/presigned?sig=abc', | ||
| }) | ||
| }) | ||
| it('flag ON + local storage: falls back to a buffered content mount', async () => { | ||
| mockIsFeatureEnabled.mockImplementation(snapshotCacheOn) | ||
| mockHasCloudStorage.mockReturnValue(false) | ||
| mockGetOrCreateTableSnapshot.mockResolvedValue({ | ||
| key: 'table-snapshots/ws_1/tbl_1/v5.csv', | ||
| size: 9, | ||
| version: 5, | ||
| }) | ||
| mockDownloadFile.mockResolvedValue(Buffer.from('name\nAda\n')) | ||
| await executeFunctionExecute({ inputTables: ['tbl_1'] }, context as never) | ||
| expect(mockGeneratePresignedDownloadUrl).not.toHaveBeenCalled() | ||
| expect(mockDownloadFile).toHaveBeenCalledWith( | ||
| expect.objectContaining({ key: 'table-snapshots/ws_1/tbl_1/v5.csv', context: 'execution' }) | ||
| ) | ||
| const file = mountedFiles()[0] | ||
| expect(file.path).toBe('/home/user/tables/tbl_1.csv') | ||
| expect(file.content).toBe('name\nAda\n') | ||
| expect(file.type).toBeUndefined() | ||
| }) | ||
| it('flag ON but small table stays on the inline path', async () => { | ||
| mockIsFeatureEnabled.mockImplementation(snapshotCacheOn) | ||
| mockGetTableById.mockResolvedValue({ ...table, rowCount: 10 }) | ||
| await executeFunctionExecute({ inputTables: ['tbl_1'] }, context as never) | ||
| expect(mockGetOrCreateTableSnapshot).not.toHaveBeenCalled() | ||
| expect(mockQueryRows).toHaveBeenCalledTimes(1) | ||
| }) | ||
| it('flag ON + cloud: throws when the snapshot exceeds the table mount limit', async () => { | ||
| mockIsFeatureEnabled.mockImplementation(snapshotCacheOn) | ||
| mockGetOrCreateTableSnapshot.mockResolvedValue({ | ||
| key: 'table-snapshots/ws_1/tbl_1/v5.csv', | ||
| size: 600 * 1024 * 1024, | ||
| version: 5, | ||
| }) | ||
| await expect( | ||
| executeFunctionExecute({ inputTables: ['tbl_1'] }, context as never) | ||
| ).rejects.toThrow(/table mount limit/) | ||
| expect(mockGeneratePresignedDownloadUrl).not.toHaveBeenCalled() | ||
| }) | ||
| it('flag ON + local: throws when the snapshot exceeds the per-file mount limit', async () => { | ||
| mockIsFeatureEnabled.mockImplementation(snapshotCacheOn) | ||
| mockHasCloudStorage.mockReturnValue(false) | ||
| mockGetOrCreateTableSnapshot.mockResolvedValue({ | ||
| key: 'table-snapshots/ws_1/tbl_1/v5.csv', | ||
| size: 20 * 1024 * 1024, | ||
| version: 5, | ||
| }) | ||
| await expect( | ||
| executeFunctionExecute({ inputTables: ['tbl_1'] }, context as never) | ||
| ).rejects.toThrow(/per-file mount limit/) | ||
| expect(mockDownloadFile).not.toHaveBeenCalled() | ||
| }) | ||
| it('rejects a table that belongs to another workspace (tenant isolation)', async () => { | ||
| mockGetTableById.mockResolvedValue({ ...table, workspaceId: 'ws_2' }) | ||
| await expect( | ||
| executeFunctionExecute({ inputTables: ['tbl_1'] }, context as never) | ||
| ).rejects.toThrow(/Input table not found/) | ||
| expect(mockGetOrCreateTableSnapshot).not.toHaveBeenCalled() | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -5,13 +5,19 @@ import { isPlanAliasPath, workflowAliasSandboxPath } from '@/lib/copilot/vfs/wor | ||
| import { isFeatureEnabled } from '@/lib/core/config/feature-flags' | ||
| import { queryRows } from '@/lib/table/rows/service' | ||
| import { getTableById, listTables } from '@/lib/table/service' | ||
| import { getOrCreateTableSnapshot, SNAPSHOT_MAX_BYTES } from '@/lib/table/snapshot-cache' | ||
| import { listWorkspaceFileFolders } from '@/lib/uploads/contexts/workspace/workspace-file-folder-manager' | ||
| import { | ||
| fetchWorkspaceFileBuffer, | ||
| findWorkspaceFileRecord, | ||
| getSandboxWorkspaceFilePath, | ||
| listWorkspaceFiles, | ||
| } from '@/lib/uploads/contexts/workspace/workspace-file-manager' | ||
| import { | ||
| downloadFile, | ||
| generatePresignedDownloadUrl, | ||
| hasCloudStorage, | ||
| } from '@/lib/uploads/core/storage-service' | ||
| import { executeTool as executeAppTool } from '@/tools' | ||
| import type { ToolExecutionContext, ToolExecutionResult } from '../../tool-executor/types' | ||
| @@ -21,11 +27,22 @@ const MAX_FILE_SIZE = 10 * 1024 * 1024 | ||
| const MAX_TOTAL_SIZE = 50 * 1024 * 1024 | ||
| const MAX_MOUNTED_FILES = 500 | ||
| interface SandboxFile { | ||
| path: string | ||
| content: string | ||
| encoding?: 'base64' | ||
| } | ||
| /** | ||
| * Below this row count a table mounts via the direct inline CSV path — the version-keyed snapshot | ||
| * cache (storage round-trip) only pays off for larger/hot tables. Behind the feature flag either | ||
| * way; this just keeps tiny one-shot tables on the cheaper path. | ||
| */ | ||
| const SNAPSHOT_MIN_ROWS = 500 | ||
| /** | ||
| * Lifetime of the presigned URL handed to the sandbox to fetch a snapshot. Long enough to download | ||
| * a large file at sandbox startup; the URL grants read to only that one version-pinned object. | ||
| */ | ||
| const SNAPSHOT_URL_TTL_SECONDS = 600 | ||
| type SandboxFile = | ||
| | { type?: 'content'; path: string; content: string; encoding?: 'base64' } | ||
| | { type: 'url'; path: string; url: string } | ||
| interface CanonicalFileInput { | ||
| path: string | ||
| @@ -249,6 +266,7 @@ async function resolveInputFiles( | ||
| const tablePathLookup = hasTablePathRefs | ||
| ? new Map((await listTables(workspaceId)).map((table) => [table.name, table])) | ||
| : undefined | ||
| const snapshotCacheEnabled = await isFeatureEnabled('table-snapshot-cache') | ||
| for (const tableRef of inputTables) { | ||
| const tableId = | ||
| typeof tableRef === 'string' | ||
| @@ -263,6 +281,56 @@ async function resolveInputFiles( | ||
| `Input table not found: "${tableId}". Pass the table id (tbl_...) from tables/{name}/meta.json, or a tables/{name}/meta.json path.` | ||
| ) | ||
| } | ||
| const sandboxPath = | ||
| typeof tableRef === 'object' && tableRef !== null | ||
| ? (tableRef as CanonicalTableInput).sandboxPath | ||
| : undefined | ||
| const mountPath = sandboxPath || `/home/user/tables/${table.id}.csv` | ||
| // Large/hot tables mount by reference from a version-keyed CSV snapshot in object storage. | ||
| if (snapshotCacheEnabled && table.rowCount >= SNAPSHOT_MIN_ROWS) { | ||
| const snapshot = await getOrCreateTableSnapshot(table, 'copilot-fn-exec') | ||
| if (hasCloudStorage()) { | ||
| // Mount by reference: the sandbox fetches the snapshot straight from storage via a | ||
| // presigned URL, so the bytes never pass through the web process — the only ceiling is | ||
| // sandbox disk (enforced at materialization by SNAPSHOT_MAX_BYTES). | ||
| if (snapshot.size > SNAPSHOT_MAX_BYTES) { | ||
| throw new Error( | ||
| `Input table "${tableId}" is ${Math.round(snapshot.size / 1024 / 1024)}MB, over the ${SNAPSHOT_MAX_BYTES / 1024 / 1024}MB table mount limit.` | ||
| ) | ||
| } | ||
| const url = await generatePresignedDownloadUrl( | ||
| snapshot.key, | ||
| 'execution', | ||
| SNAPSHOT_URL_TTL_SECONDS | ||
| ) | ||
| sandboxFiles.push({ type: 'url', path: mountPath, url }) | ||
| continue | ||
| } | ||
| // Local storage: a presigned URL is an app-internal serve path a remote sandbox can't | ||
| // reach, so fall back to buffering the bytes through the web process (file-mount guards). | ||
| if (snapshot.size > MAX_FILE_SIZE) { | ||
| throw new Error( | ||
| `Input table "${tableId}" is ${Math.round(snapshot.size / 1024 / 1024)}MB, over the ${MAX_FILE_SIZE / 1024 / 1024}MB per-file mount limit.` | ||
| ) | ||
| } | ||
| if (totalSize + snapshot.size > MAX_TOTAL_SIZE) { | ||
| throw new Error( | ||
| `Mounting "${tableId}" would exceed the ${MAX_TOTAL_SIZE / 1024 / 1024}MB total mount limit. Mount fewer or smaller tables.` | ||
| ) | ||
| } | ||
| const buffer = await downloadFile({ | ||
| key: snapshot.key, | ||
| context: 'execution', | ||
| maxBytes: MAX_FILE_SIZE, | ||
| }) | ||
| totalSize += buffer.length | ||
| sandboxFiles.push({ path: mountPath, content: buffer.toString('utf-8') }) | ||
| continue | ||
| } | ||
TheodoreSpeaks marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| const rows = await queryRows(table, {}, 'copilot-fn-exec') | ||
| const allKeys = new Set(table.schema.columns.map((column) => column.name)) | ||
| @@ -290,14 +358,7 @@ async function resolveInputFiles( | ||
| ) | ||
| } | ||
| const csvContent = csvLines.join('\n') | ||
| const sandboxPath = | ||
| typeof tableRef === 'object' && tableRef !== null | ||
| ? (tableRef as CanonicalTableInput).sandboxPath | ||
| : undefined | ||
| sandboxFiles.push({ | ||
| path: sandboxPath || `/home/user/tables/${table.id}.csv`, | ||
| content: csvContent, | ||
| }) | ||
| sandboxFiles.push({ path: mountPath, content: csvContent }) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.