Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
79eaf18
improvement(processing): reduce redundant DB queries in execution pre…
waleedlatif1 Feb 24, 2026
9b201d8
improvement(processing): add defensive ID check for prefetched workfl…
waleedlatif1 Feb 24, 2026
eba3358
improvement(processing): fix type safety in execution error logging
waleedlatif1 Feb 24, 2026
ffd5385
improvement(processing): replace `as any` casts with proper types in …
waleedlatif1 Feb 24, 2026
007d137
improvement(processing): use exported HighestPrioritySubscription typ…
waleedlatif1 Feb 24, 2026
6540453
improvement(processing): replace remaining `as any` casts with proper…
waleedlatif1 Feb 24, 2026
1b3708a
fix(processing): prevent double-billing race in LoggingSession comple…
waleedlatif1 Feb 24, 2026
a1b91c1
fix(processing): unblock error responses and isolate run-count failures
waleedlatif1 Feb 24, 2026
540e0be
improvement(processing): remove dead setupExecutor method
waleedlatif1 Feb 24, 2026
4fae73b
remove logger.debug
waleedlatif1 Feb 24, 2026
e7b216b
fix(processing): guard completionPromise as write-once (singleton pro…
waleedlatif1 Feb 24, 2026
f093193
improvement(processing): remove empty else/catch blocks left by debug…
waleedlatif1 Feb 24, 2026
8e72e13
fix(processing): enforce waitForCompletion inside markAsFailed to pre…
waleedlatif1 Feb 24, 2026
5a8e611
fix(processing): reset completing flag on fallback failure, clean up …
waleedlatif1 Feb 24, 2026
6004fea
fix(processing): restore disconnect error logging in MCP test-connection
waleedlatif1 Feb 24, 2026
4c78376
fix(processing): address audit findings across branch
waleedlatif1 Feb 24, 2026
dff3f64
revert: undo unnecessary subscription null→undefined change
waleedlatif1 Feb 24, 2026
e1981b6
improvement(processing): remove dead try/catch around getHighestPrior…
waleedlatif1 Feb 24, 2026
2860663
improvement(processing): remove dead getSnapshotByHash method
waleedlatif1 Feb 24, 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
1 change: 0 additions & 1 deletion apps/sim/app/api/billing/update-cost/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ export async function POST(req: NextRequest) {
logger.info(`[${requestId}] Update cost request started`)

if (!isBillingEnabled) {
logger.debug(`[${requestId}] Billing is disabled, skipping cost update`)
return NextResponse.json({
success: true,
message: 'Billing disabled, cost update skipped',
Expand Down
4 changes: 0 additions & 4 deletions apps/sim/app/api/chat/[identifier]/otp/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,6 @@ export async function POST(
const requestId = generateRequestId()

try {
logger.debug(`[${requestId}] Processing OTP request for identifier: ${identifier}`)

const body = await request.json()
const { email } = otpRequestSchema.parse(body)

Expand Down Expand Up @@ -211,8 +209,6 @@ export async function PUT(
const requestId = generateRequestId()

try {
logger.debug(`[${requestId}] Verifying OTP for identifier: ${identifier}`)

const body = await request.json()
const { email, otp } = otpVerifySchema.parse(body)

Expand Down
4 changes: 0 additions & 4 deletions apps/sim/app/api/chat/[identifier]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,6 @@ export async function POST(
const requestId = generateRequestId()

try {
logger.debug(`[${requestId}] Processing chat request for identifier: ${identifier}`)

let parsedBody
try {
const rawBody = await request.json()
Expand Down Expand Up @@ -294,8 +292,6 @@ export async function GET(
const requestId = generateRequestId()

try {
logger.debug(`[${requestId}] Fetching chat info for identifier: ${identifier}`)

const deploymentResult = await db
.select({
id: chat.id,
Expand Down
5 changes: 0 additions & 5 deletions apps/sim/app/api/creators/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,11 +95,6 @@ export async function POST(request: NextRequest) {
const body = await request.json()
const data = CreateCreatorProfileSchema.parse(body)

logger.debug(`[${requestId}] Creating creator profile:`, {
referenceType: data.referenceType,
referenceId: data.referenceId,
})

// Validate permissions
if (data.referenceType === 'user') {
if (data.referenceId !== session.user.id) {
Expand Down
4 changes: 0 additions & 4 deletions apps/sim/app/api/form/[identifier]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,6 @@ export async function POST(
const requestId = generateRequestId()

try {
logger.debug(`[${requestId}] Processing form submission for identifier: ${identifier}`)

let parsedBody
try {
const rawBody = await request.json()
Expand Down Expand Up @@ -300,8 +298,6 @@ export async function GET(
const requestId = generateRequestId()

try {
logger.debug(`[${requestId}] Fetching form info for identifier: ${identifier}`)

const deploymentResult = await db
.select({
id: form.id,
Expand Down
2 changes: 0 additions & 2 deletions apps/sim/app/api/help/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,6 @@ export async function POST(req: NextRequest) {
}
}

logger.debug(`[${requestId}] Help request includes ${images.length} images`)

const userId = session.user.id
let emailText = `
Type: ${type}
Expand Down
4 changes: 0 additions & 4 deletions apps/sim/app/api/knowledge/search/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,8 +186,6 @@ export async function POST(request: NextRequest) {
valueTo: filter.valueTo,
}
})

logger.debug(`[${requestId}] Processed ${structuredFilters.length} structured filters`)
}

if (accessibleKbIds.length === 0) {
Expand Down Expand Up @@ -220,7 +218,6 @@ export async function POST(request: NextRequest) {

if (!hasQuery && hasFilters) {
// Tag-only search without vector similarity
logger.debug(`[${requestId}] Executing tag-only search with filters:`, structuredFilters)
results = await handleTagOnlySearch({
knowledgeBaseIds: accessibleKbIds,
topK: validatedData.topK,
Expand All @@ -244,7 +241,6 @@ export async function POST(request: NextRequest) {
})
} else if (hasQuery && !hasFilters) {
// Vector-only search
logger.debug(`[${requestId}] Executing vector-only search`)
const strategy = getQueryStrategy(accessibleKbIds.length, validatedData.topK)
const queryVector = JSON.stringify(await queryEmbeddingPromise)

Expand Down
26 changes: 0 additions & 26 deletions apps/sim/app/api/knowledge/search/utils.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
import { db } from '@sim/db'
import { document, embedding } from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { and, eq, inArray, isNull, sql } from 'drizzle-orm'
import type { StructuredFilter } from '@/lib/knowledge/types'

const logger = createLogger('KnowledgeSearchUtils')

export async function getDocumentNamesByIds(
documentIds: string[]
): Promise<Record<string, string>> {
Expand Down Expand Up @@ -140,17 +137,12 @@ function buildFilterCondition(filter: StructuredFilter, embeddingTable: any) {
const { tagSlot, fieldType, operator, value, valueTo } = filter

if (!isTagSlotKey(tagSlot)) {
logger.debug(`[getStructuredTagFilters] Unknown tag slot: ${tagSlot}`)
return null
}

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

logger.debug(
`[getStructuredTagFilters] Processing ${tagSlot} (${fieldType}) ${operator} ${value}`
)

// Handle text operators
if (fieldType === 'text') {
const stringValue = String(value)
Expand Down Expand Up @@ -208,7 +200,6 @@ function buildFilterCondition(filter: StructuredFilter, embeddingTable: any) {
const dateStr = String(value)
// Validate YYYY-MM-DD format
if (!/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
logger.debug(`[getStructuredTagFilters] Invalid date format: ${dateStr}, expected YYYY-MM-DD`)
return null
}

Expand Down Expand Up @@ -287,9 +278,6 @@ function getStructuredTagFilters(filters: StructuredFilter[], embeddingTable: an
conditions.push(slotConditions[0])
} else {
// Multiple conditions for same slot - OR them together
logger.debug(
`[getStructuredTagFilters] OR'ing ${slotConditions.length} conditions for ${slot}`
)
conditions.push(sql`(${sql.join(slotConditions, sql` OR `)})`)
}
}
Expand Down Expand Up @@ -380,8 +368,6 @@ export async function handleTagOnlySearch(params: SearchParams): Promise<SearchR
throw new Error('Tag filters are required for tag-only search')
}

logger.debug(`[handleTagOnlySearch] Executing tag-only search with filters:`, structuredFilters)

const strategy = getQueryStrategy(knowledgeBaseIds.length, topK)
const tagFilterConditions = getStructuredTagFilters(structuredFilters, embedding)

Expand Down Expand Up @@ -431,8 +417,6 @@ export async function handleVectorOnlySearch(params: SearchParams): Promise<Sear
throw new Error('Query vector and distance threshold are required for vector-only search')
}

logger.debug(`[handleVectorOnlySearch] Executing vector-only search`)

const strategy = getQueryStrategy(knowledgeBaseIds.length, topK)

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

logger.debug(
`[handleTagAndVectorSearch] Executing tag + vector search with filters:`,
structuredFilters
)

// Step 1: Filter by tags first
const tagFilteredIds = await executeTagFilterQuery(knowledgeBaseIds, structuredFilters)

if (tagFilteredIds.length === 0) {
logger.debug(`[handleTagAndVectorSearch] No results found after tag filtering`)
return []
}

logger.debug(
`[handleTagAndVectorSearch] Found ${tagFilteredIds.length} results after tag filtering`
)

// Step 2: Perform vector search only on tag-filtered results
return await executeVectorSearchOnIds(
tagFilteredIds.map((r) => r.id),
Expand Down
9 changes: 0 additions & 9 deletions apps/sim/app/api/logs/execution/[executionId]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,6 @@ export async function GET(

const authenticatedUserId = authResult.userId

logger.debug(
`[${requestId}] Fetching execution data for: ${executionId} (auth: ${authResult.authType})`
)

const [workflowLog] = await db
.select({
id: workflowExecutionLogs.id,
Expand Down Expand Up @@ -125,11 +121,6 @@ export async function GET(
},
}

logger.debug(`[${requestId}] Successfully fetched execution data for: ${executionId}`)
logger.debug(
`[${requestId}] Workflow state contains ${Object.keys((snapshot.stateData as any)?.blocks || {}).length} blocks`
)

return NextResponse.json(response)
} catch (error) {
logger.error(`[${requestId}] Error fetching execution data:`, error)
Expand Down
1 change: 0 additions & 1 deletion apps/sim/app/api/mcp/tools/execute/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,6 @@ export const POST = withMcpAuth('read')(
serverId: serverId,
serverName: 'provided-schema',
} as McpTool
logger.debug(`[${requestId}] Using provided schema for ${toolName}, skipping discovery`)
} else {
const tools = await mcpService.discoverServerTools(userId, serverId, workspaceId)
tool = tools.find((t) => t.name === toolName) ?? null
Expand Down
1 change: 0 additions & 1 deletion apps/sim/app/api/schedules/[id]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ export async function PUT(request: NextRequest, { params }: { params: Promise<{

try {
const { id: scheduleId } = await params
logger.debug(`[${requestId}] Reactivating schedule with ID: ${scheduleId}`)

const session = await getSession()
if (!session?.user?.id) {
Expand Down
1 change: 0 additions & 1 deletion apps/sim/app/api/schedules/execute/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ export async function GET(request: NextRequest) {
lastQueuedAt: workflowSchedule.lastQueuedAt,
})

logger.debug(`[${requestId}] Successfully queried schedules: ${dueSchedules.length} found`)
logger.info(`[${requestId}] Processing ${dueSchedules.length} due scheduled workflows`)

const jobQueue = await getJobQueue()
Expand Down
4 changes: 0 additions & 4 deletions apps/sim/app/api/templates/[id]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@ export async function GET(request: NextRequest, { params }: { params: Promise<{
try {
const session = await getSession()

logger.debug(`[${requestId}] Fetching template: ${id}`)

const result = await db
.select({
template: templates,
Expand Down Expand Up @@ -74,8 +72,6 @@ export async function GET(request: NextRequest, { params }: { params: Promise<{
views: sql`${templates.views} + 1`,
})
.where(eq(templates.id, id))

logger.debug(`[${requestId}] Incremented view count for template: ${id}`)
} catch (viewError) {
logger.warn(`[${requestId}] Failed to increment view count for template: ${id}`, viewError)
}
Expand Down
4 changes: 0 additions & 4 deletions apps/sim/app/api/templates/[id]/star/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,6 @@ export async function POST(request: NextRequest, { params }: { params: Promise<{
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}

logger.debug(`[${requestId}] Adding star for template: ${id}, user: ${session.user.id}`)

// Verify the template exists
const templateExists = await db
.select({ id: templates.id })
Expand Down Expand Up @@ -133,8 +131,6 @@ export async function DELETE(
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}

logger.debug(`[${requestId}] Removing star for template: ${id}, user: ${session.user.id}`)

// Check if the star exists
const existingStar = await db
.select({ id: templateStars.id })
Expand Down
7 changes: 0 additions & 7 deletions apps/sim/app/api/templates/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,6 @@ export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url)
const params = QueryParamsSchema.parse(Object.fromEntries(searchParams.entries()))

logger.debug(`[${requestId}] Fetching templates with params:`, params)

// Check if user is a super user
const { effectiveSuperUser } = await verifyEffectiveSuperUser(session.user.id)
const isSuperUser = effectiveSuperUser
Expand Down Expand Up @@ -187,11 +185,6 @@ export async function POST(request: NextRequest) {
const body = await request.json()
const data = CreateTemplateSchema.parse(body)

logger.debug(`[${requestId}] Creating template:`, {
name: data.name,
workflowId: data.workflowId,
})

// Verify the workflow exists and belongs to the user
const workflowExists = await db
.select({ id: workflow.id })
Expand Down
1 change: 0 additions & 1 deletion apps/sim/app/api/users/me/api-keys/[id]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ export async function DELETE(
const { id } = await params

try {
logger.debug(`[${requestId}] Deleting API key: ${id}`)
const session = await getSession()
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
Expand Down
27 changes: 0 additions & 27 deletions apps/sim/app/api/wand/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,12 +103,10 @@ async function updateUserStatsForWand(
isBYOK = false
): Promise<void> {
if (!isBillingEnabled) {
logger.debug(`[${requestId}] Billing is disabled, skipping wand usage cost update`)
return
}

if (!usage.total_tokens || usage.total_tokens <= 0) {
logger.debug(`[${requestId}] No tokens to update in user stats`)
return
}

Expand Down Expand Up @@ -146,13 +144,6 @@ async function updateUserStatsForWand(
})
.where(eq(userStats.userId, userId))

logger.debug(`[${requestId}] Updated user stats for wand usage`, {
userId,
tokensUsed: totalTokens,
costAdded: costToStore,
isBYOK,
})

await logModelUsage({
userId,
source: 'wand',
Expand Down Expand Up @@ -291,23 +282,8 @@ export async function POST(req: NextRequest) {

messages.push({ role: 'user', content: prompt })

logger.debug(
`[${requestId}] Calling ${useWandAzure ? 'Azure OpenAI' : 'OpenAI'} API for wand generation`,
{
stream,
historyLength: history.length,
endpoint: useWandAzure ? azureEndpoint : 'api.openai.com',
model: useWandAzure ? wandModelName : 'gpt-4o',
apiVersion: useWandAzure ? azureApiVersion : 'N/A',
}
)

if (stream) {
try {
logger.debug(
`[${requestId}] Starting streaming request to ${useWandAzure ? 'Azure OpenAI' : 'OpenAI'}`
)

logger.info(
`[${requestId}] About to create stream with model: ${useWandAzure ? wandModelName : 'gpt-4o'}`
)
Expand All @@ -327,8 +303,6 @@ export async function POST(req: NextRequest) {
headers.Authorization = `Bearer ${activeOpenAIKey}`
}

logger.debug(`[${requestId}] Making streaming request to: ${apiUrl}`)

const response = await fetch(apiUrl, {
method: 'POST',
headers,
Expand Down Expand Up @@ -429,7 +403,6 @@ export async function POST(req: NextRequest) {
try {
parsed = JSON.parse(data)
} catch (parseError) {
logger.debug(`[${requestId}] Skipped non-JSON line: ${data.substring(0, 100)}`)
continue
}

Expand Down
Loading