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
feat(table): per-plan table dispatch concurrency with env overrides#5720
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
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
c0ade1c
feat(table): per-plan table dispatch concurrency with env overrides
TheodoreSpeaks e5d2bd5
fix(table): enforce shared concurrencyKey cap on database batchEnqueu…
TheodoreSpeaks 57c4f3e
refactor(table): thread dispatch concurrency via invocation instead o…
TheodoreSpeaks 57c9fe7
improvement(table): collapse dispatch concurrency env vars to FREE/PAID
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
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
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
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,82 @@ | ||
| /** | ||
| * @vitest-environment node | ||
| */ | ||
| import { beforeEach, describe, expect, it, vi } from 'vitest' | ||
| const { mockEnv, mockFlags } = vi.hoisted(() => ({ | ||
| mockEnv: {} as Record<string, string | undefined>, | ||
| mockFlags: { isBillingEnabled: true }, | ||
| })) | ||
| vi.mock('@/lib/core/config/env', () => ({ | ||
| env: mockEnv, | ||
| envNumber: ( | ||
| value: number | string | undefined | null, | ||
| fallback: number, | ||
| options: { min?: number; integer?: boolean } = {} | ||
| ) => { | ||
| const parsed = Number(value) | ||
| const min = options.min ?? 0 | ||
| return Number.isFinite(parsed) && | ||
| parsed >= min && | ||
| (!options.integer || Number.isInteger(parsed)) | ||
| ? parsed | ||
| : fallback | ||
| }, | ||
| })) | ||
| vi.mock('@/lib/core/config/env-flags', () => ({ | ||
| get isBillingEnabled() { | ||
| return mockFlags.isBillingEnabled | ||
| }, | ||
| })) | ||
| import { | ||
| getMaxTableDispatchConcurrency, | ||
| getTableDispatchConcurrency, | ||
| } from '@/lib/table/dispatch-concurrency' | ||
| describe('getTableDispatchConcurrency', () => { | ||
| beforeEach(() => { | ||
| for (const key of Object.keys(mockEnv)) delete mockEnv[key] | ||
| mockFlags.isBillingEnabled = true | ||
| }) | ||
| it('resolves free vs paid defaults', () => { | ||
| expect(getTableDispatchConcurrency(null)).toBe(20) | ||
| expect(getTableDispatchConcurrency('free')).toBe(20) | ||
| expect(getTableDispatchConcurrency('pro_6000')).toBe(50) | ||
| expect(getTableDispatchConcurrency('team_25000')).toBe(50) | ||
| expect(getTableDispatchConcurrency('enterprise')).toBe(50) | ||
| }) | ||
| it('applies env overrides', () => { | ||
| mockEnv.TABLE_DISPATCH_CONCURRENCY_FREE = '5' | ||
| mockEnv.TABLE_DISPATCH_CONCURRENCY_PAID = '200' | ||
| expect(getTableDispatchConcurrency('free')).toBe(5) | ||
| expect(getTableDispatchConcurrency('pro_6000')).toBe(200) | ||
| expect(getTableDispatchConcurrency('enterprise')).toBe(200) | ||
| }) | ||
| it('uses the paid value when billing is disabled', () => { | ||
| mockFlags.isBillingEnabled = false | ||
| expect(getTableDispatchConcurrency(null)).toBe(50) | ||
| mockEnv.TABLE_DISPATCH_CONCURRENCY_PAID = '120' | ||
| expect(getTableDispatchConcurrency(null)).toBe(120) | ||
| }) | ||
| }) | ||
| describe('getMaxTableDispatchConcurrency', () => { | ||
| beforeEach(() => { | ||
| for (const key of Object.keys(mockEnv)) delete mockEnv[key] | ||
| }) | ||
| it('returns the highest configured value', () => { | ||
| expect(getMaxTableDispatchConcurrency()).toBe(50) | ||
| mockEnv.TABLE_DISPATCH_CONCURRENCY_FREE = '80' | ||
| expect(getMaxTableDispatchConcurrency()).toBe(80) | ||
| }) | ||
| }) |
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,72 @@ | ||
| import { getPlanTypeForLimits } from '@/lib/billing/plan-helpers' | ||
| import { env, envNumber } from '@/lib/core/config/env' | ||
| import { isBillingEnabled } from '@/lib/core/config/env-flags' | ||
| /** | ||
| * Default table dispatch concurrency — how many rows one table run executes | ||
| * in parallel (the dispatcher window size). Free vs paid (Pro, Max, | ||
| * Enterprise); overridable via `TABLE_DISPATCH_CONCURRENCY_{FREE,PAID}`. | ||
| */ | ||
| export const DEFAULT_TABLE_DISPATCH_CONCURRENCY = { | ||
| free: 20, | ||
| paid: 50, | ||
| } as const | ||
| /** | ||
| * Resolves dispatch concurrency limits, applying env overrides on top of the | ||
| * defaults. | ||
| */ | ||
| export function getTableDispatchConcurrencyLimits(): { free: number; paid: number } { | ||
| return { | ||
| free: envNumber(env.TABLE_DISPATCH_CONCURRENCY_FREE, DEFAULT_TABLE_DISPATCH_CONCURRENCY.free, { | ||
| min: 1, | ||
| integer: true, | ||
| }), | ||
| paid: envNumber(env.TABLE_DISPATCH_CONCURRENCY_PAID, DEFAULT_TABLE_DISPATCH_CONCURRENCY.paid, { | ||
| min: 1, | ||
| integer: true, | ||
| }), | ||
| } | ||
| } | ||
| /** | ||
| * Dispatch concurrency for one payer plan. Billing-disabled deployments get | ||
| * the paid value. | ||
| */ | ||
| export function getTableDispatchConcurrency(plan: string | null | undefined): number { | ||
| const limits = getTableDispatchConcurrencyLimits() | ||
| if (!isBillingEnabled) return limits.paid | ||
| return getPlanTypeForLimits(plan) === 'free' ? limits.free : limits.paid | ||
| } | ||
| /** | ||
| * Highest configured dispatch concurrency. The `workflow-group-cell` | ||
| * trigger.dev queue cap derives from this so the server-side per-table | ||
| * ceiling never throttles below a plan's window. | ||
| */ | ||
| export function getMaxTableDispatchConcurrency(): number { | ||
| const limits = getTableDispatchConcurrencyLimits() | ||
| return Math.max(limits.free, limits.paid) | ||
| } | ||
| /** | ||
| * Resolves the workspace payer's plan and returns its dispatch concurrency. | ||
| * Uses the same billing attribution the cells are billed under, so the window | ||
| * follows whoever pays for the run. | ||
| */ | ||
| export async function resolveTableDispatchConcurrency(input: { | ||
| workspaceId: string | ||
| actorUserId?: string | null | ||
| }): Promise<number> { | ||
| if (!isBillingEnabled) return getTableDispatchConcurrencyLimits().paid | ||
| const { resolveBillingAttribution, resolveSystemBillingAttribution } = await import( | ||
| '@/lib/billing/core/billing-attribution' | ||
| ) | ||
| const attribution = input.actorUserId | ||
| ? await resolveBillingAttribution({ | ||
| actorUserId: input.actorUserId, | ||
| workspaceId: input.workspaceId, | ||
| }) | ||
| : await resolveSystemBillingAttribution(input.workspaceId) | ||
| return getTableDispatchConcurrency(attribution.payerSubscription?.plan) | ||
| } |
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 |
|---|---|---|
| @@ -40,11 +40,6 @@ import { | ||
| const logger = createLogger('TableRunDispatcher') | ||
| /** Window size matches the cell-execution concurrency cap so one window | ||
| * saturates the pool before the next is loaded — yields a row-major | ||
| * scan-line crawl (rows 1-20 finish before 21-40 start). */ | ||
| const WINDOW_SIZE = TABLE_CONCURRENCY_LIMIT | ||
| const ACTIVE_DISPATCH_STATUSES = ['pending', 'dispatching'] as const | ||
| export type DispatchStatus = 'pending' | 'dispatching' | 'complete' | 'cancelled' | ||
| @@ -323,14 +318,23 @@ export async function readDispatch(dispatchId: string): Promise<DispatchRow | nu | ||
| /** Drive `dispatcherStep` to completion. Shared between the trigger.dev task | ||
| * wrapper (`tableRunDispatcherTask`) and the in-process inline path so both | ||
| * runtimes use identical loop semantics + error logging. */ | ||
| export async function runDispatcherToCompletion(dispatchId: string): Promise<void> { | ||
| while ((await dispatcherStep(dispatchId)) === 'continue') {} | ||
| * runtimes use identical loop semantics + error logging. `concurrency` is the | ||
| * invoker's plan-resolved window size (see `resolveTableDispatchConcurrency`), | ||
| * threaded via the task payload; absent on payloads from before the field | ||
| * existed → legacy cap. */ | ||
| export async function runDispatcherToCompletion( | ||
| dispatchId: string, | ||
| concurrency?: number | ||
| ): Promise<void> { | ||
| while ((await dispatcherStep(dispatchId, concurrency)) === 'continue') {} | ||
| } | ||
| /** Run one window of the dispatcher state machine. Caller re-invokes (via the | ||
| * trigger.dev task wrapper) until the returned status is `'done'`. */ | ||
| export async function dispatcherStep(dispatchId: string): Promise<DispatcherStepResult> { | ||
| export async function dispatcherStep( | ||
| dispatchId: string, | ||
| concurrency?: number | ||
| ): Promise<DispatcherStepResult> { | ||
| const dispatch = await readDispatch(dispatchId) | ||
| if (!dispatch) { | ||
| logger.warn(`[${dispatchId}] dispatch row missing — aborting`) | ||
| @@ -380,6 +384,11 @@ export async function dispatcherStep(dispatchId: string): Promise<DispatcherStep | ||
| }) | ||
| } | ||
| // Window size = the invoker's plan-resolved parallelism, so one window | ||
| // saturates the cell pool before the next is loaded — yields a row-major | ||
| // scan-line crawl. Payloads without the field fall back to the legacy cap. | ||
| const windowSize = concurrency ?? TABLE_CONCURRENCY_LIMIT | ||
| const filters = [ | ||
| eq(userTableRows.tableId, dispatch.tableId), | ||
| gt(userTableRows.position, dispatch.cursor), | ||
| @@ -429,7 +438,7 @@ export async function dispatcherStep(dispatchId: string): Promise<DispatcherStep | ||
| .from(userTableRows) | ||
| .where(and(...filters)) | ||
| .orderBy(asc(userTableRows.position)) | ||
| .limit(WINDOW_SIZE) | ||
| .limit(windowSize) | ||
| // Filtered scopes carry a jsonb predicate the planner can't estimate — left alone it | ||
| // seq-scans the whole shared relation per window; keep it on the tenant's position index. | ||
| const chunk = hasJsonbFilter | ||
| @@ -533,8 +542,8 @@ export async function dispatcherStep(dispatchId: string): Promise<DispatcherStep | ||
| // (CRIU-checkpointed wait); database backend calls the cell-task runner | ||
| // directly via Promise.all (skips async_jobs since we're awaiting in- | ||
| // process anyway). Either way the parent dispatcher blocks until every | ||
| // cell in the window terminates — bounds queue depth at WINDOW_SIZE. | ||
| const items = await buildEnqueueItems(windowRuns) | ||
| // cell in the window terminates — bounds queue depth at the window size. | ||
| const items = await buildEnqueueItems(windowRuns, windowSize) | ||
cursor[bot] marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| const queue = await getJobQueue() | ||
| try { | ||
| await queue.batchEnqueueAndWait('workflow-group-cell', items) | ||
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.