Skip to content

Commit 26daa04

Browse files
committed
refactor(workflow-code): simplify the round's fixes: explicit blob consumption for every write, one fallback completion shape, a shared cancellation check
1 parent 4c94efa commit 26daa04

14 files changed

Lines changed: 109 additions & 121 deletions

File tree

‎apps/sim/lib/billing/storage/tracking.ts‎

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -194,18 +194,18 @@ function getWorkspaceBillingEntity(row: LockedWorkspaceStorage): BillingEntity {
194194
: { type: 'user', id: row.billedAccountUserId }
195195
}
196196

197-
/** Whether the locked workspace row still routes storage to `context`'s payer. */
198-
function routesToContextPayer(
197+
/** The payer the locked workspace row routes storage to, when it is still `context`'s; else `null`. */
198+
function contextPayerOf(
199199
row: LockedWorkspaceStorage,
200200
context: StorageBillingContext
201-
): boolean {
202-
const currentBillingEntity = getWorkspaceBillingEntity(row)
203-
return (
204-
row.id === context.workspaceId &&
205-
currentBillingEntity.type === context.billingEntity.type &&
206-
currentBillingEntity.id === context.billingEntity.id &&
201+
): BillingEntity | null {
202+
const current = getWorkspaceBillingEntity(row)
203+
return row.id === context.workspaceId &&
204+
current.type === context.billingEntity.type &&
205+
current.id === context.billingEntity.id &&
207206
row.billedAccountUserId === context.billedAccountUserId
208-
)
207+
? current
208+
: null
209209
}
210210

211211
/**
@@ -216,12 +216,13 @@ function assertWorkspaceStorageContext(
216216
row: LockedWorkspaceStorage,
217217
context: StorageBillingContext
218218
): BillingEntity {
219-
if (!routesToContextPayer(row, context)) {
219+
const payer = contextPayerOf(row, context)
220+
if (!payer) {
220221
throw new Error(
221222
`Storage payer changed for workspace ${context.workspaceId}; resolve a fresh billing context`
222223
)
223224
}
224-
return getWorkspaceBillingEntity(row)
225+
return payer
225226
}
226227

227228
/**
@@ -233,10 +234,8 @@ export async function isWorkspaceStoragePayerInTx(
233234
tx: DbOrTx,
234235
context: StorageBillingContext
235236
): Promise<boolean> {
236-
return routesToContextPayer(
237-
await lockWorkspaceStorageForMutationInTx(tx, context.workspaceId),
238-
context
239-
)
237+
const row = await lockWorkspaceStorageForMutationInTx(tx, context.workspaceId)
238+
return contextPayerOf(row, context) !== null
240239
}
241240

242241
/**

‎apps/sim/lib/logs/execution/logging-session.ts‎

Lines changed: 30 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,12 @@ export interface SessionPausedParams {
194194
executionState?: SerializableExecutionState
195195
}
196196

197+
/** What a completion was given that its cost-only fallback carries over. */
198+
type FallbackCompletion = Pick<
199+
SessionCompleteParams,
200+
'endedAt' | 'totalDurationMs' | 'traceSpans' | 'workflowInput' | 'executionState'
201+
>
202+
197203
export interface LoggingSessionOptions {
198204
/**
199205
* Overrides the per-run fixed charge. Pass `0` for a run whose base charge is
@@ -1530,16 +1536,11 @@ export class LoggingSession {
15301536
requestId: this.requestId,
15311537
error: errorMsg,
15321538
})
1533-
await this.completeWithCostOnlyLog({
1534-
traceSpans: params.traceSpans,
1535-
workflowInput: params.workflowInput,
1536-
endedAt: params.endedAt,
1537-
totalDurationMs: params.totalDurationMs,
1539+
await this.completeWithCostOnlyLog(params, {
15381540
errorMessage: `Failed to store trace spans: ${errorMsg}`,
15391541
isError: false,
15401542
finalizationPath: 'fallback_completed',
15411543
finalOutput: params.finalOutput || {},
1542-
executionState: params.executionState,
15431544
})
15441545
}
15451546
}
@@ -1560,19 +1561,14 @@ export class LoggingSession {
15601561
`CompleteWithError failed for execution ${this.executionId}, attempting fallback`,
15611562
{ requestId: this.requestId, error: errorMsg }
15621563
)
1563-
await this.completeWithCostOnlyLog({
1564-
traceSpans: params?.traceSpans,
1565-
workflowInput: params?.workflowInput,
1566-
endedAt: params?.endedAt,
1567-
totalDurationMs: params?.totalDurationMs,
1564+
await this.completeWithCostOnlyLog(params, {
15681565
errorMessage:
15691566
params?.error?.message || `Execution failed to store trace spans: ${errorMsg}`,
15701567
isError: true,
15711568
finalizationPath: 'force_failed',
15721569
finalOutput: {
15731570
error: params?.error?.message || `Execution failed to store trace spans: ${errorMsg}`,
15741571
},
1575-
executionState: params?.executionState,
15761572
status: 'failed',
15771573
})
15781574
}
@@ -1595,16 +1591,11 @@ export class LoggingSession {
15951591
`CompleteWithCancellation failed for execution ${this.executionId}, attempting fallback`,
15961592
{ requestId: this.requestId, error: errorMsg }
15971593
)
1598-
await this.completeWithCostOnlyLog({
1599-
traceSpans: params?.traceSpans,
1600-
workflowInput: params?.workflowInput,
1601-
endedAt: params?.endedAt,
1602-
totalDurationMs: params?.totalDurationMs,
1594+
await this.completeWithCostOnlyLog(params, {
16031595
errorMessage: 'Run was cancelled',
16041596
isError: false,
16051597
finalizationPath: 'cancelled',
16061598
finalOutput: { cancelled: true },
1607-
executionState: params?.executionState,
16081599
status: 'cancelled',
16091600
})
16101601
}
@@ -1625,16 +1616,11 @@ export class LoggingSession {
16251616
`CompleteWithPause failed for execution ${this.executionId}, attempting fallback`,
16261617
{ requestId: this.requestId, error: errorMsg }
16271618
)
1628-
await this.completeWithCostOnlyLog({
1629-
traceSpans: params?.traceSpans,
1630-
workflowInput: params?.workflowInput,
1631-
endedAt: params?.endedAt,
1632-
totalDurationMs: params?.totalDurationMs,
1619+
await this.completeWithCostOnlyLog(params, {
16331620
errorMessage: 'Run paused but failed to store full trace spans',
16341621
isError: false,
16351622
finalizationPath: 'paused',
16361623
finalOutput: { paused: true },
1637-
executionState: params?.executionState,
16381624
status: 'pending',
16391625
})
16401626
}
@@ -1733,18 +1719,21 @@ export class LoggingSession {
17331719
}
17341720
}
17351721

1736-
private async completeWithCostOnlyLog(params: {
1737-
traceSpans?: TraceSpan[]
1738-
workflowInput?: unknown
1739-
endedAt?: string
1740-
totalDurationMs?: number
1741-
errorMessage: string
1742-
isError: boolean
1743-
finalizationPath: ExecutionFinalizationPath
1744-
finalOutput?: Record<string, unknown>
1745-
executionState?: SerializableExecutionState
1746-
status?: 'completed' | 'failed' | 'cancelled' | 'pending'
1747-
}): Promise<void> {
1722+
/**
1723+
* Completes the run with no trace spans, after the full completion failed: `completion` is
1724+
* what that completion was given (its timing, input and state carry over), `params` what the
1725+
* fallback records instead.
1726+
*/
1727+
private async completeWithCostOnlyLog(
1728+
completion: FallbackCompletion | undefined,
1729+
params: {
1730+
errorMessage: string
1731+
isError: boolean
1732+
finalizationPath: ExecutionFinalizationPath
1733+
finalOutput?: Record<string, unknown>
1734+
status?: 'completed' | 'failed' | 'cancelled' | 'pending'
1735+
}
1736+
): Promise<void> {
17481737
if (this.completed || this.completing) {
17491738
return
17501739
}
@@ -1761,18 +1750,18 @@ export class LoggingSession {
17611750
// from the in-memory trace spans when available (this fallback fires when
17621751
// persisting spans failed, not when computing them did), else just the
17631752
// base execution charge.
1764-
const costSummary = calculateCostSummary(params.traceSpans, this.costOptions)
1753+
const costSummary = calculateCostSummary(completion?.traceSpans, this.costOptions)
17651754

17661755
const finalOutput = params.finalOutput || { _fallback: true, error: params.errorMessage }
17671756

17681757
await this.completeExecutionWithFinalization({
1769-
endedAt: params.endedAt || new Date().toISOString(),
1770-
totalDurationMs: params.totalDurationMs || 0,
1758+
endedAt: completion?.endedAt || new Date().toISOString(),
1759+
totalDurationMs: completion?.totalDurationMs || 0,
17711760
costSummary,
17721761
finalOutput,
17731762
traceSpans: [],
1774-
workflowInput: params.workflowInput,
1775-
executionState: params.executionState,
1763+
workflowInput: completion?.workflowInput,
1764+
executionState: completion?.executionState,
17761765
finalizationPath: params.finalizationPath,
17771766
completionFailure: params.errorMessage,
17781767
level: params.isError ? 'error' : 'info',

‎apps/sim/lib/table/ids.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
import { generateId } from '@sim/utils/id'
22

3-
/** What every table id starts with. */
43
const TABLE_ID_PREFIX = 'tbl_'
54

6-
/** The shape {@link generateTableId} mints: `tbl_` and 32 lowercase hex digits. */
7-
const TABLE_ID_SHAPE = /^tbl_[0-9a-f]{32}$/
5+
/** The shape {@link generateTableId} mints: the prefix and 32 lowercase hex digits. */
6+
const TABLE_ID_SHAPE = new RegExp(`^${TABLE_ID_PREFIX}[0-9a-f]{32}$`)
87

98
/**
109
* Whether `reference` is shaped like a table id, so it is never read as a table name: a name

‎apps/sim/lib/workspace-source/application/apply-workspace-source.ts‎

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -401,8 +401,8 @@ async function consumeStagedBlobs(target: StagingScope, consumed: StagedBlob[]):
401401
/**
402402
* Writes the plan's changes in write order under `lease`, recording each into `base` and
403403
* `result`; the first failure stops it and is reported as `result.failed`. Each write reads its
404-
* binary files from `staged`; returns the staged blobs the workspace now stores: those of the
405-
* writes that succeeded, and those the failed write reported stored before it failed.
404+
* binary files from `staged`; returns the staged blobs the writes reported stored, the failed
405+
* write's included.
406406
*/
407407
async function writeAll(
408408
changes: PlannedChange[],
@@ -419,8 +419,6 @@ async function writeAll(
419419
)
420420
const consumed: StagedBlob[] = []
421421
for (const change of writeOrder(changes)) {
422-
const read: StagedBlob[] = []
423-
const stored: StagedBlob[] = []
424422
const stagedAt = (path: string) => {
425423
const blob = staged.get(path)
426424
if (!blob) throw new Error('A blob write ran without its staged bytes')
@@ -429,20 +427,15 @@ async function writeAll(
429427
const writeCtx: ApplyContext = {
430428
...ctx,
431429
blobs: {
432-
read(path) {
433-
const blob = stagedAt(path)
434-
read.push(blob)
435-
return readStagedBlob(blob)
436-
},
437-
stored(path) {
438-
stored.push(stagedAt(path))
430+
read: (path) => readStagedBlob(stagedAt(path)),
431+
stored: (path) => {
432+
consumed.push(stagedAt(path))
439433
},
440434
},
441435
}
442436
try {
443437
await lease.confirm()
444438
const written = await write(change, writeCtx)
445-
consumed.push(...read)
446439
Object.assign(result.files, written.text)
447440
for (const diagnostic of written.diagnostics ?? []) {
448441
const at = reported.get(findingIdentity(diagnostic))
@@ -466,7 +459,6 @@ async function writeAll(
466459
if (written.base) base.resources[address] = written.base
467460
else delete base.resources[address]
468461
} catch (error) {
469-
consumed.push(...stored)
470462
const failure = failureOf(error, change, result.applyId)
471463
result.failed = failure.failed
472464
result.diagnostics.push(...failure.diagnostics)

‎apps/sim/lib/workspace-source/application/kinds/files/adapter.ts‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -480,14 +480,21 @@ async function claimFileKey(
480480

481481
/**
482482
* The bytes a write sends and their SHA-256: read from the staging area, which checks them
483-
* against the declared hash, so the declaration's hash is theirs.
483+
* against the declared hash, so the declaration's hash is theirs. `stored` reports them stored
484+
* once the write lands, so their staged copy stops counting toward the quota.
484485
*/
485486
async function contentOf(
486487
change: FileChange,
487488
ctx: ApplyContext
488-
): Promise<{ content: Buffer; sha256: string }> {
489-
if (!change.decl || !ctx.blobs) throw new Error('A file write needs its declaration and bytes')
490-
return { content: await ctx.blobs.read(fileBlobPath(change.key)), sha256: change.decl.sha256 }
489+
): Promise<{ content: Buffer; sha256: string; stored: () => void }> {
490+
const { blobs } = ctx
491+
if (!change.decl || !blobs) throw new Error('A file write needs its declaration and bytes')
492+
const path = fileBlobPath(change.key)
493+
return {
494+
content: await blobs.read(path),
495+
sha256: change.decl.sha256,
496+
stored: () => blobs.stored(path),
497+
}
491498
}
492499

493500
/** The base entry of a file just written, from what the server recorded. */
@@ -599,7 +606,7 @@ export const fileAdapter: KindAdapter<'file', StoredFileState> = {
599606
.catch(staleAs(change))
600607
return { id: fileId, text: {} }
601608
}
602-
const { content, sha256 } = await contentOf(change, ctx)
609+
const { content, sha256, stored } = await contentOf(change, ctx)
603610
if (change.action === 'create') {
604611
const segments = change.key.split('/')
605612
const resourceKey = change.detail?.resourceKey
@@ -617,6 +624,7 @@ export const fileAdapter: KindAdapter<'file', StoredFileState> = {
617624
: {}),
618625
},
619626
})
627+
stored()
620628
return written(ctx, change.key, created.id, sha256)
621629
}
622630
const fileId = change.storedId
@@ -634,6 +642,7 @@ export const fileAdapter: KindAdapter<'file', StoredFileState> = {
634642
},
635643
})
636644
.catch(staleAs(change))
645+
stored()
637646
return written(ctx, change.key, fileId, sha256)
638647
},
639648

‎apps/sim/lib/workspace-source/application/knowledge.integration.ts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1098,11 +1098,11 @@ describe('knowledge bases as workspace source', () => {
10981098
})
10991099
.from(workspaceSourceStagedBlob)
11001100
.where(eq(workspaceSourceStagedBlob.workspaceId, workspaceId))
1101-
const consumed = (path: string) =>
1102-
staging.find((row) => row.sha256 === sha256Hex(POLICIES.docs[path] ?? Buffer.alloc(0)))
1103-
?.consumedAt ?? null
1104-
expect(consumed(REFUNDS)).toBeInstanceOf(Date)
1105-
expect(consumed('knowledge/policies/docs/shipping.txt')).toBeNull()
1101+
const consumedAt = new Map(staging.map((row) => [row.sha256, row.consumedAt]))
1102+
const hashOf = (path: string) => sha256Hex(POLICIES.docs[path] ?? Buffer.alloc(0))
1103+
expect(consumedAt.get(hashOf(REFUNDS))).toBeInstanceOf(Date)
1104+
// Still staged, and unconsumed: a missing row reads undefined, never null.
1105+
expect(consumedAt.get(hashOf('knowledge/policies/docs/shipping.txt'))).toBeNull()
11061106

11071107
const second = await apply(workspaceId, POLICIES, { base: first.base })
11081108

‎apps/sim/lib/workspace-source/application/staging.integration.ts‎

Lines changed: 7 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -173,13 +173,14 @@ async function missing(
173173
return result.missing
174174
}
175175

176-
/** What the staging table holds for the workspace: scope, hash and size per row. */
176+
/** The workspace's staging rows, read directly. */
177177
async function rows(workspaceId: string) {
178178
return db
179179
.select({
180180
scope: workspaceSourceStagedBlob.scope,
181181
sha256: workspaceSourceStagedBlob.sha256,
182182
storageKey: workspaceSourceStagedBlob.storageKey,
183+
consumedAt: workspaceSourceStagedBlob.consumedAt,
183184
})
184185
.from(workspaceSourceStagedBlob)
185186
.where(eq(workspaceSourceStagedBlob.workspaceId, workspaceId))
@@ -340,16 +341,10 @@ describe('workspace source staging', () => {
340341
const restaged = { sha256: sha256Hex(notes), size: notes.byteLength, content: notes }
341342
const refused = await failure(stage(applier, workspaceId, [restaged]))
342343
expect(refused).toMatchObject({ name: 'SourceStagingFullError' })
343-
const consumedNotes = await db
344-
.select({ consumedAt: workspaceSourceStagedBlob.consumedAt })
345-
.from(workspaceSourceStagedBlob)
346-
.where(
347-
and(
348-
eq(workspaceSourceStagedBlob.workspaceId, workspaceId),
349-
eq(workspaceSourceStagedBlob.sha256, restaged.sha256)
350-
)
351-
)
352-
expect(consumedNotes).toEqual([{ consumedAt: expect.any(Date) }])
344+
const [consumedNotes] = (await rows(workspaceId)).filter(
345+
(row) => row.sha256 === restaged.sha256
346+
)
347+
expect(consumedNotes.consumedAt).toBeInstanceOf(Date)
353348

354349
// Renewing a blob that still counts adds nothing, so it fits with 2 bytes left.
355350
expect((await stage(applier, workspaceId, [six])).staged).toEqual([
@@ -475,13 +470,7 @@ describe('workspace source staging', () => {
475470
{ sha256: a.sha256, size: a.size, storageKey: read.storageKey },
476471
])
477472

478-
const held = await db
479-
.select({
480-
storageKey: workspaceSourceStagedBlob.storageKey,
481-
consumedAt: workspaceSourceStagedBlob.consumedAt,
482-
})
483-
.from(workspaceSourceStagedBlob)
484-
.where(eq(workspaceSourceStagedBlob.workspaceId, workspaceId))
473+
const held = await rows(workspaceId)
485474
expect(held).toHaveLength(1)
486475
expect(held[0].storageKey).not.toBe(read.storageKey)
487476
expect(held[0].consumedAt).toBeNull()

0 commit comments

Comments
 (0)