Skip to content

Commit 6494bd2

Browse files
waleedlatif1Royce Christon
authored andcommitted
improvement(processing): reduce redundant DB queries in execution preprocessing (simstudioai#3320)
* improvement(processing): reduce redundant DB queries in execution preprocessing * improvement(processing): add defensive ID check for prefetched workflow record * improvement(processing): fix type safety in execution error logging Replace `as any` cast in non-SSE error path with proper `buildTraceSpans()` transformation, matching the SSE error path. Remove redundant `as any` cast in preprocessing.ts where the types already align. * improvement(processing): replace `as any` casts with proper types in logging - logger.ts: cast JSONB cost column to `WorkflowExecutionLog['cost']` instead of `any` in both `completeWorkflowExecution` and `getWorkflowExecution` - logger.ts: replace `(orgUsageBefore as any)?.toString?.()` with `String()` since COALESCE guarantees a non-null SQL aggregate value - logging-session.ts: cast JSONB cost to `AccumulatedCost` (the local interface) instead of `any` in `loadExistingCost` * improvement(processing): use exported HighestPrioritySubscription type in usage.ts Replace inline `Awaited<ReturnType<typeof getHighestPrioritySubscription>>` with the already-exported `HighestPrioritySubscription` type alias. * improvement(processing): replace remaining `as any` casts with proper types - preprocessing.ts: use exported `HighestPrioritySubscription` type instead of redeclaring via `Awaited<ReturnType<...>>` - deploy/route.ts, status/route.ts: cast `hasWorkflowChanged` args to `WorkflowState` instead of `any` (JSONB + object literal narrowing) - state/route.ts: type block sanitization and save with `BlockState` and `WorkflowState` instead of `any` - search-suggestions.ts: remove 8 unnecessary `as any` casts on `'date'` literal that already satisfies the `Suggestion['category']` union * fix(processing): prevent double-billing race in LoggingSession completion When executeWorkflowCore throws, its catch block fire-and-forgets safeCompleteWithError, then re-throws. The caller's catch block also fire-and-forgets safeCompleteWithError on the same LoggingSession. Both check this.completed (still false) before either's async DB write resolves, so both proceed to completeWorkflowExecution which uses additive SQL for billing — doubling the charged cost on every failed execution. Fix: add a synchronous `completing` flag set immediately before the async work begins. This blocks concurrent callers at the guard check. On failure, the flag is reset so the safe* fallback path (completeWithCostOnlyLog) can still attempt recovery. * fix(processing): unblock error responses and isolate run-count failures Remove unnecessary `await waitForCompletion()` from non-SSE and SSE error paths where no `markAsFailed()` follows — these were blocking error responses on log persistence for no reason. Wrap `updateWorkflowRunCounts` in its own try/catch so a run-count DB failure cannot prevent session completion, billing, and trace span persistence. * improvement(processing): remove dead setupExecutor method The method body was just a debug log with an `any` parameter — logging now works entirely through trace spans with no executor integration. * remove logger.debug * fix(processing): guard completionPromise as write-once (singleton promise) Prevent concurrent safeComplete* calls from overwriting completionPromise with a no-op. The guard now lives at the assignment site — if a completion is already in-flight, return its promise instead of starting a new one. This ensures waitForCompletion() always awaits the real work. * improvement(processing): remove empty else/catch blocks left by debug log cleanup * fix(processing): enforce waitForCompletion inside markAsFailed to prevent completion races Move waitForCompletion() into markAsFailed() so every call site is automatically safe against in-flight fire-and-forget completions. Remove the now-redundant external waitForCompletion() calls in route.ts. * fix(processing): reset completing flag on fallback failure, clean up empty catch - completeWithCostOnlyLog now resets this.completing = false when the fallback itself fails, preventing a permanently stuck session - Use _disconnectError in MCP test-connection to signal intentional ignore * fix(processing): restore disconnect error logging in MCP test-connection Revert unrelated debug log removal — this file isn't part of the processing improvements and the log aids connection leak detection. * fix(processing): address audit findings across branch - preprocessing.ts: use undefined (not null) for failed subscription fetch so getUserUsageLimit does a fresh lookup instead of silently falling back to free-tier limits - deployed/route.ts: log warning on loadDeployedWorkflowState failure instead of silently swallowing the error - schedule-execution.ts: remove dead successLog parameter and all call-site arguments left over from logger.debug cleanup - mcp/middleware.ts: drop unused error binding in empty catch - audit/log.ts, wand.ts: promote logger.debug to logger.warn in catch blocks where these are the only failure signal * revert: undo unnecessary subscription null→undefined change getHighestPrioritySubscription never throws (it catches internally and returns null), so the catch block in preprocessExecution is dead code. The null vs undefined distinction doesn't matter and the coercions added unnecessary complexity. * improvement(processing): remove dead try/catch around getHighestPrioritySubscription getHighestPrioritySubscription catches internally and returns null on error, so the wrapping try/catch was unreachable dead code. * improvement(processing): remove dead getSnapshotByHash method No longer called after createSnapshotWithDeduplication was refactored to use a single upsert instead of select-then-insert. ---------
1 parent 0ad3f18 commit 6494bd2

54 files changed

Lines changed: 298 additions & 564 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.

apps/sim/app/api/billing/update-cost/route.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@ export async function POST(req: NextRequest) {
3333
logger.info(`[${requestId}] Update cost request started`)
3434

3535
if (!isBillingEnabled) {
36-
logger.debug(`[${requestId}] Billing is disabled, skipping cost update`)
3736
return NextResponse.json({
3837
success: true,
3938
message: 'Billing disabled, cost update skipped',

apps/sim/app/api/chat/[identifier]/otp/route.ts

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -117,8 +117,6 @@ export async function POST(
117117
const requestId = generateRequestId()
118118

119119
try {
120-
logger.debug(`[${requestId}] Processing OTP request for identifier: ${identifier}`)
121-
122120
const body = await request.json()
123121
const { email } = otpRequestSchema.parse(body)
124122

@@ -211,8 +209,6 @@ export async function PUT(
211209
const requestId = generateRequestId()
212210

213211
try {
214-
logger.debug(`[${requestId}] Verifying OTP for identifier: ${identifier}`)
215-
216212
const body = await request.json()
217213
const { email, otp } = otpVerifySchema.parse(body)
218214

apps/sim/app/api/chat/[identifier]/route.ts

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1003,8 +1003,6 @@ export async function GET(
10031003
const requestId = generateRequestId()
10041004

10051005
try {
1006-
logger.debug(`[${requestId}] Fetching chat info for identifier: ${identifier}`)
1007-
10081006
const deploymentResult = await db
10091007
.select({
10101008
id: chat.id,

apps/sim/app/api/creators/route.ts

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -95,11 +95,6 @@ export async function POST(request: NextRequest) {
9595
const body = await request.json()
9696
const data = CreateCreatorProfileSchema.parse(body)
9797

98-
logger.debug(`[${requestId}] Creating creator profile:`, {
99-
referenceType: data.referenceType,
100-
referenceId: data.referenceId,
101-
})
102-
10398
// Validate permissions
10499
if (data.referenceType === 'user') {
105100
if (data.referenceId !== session.user.id) {

apps/sim/app/api/form/[identifier]/route.ts

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,6 @@ export async function POST(
5858
const requestId = generateRequestId()
5959

6060
try {
61-
logger.debug(`[${requestId}] Processing form submission for identifier: ${identifier}`)
62-
6361
let parsedBody
6462
try {
6563
const rawBody = await request.json()
@@ -300,8 +298,6 @@ export async function GET(
300298
const requestId = generateRequestId()
301299

302300
try {
303-
logger.debug(`[${requestId}] Fetching form info for identifier: ${identifier}`)
304-
305301
const deploymentResult = await db
306302
.select({
307303
id: form.id,

apps/sim/app/api/help/route.ts

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,8 +77,6 @@ export async function POST(req: NextRequest) {
7777
}
7878
}
7979

80-
logger.debug(`[${requestId}] Help request includes ${images.length} images`)
81-
8280
const userId = session.user.id
8381
let emailText = `
8482
Type: ${type}

apps/sim/app/api/knowledge/search/route.ts

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -245,8 +245,6 @@ export async function POST(request: NextRequest) {
245245
valueTo: filter.valueTo,
246246
}
247247
})
248-
249-
logger.debug(`[${requestId}] Processed ${structuredFilters.length} structured filters`)
250248
}
251249

252250
if (accessibleKbIds.length === 0) {
@@ -279,7 +277,6 @@ export async function POST(request: NextRequest) {
279277

280278
if (!hasQuery && hasFilters) {
281279
// Tag-only search without vector similarity
282-
logger.debug(`[${requestId}] Executing tag-only search with filters:`, structuredFilters)
283280
results = await handleTagOnlySearch({
284281
knowledgeBaseIds: accessibleKbIds,
285282
topK: validatedData.topK,
@@ -303,7 +300,6 @@ export async function POST(request: NextRequest) {
303300
})
304301
} else if (hasQuery && !hasFilters) {
305302
// Vector-only search
306-
logger.debug(`[${requestId}] Executing vector-only search`)
307303
const strategy = getQueryStrategy(accessibleKbIds.length, validatedData.topK)
308304
const queryVector = JSON.stringify(await queryEmbeddingPromise)
309305

apps/sim/app/api/knowledge/search/utils.ts

Lines changed: 0 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,9 @@
11
import { db } from '@sim/db'
22
import { document, embedding } from '@sim/db/schema'
3-
import { createLogger } from '@sim/logger'
43
import { and, eq, inArray, isNull, sql } from 'drizzle-orm'
54
import { env } from '@/lib/core/config/env'
65
import type { StructuredFilter } from '@/lib/knowledge/types'
76

8-
const logger = createLogger('KnowledgeSearchUtils')
9-
107
export async function getDocumentNamesByIds(
118
documentIds: string[]
129
): Promise<Record<string, string>> {
@@ -148,17 +145,12 @@ function buildFilterCondition(filter: StructuredFilter, embeddingTable: any) {
148145
const { tagSlot, fieldType, operator, value, valueTo } = filter
149146

150147
if (!isTagSlotKey(tagSlot)) {
151-
logger.debug(`[getStructuredTagFilters] Unknown tag slot: ${tagSlot}`)
152148
return null
153149
}
154150

155151
const column = embeddingTable[tagSlot]
156152
if (!column) return null
157153

158-
logger.debug(
159-
`[getStructuredTagFilters] Processing ${tagSlot} (${fieldType}) ${operator} ${value}`
160-
)
161-
162154
// Handle text operators
163155
if (fieldType === 'text') {
164156
const stringValue = String(value)
@@ -216,7 +208,6 @@ function buildFilterCondition(filter: StructuredFilter, embeddingTable: any) {
216208
const dateStr = String(value)
217209
// Validate YYYY-MM-DD format
218210
if (!/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
219-
logger.debug(`[getStructuredTagFilters] Invalid date format: ${dateStr}, expected YYYY-MM-DD`)
220211
return null
221212
}
222213

@@ -295,9 +286,6 @@ function getStructuredTagFilters(filters: StructuredFilter[], embeddingTable: an
295286
conditions.push(slotConditions[0])
296287
} else {
297288
// Multiple conditions for same slot - OR them together
298-
logger.debug(
299-
`[getStructuredTagFilters] OR'ing ${slotConditions.length} conditions for ${slot}`
300-
)
301289
conditions.push(sql`(${sql.join(slotConditions, sql` OR `)})`)
302290
}
303291
}
@@ -388,8 +376,6 @@ export async function handleTagOnlySearch(params: SearchParams): Promise<SearchR
388376
throw new Error('Tag filters are required for tag-only search')
389377
}
390378

391-
logger.debug(`[handleTagOnlySearch] Executing tag-only search with filters:`, structuredFilters)
392-
393379
const strategy = getQueryStrategy(knowledgeBaseIds.length, topK)
394380
const tagFilterConditions = getStructuredTagFilters(structuredFilters, embedding)
395381

@@ -439,8 +425,6 @@ export async function handleVectorOnlySearch(params: SearchParams): Promise<Sear
439425
throw new Error('Query vector and distance threshold are required for vector-only search')
440426
}
441427

442-
logger.debug(`[handleVectorOnlySearch] Executing vector-only search`)
443-
444428
const strategy = getQueryStrategy(knowledgeBaseIds.length, topK)
445429

446430
const distanceExpr = sql<number>`${embedding.embedding} <=> ${queryVector}::vector`.as('distance')
@@ -497,23 +481,13 @@ export async function handleTagAndVectorSearch(params: SearchParams): Promise<Se
497481
throw new Error('Query vector and distance threshold are required for tag and vector search')
498482
}
499483

500-
logger.debug(
501-
`[handleTagAndVectorSearch] Executing tag + vector search with filters:`,
502-
structuredFilters
503-
)
504-
505484
// Step 1: Filter by tags first
506485
const tagFilteredIds = await executeTagFilterQuery(knowledgeBaseIds, structuredFilters)
507486

508487
if (tagFilteredIds.length === 0) {
509-
logger.debug(`[handleTagAndVectorSearch] No results found after tag filtering`)
510488
return []
511489
}
512490

513-
logger.debug(
514-
`[handleTagAndVectorSearch] Found ${tagFilteredIds.length} results after tag filtering`
515-
)
516-
517491
// Step 2: Perform vector search only on tag-filtered results
518492
return await executeVectorSearchOnIds(
519493
tagFilteredIds.map((r) => r.id),

apps/sim/app/api/logs/execution/[executionId]/route.ts

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,6 @@ export async function GET(
3434

3535
const authenticatedUserId = authResult.userId
3636

37-
logger.debug(
38-
`[${requestId}] Fetching execution data for: ${executionId} (auth: ${authResult.authType})`
39-
)
40-
4137
const [workflowLog] = await db
4238
.select({
4339
id: workflowExecutionLogs.id,
@@ -125,11 +121,6 @@ export async function GET(
125121
},
126122
}
127123

128-
logger.debug(`[${requestId}] Successfully fetched execution data for: ${executionId}`)
129-
logger.debug(
130-
`[${requestId}] Workflow state contains ${Object.keys((snapshot.stateData as any)?.blocks || {}).length} blocks`
131-
)
132-
133124
return NextResponse.json(response)
134125
} catch (error) {
135126
logger.error(`[${requestId}] Error fetching execution data:`, error)

apps/sim/app/api/mcp/tools/execute/route.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,6 @@ export const POST = withMcpAuth('read')(
8383
serverId: serverId,
8484
serverName: 'provided-schema',
8585
} as McpTool
86-
logger.debug(`[${requestId}] Using provided schema for ${toolName}, skipping discovery`)
8786
} else {
8887
const tools = await mcpService.discoverServerTools(userId, serverId, workspaceId)
8988
tool = tools.find((t) => t.name === toolName) ?? null

0 commit comments

Comments
 (0)