Skip to content

Commit 158f5fa

Browse files
authored
fix(file-search): claim a file write that lands on an owner the backfill already queued (#9666)
* fix(file-search): claim a file write that lands on an owner the backfill already queued Backfill reconciliation wake-ups enter the owner queue as if just dispatched so they rotate in behind owners woken for a write. A write that landed while such a row was still queued only advanced its updated_at through the file trigger's upsert, so it kept the reconciliation stamp and waited behind every older-stamped owner. The same held for an owner that was served, left queued with work, and then woken again. Claims now take owners woken since their last dispatch first: never dispatched, or updated_at later than last_dispatched_at, which every real wake-up (file write, released claim, reaped claim, artifact-ready requeue) advances and a reconciliation wake-up never does; it no longer touches an owner already queued. Within each group the dispatch-age rotation is unchanged. Queue timestamps the comparison reads come from the transaction clock, the same clock the trigger writes. * fix(file-search): rotate a woken owner whose slots are full by dispatch age An owner already holding both of its outstanding claims can claim nothing, but a write between passes kept marking it woken, so with little global capacity left it took every owner turn and the free slot went unused. Woken owners now go first only while they have a free slot; a full owner keeps the dispatch-age rotation it had before. Also gives the due-reconcile work-check case the same one-minute margin as its not-yet-due counterpart: exactly at the interval it compared a database timestamp with the application clock and flaked on skew.
1 parent 35ab8fe commit 158f5fa

4 files changed

Lines changed: 115 additions & 38 deletions

File tree

‎apps/sim/lib/workspace-files/search/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,6 @@ The design uses PostgreSQL's documented [TOAST behavior](https://www.postgresql.
7171

7272
Migration `0426_file_search_owner_scope.sql` adds canonical workspace/Project ownership to the existing build, revision, and chunk pipeline. Legacy workspace inserts are translated by triggers, and the existing workspace trigram index remains usable. Project rows use a separate owner-scoped trigram index on the same chunk table. Organizations and personal users are not enabled search owners.
7373

74-
The new `file_search_dispatch_queue` replaces the workspace-keyed scheduler because older workers cannot decode a Project without a workspace. During expansion, workspace mutations enqueue both queues, while the new dispatcher reads the owner queue. Both deployments share the dispatcher lock, revision claim token, build lease, and publication fence. Drain old app dispatchers and Trigger workers/retries before enabling Project dispatch. Retire the legacy queue and its dual enqueue in a later contract deploy; they are not a second indexing pipeline. The `file-search-owners-v3` cursor performs bounded owner/file keyset backfill and hourly reconciliation without rewriting extracted text in the migration. Each claim pass takes owners never dispatched first, so the owners a backfill page wakes enter the queue as if just dispatched: a page of reconciliation wake-ups rotates in by dispatch age behind the owners the file trigger woke for a write, instead of delaying them by several passes.
74+
The new `file_search_dispatch_queue` replaces the workspace-keyed scheduler because older workers cannot decode a Project without a workspace. During expansion, workspace mutations enqueue both queues, while the new dispatcher reads the owner queue. Both deployments share the dispatcher lock, revision claim token, build lease, and publication fence. Drain old app dispatchers and Trigger workers/retries before enabling Project dispatch. Retire the legacy queue and its dual enqueue in a later contract deploy; they are not a second indexing pipeline. The `file-search-owners-v3` cursor performs bounded owner/file keyset backfill and hourly reconciliation without rewriting extracted text in the migration. Claims take owners woken since their last dispatch first (`wokenSinceDispatch` in `dispatcher.ts`); backfill wake-ups enter as if just dispatched and never touch an owner already queued, so a page of them cannot delay a file write by several passes.
7575

7676
Generated document indexing never executes source. A cached artifact must match its owner and current input manifest. Each published build stores at most 500 input identities. Queries exclude a build when any input is changed, archived, deleted, or outside the owner, and report it as pending coverage. Input mutations wake their owner queue; the dispatcher retires stale manifests in bounded batches before rebuilding. Expired build cleanup also removes its dependency records. A cache miss indexes the stored generation source as text until an authorized rendering path creates a current artifact.

‎apps/sim/lib/workspace-files/search/artifact-ready.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -162,12 +162,13 @@ export async function markFileSearchArtifactReadyInTx(
162162
},
163163
setWhere: predicate,
164164
})
165+
// The dispatcher stamps queue rows with the transaction clock and claims rows touched since.
165166
await tx
166167
.insert(fileSearchDispatchQueue)
167-
.values({ ...owner, enqueuedAt: now, updatedAt: now })
168+
.values({ ...owner, enqueuedAt: now, updatedAt: sql`now()` })
168169
.onConflictDoUpdate({
169170
target: [fileSearchDispatchQueue.entityType, fileSearchDispatchQueue.entityId],
170-
set: { updatedAt: now },
171+
set: { updatedAt: sql`now()` },
171172
})
172173
return true
173174
}

‎apps/sim/lib/workspace-files/search/dispatcher.integration.ts‎

Lines changed: 66 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import {
3131
FILE_SEARCH_INDEX_DISPATCH_WORKSPACES,
3232
FILE_SEARCH_INDEX_MAX_OUTSTANDING,
3333
FILE_SEARCH_INDEX_STALE_DISPATCH_MS,
34+
FILE_SEARCH_INDEX_WORKSPACE_OUTSTANDING,
3435
FILE_SEARCH_RECONCILE_INTERVAL_MS,
3536
} from '@/lib/workspace-files/search/constants'
3637
import {
@@ -408,33 +409,80 @@ describe('workspace file search dispatch PostgreSQL deadlines', () => {
408409
})
409410
}
410411

411-
it('serves an owner woken by a file write ahead of a backfill page of reconciliation wake-ups', async () => {
412-
const wakeUps = FILE_SEARCH_INDEX_DISPATCH_WORKSPACES * 2 + 50
413-
await seedIndexedOwners('reconciled-', wakeUps)
414-
const first = await prepareWorkspaceFileSearchDispatch()
415-
expect(first.backfilledFiles).toBe(wakeUps)
416-
expect(first.payloads).toEqual([])
412+
/** Fills global capacity with claims of an unqueued owner, leaving `slots` free. */
413+
async function leaveSlots(slots: number) {
414+
await seedQueue('workspace-active', 0, FILE_SEARCH_INDEX_MAX_OUTSTANDING - slots)
415+
await connection`DELETE FROM file_search_dispatch_queue WHERE entity_id = 'workspace-active'`
416+
}
417417

418-
await writeFile('written-workspace')
419-
const next = await prepareWorkspaceFileSearchDispatch()
420-
expect(next.payloads.map((payload) => payload.fileId)).toEqual(['written-workspace-written'])
418+
const wakeUps = FILE_SEARCH_INDEX_DISPATCH_WORKSPACES * 2 + 50
419+
it.each([
420+
['an owner the page did not reach', 'written-workspace', 0],
421+
['an owner the page left queued', `reconciled-${String(wakeUps).padStart(4, '0')}`, 1],
422+
])(
423+
'serves a file write to %s ahead of a backfill page of reconciliation wake-ups',
424+
async (_, owner, queuedRows) => {
425+
await seedIndexedOwners('reconciled-', wakeUps)
426+
const first = await prepareWorkspaceFileSearchDispatch()
427+
expect(first.backfilledFiles).toBe(wakeUps)
428+
expect(first.payloads).toEqual([])
429+
// A queued owner's write takes the conflict path; an unqueued owner's takes the insert path.
430+
const [queued] = await connection`SELECT count(*)::int AS count
431+
FROM file_search_dispatch_queue WHERE entity_id = ${owner}`
432+
expect(queued.count).toBe(queuedRows)
433+
434+
await writeFile(owner)
435+
const next = await prepareWorkspaceFileSearchDispatch()
436+
expect(next.payloads.map((payload) => payload.fileId)).toEqual([`${owner}-written`])
437+
}
438+
)
439+
440+
it('keeps a queued reconciliation wake-up behind woken work when the backfill passes it again', async () => {
441+
await leaveSlots(1)
442+
// Queued by an earlier page, with nothing to claim; its stamp is older than the woken owner's.
443+
await seedIndexedOwners('reconciled-', 1)
444+
await connection`INSERT INTO file_search_dispatch_queue
445+
(entity_type, entity_id, enqueued_at, updated_at, last_dispatched_at)
446+
VALUES ('workspace', 'reconciled-0001', now() - interval '2 hours',
447+
now() - interval '2 hours', now() - interval '2 hours')`
448+
await seedQueue('woken-workspace', 1)
449+
await connection`UPDATE file_search_dispatch_queue
450+
SET last_dispatched_at = now() - interval '1 hour' WHERE entity_id = 'woken-workspace'`
451+
await connection`UPDATE workspace_file_search_backfill SET completed_at = NULL`
452+
453+
const result = await prepareWorkspaceFileSearchDispatch()
454+
expect(result.backfilledFiles).toBeGreaterThan(0)
455+
expect(result.payloads.map((payload) => payload.fileId)).toEqual(['woken-workspace-000001'])
456+
})
457+
458+
it('rotates a woken owner whose slots are full behind an older waiting owner', async () => {
459+
await leaveSlots(1 + FILE_SEARCH_INDEX_WORKSPACE_OUTSTANDING)
460+
// Both of its slots are taken and it has more files; a write woke it after its last dispatch.
461+
await seedQueue('busy-workspace', 3, FILE_SEARCH_INDEX_WORKSPACE_OUTSTANDING)
462+
await connection`UPDATE file_search_dispatch_queue
463+
SET last_dispatched_at = now() - interval '10 minutes' WHERE entity_id = 'busy-workspace'`
464+
await seedQueue('waiting-workspace', 1)
465+
await connection`UPDATE file_search_dispatch_queue SET last_dispatched_at = now() - interval '1 hour',
466+
updated_at = now() - interval '1 hour' WHERE entity_id = 'waiting-workspace'`
467+
468+
const result = await prepareWorkspaceFileSearchDispatch()
469+
expect(result.payloads.map((payload) => payload.fileId)).toEqual(['waiting-workspace-000001'])
421470
})
422471

423472
it('serves a fresh write before work the backfill found, then the backfill work', async () => {
424-
await seedQueue('workspace-active', 0, FILE_SEARCH_INDEX_MAX_OUTSTANDING)
425-
await connection`DELETE FROM file_search_dispatch_queue WHERE entity_id = 'workspace-active'`
473+
await leaveSlots(0)
426474
await connection`UPDATE workspace_file_search_backfill SET completed_at = NULL`
427475
await connection`INSERT INTO workspace_files (id, workspace_id, context, content_updated_at)
428476
VALUES ('backfill-found-file', 'backfill-found', 'workspace', '2026-09-16')`
429-
/** No capacity: the page seeds and queues the unindexed file's owner but claims nothing. */
477+
// No capacity: the page seeds and queues the unindexed file's owner but claims nothing.
430478
const seeded = await prepareWorkspaceFileSearchDispatch()
431479
expect(seeded.backfilledFiles).toBeGreaterThan(0)
432480
expect(seeded.payloads).toEqual([])
433481

434482
await writeFile('fresh-write')
435483
const served: string[] = []
436484
for (let pass = 0; pass < 2; pass++) {
437-
/** Free exactly one slot, so each pass claims for one owner. */
485+
// Free exactly one slot, so each pass claims for one owner.
438486
await connection`UPDATE workspace_file_search_revision SET status = 'ready'
439487
WHERE file_id = (SELECT file_id FROM workspace_file_search_revision
440488
WHERE status = 'pending' AND dispatched_at IS NOT NULL ORDER BY file_id LIMIT 1)`
@@ -445,9 +493,8 @@ describe('workspace file search dispatch PostgreSQL deadlines', () => {
445493
})
446494

447495
it('leaves an owner queued by a file write at the front when a backfill page passes it', async () => {
448-
await seedQueue('workspace-active', 0, FILE_SEARCH_INDEX_MAX_OUTSTANDING - 1)
449-
await connection`DELETE FROM file_search_dispatch_queue WHERE entity_id = 'workspace-active'`
450-
/** Queued first and served an hour ago: it wins the single slot only if the write is demoted. */
496+
await leaveSlots(1)
497+
// Queued first and served an hour ago: it wins the single slot only if the write is demoted.
451498
await seedQueue('earlier-served', 1)
452499
await connection`UPDATE file_search_dispatch_queue
453500
SET last_dispatched_at = now() - interval '1 hour' WHERE entity_id = 'earlier-served'`
@@ -995,8 +1042,10 @@ describe('workspace file search dispatch PostgreSQL deadlines', () => {
9951042
},
9961043
{
9971044
work: 'a backfill reconcile that is due',
1045+
// A minute past the interval, mirroring the not-yet-due case: the check compares a database
1046+
// timestamp with the application clock, so exactly at the boundary it depends on clock skew.
9981047
seed: () => connection`UPDATE workspace_file_search_backfill
999-
SET completed_at = now() - make_interval(secs => ${reconcileSeconds})`,
1048+
SET completed_at = now() - make_interval(secs => ${reconcileSeconds + 60})`,
10001049
},
10011050
{
10021051
work: 'a queued workspace',

‎apps/sim/lib/workspace-files/search/dispatcher.ts‎

Lines changed: 45 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -171,11 +171,39 @@ function queuedOwnerFilter(owners: readonly EditableFileOwner[]): SQL | undefine
171171
return or(...owners.map(queuedOwner))
172172
}
173173

174+
/**
175+
* The transaction's start time. Queue rows compare `updated_at` with `last_dispatched_at`, and
176+
* the `workspace_file_search_mark_pending` trigger writes `updated_at` the same way, so both sides
177+
* share one clock.
178+
*/
179+
const transactionNow = sql`now()`
180+
181+
/**
182+
* Whether an owner was woken after its last dispatch: never dispatched, or touched since. A file
183+
* write, a released claim, and a reaped claim advance `updated_at`; a claim stamps both columns
184+
* with one time, and a reconciliation wake-up enters with them equal. A write whose transaction
185+
* began before the claim that stamped its owner reads as earlier and waits one rotation.
186+
*/
187+
const wokenSinceDispatch = sql`(${fileSearchDispatchQueue.lastDispatchedAt} IS NULL OR ${fileSearchDispatchQueue.updatedAt} > ${fileSearchDispatchQueue.lastDispatchedAt})`
188+
189+
/**
190+
* Whether the queued owner already holds every claim it may have outstanding. Such an owner can
191+
* claim nothing this pass, so being woken must not put it ahead of owners that can: it keeps
192+
* rotating by dispatch age, or a busy owner written to between passes would take every turn while
193+
* the free global capacity goes unused.
194+
*/
195+
const ownerSlotsFull = sql`(SELECT count(*) FROM (
196+
SELECT 1 FROM workspace_file_search_revision active
197+
WHERE coalesce(active.entity_type, 'workspace') = ${fileSearchDispatchQueue.entityType}
198+
AND coalesce(active.entity_id, active.workspace_id) = ${fileSearchDispatchQueue.entityId}
199+
AND active.status = 'pending' AND active.dispatched_at IS NOT NULL
200+
LIMIT ${FILE_SEARCH_INDEX_WORKSPACE_OUTSTANDING}
201+
) active_claims) >= ${FILE_SEARCH_INDEX_WORKSPACE_OUTSTANDING}`
202+
174203
/**
175204
* Queues owners for the claim pass. A `reconciliation` wake-up, from the backfill walk, enters as
176-
* if just dispatched: claims take owners never dispatched first, so marking it served keeps a page
177-
* of owners with nothing new behind the owners the file trigger woke for a write, and its row still
178-
* rotates in by dispatch age. An owner already queued keeps its place either way.
205+
* if just dispatched and never touches an owner already queued, so a page of owners with nothing
206+
* new rotates in behind the owners woken for work.
179207
*/
180208
async function enqueueOwners(
181209
tx: DbTransaction,
@@ -185,20 +213,18 @@ async function enqueueOwners(
185213
): Promise<void> {
186214
const unique = [...new Map(owners.map((owner) => [JSON.stringify(owner), owner])).values()]
187215
if (unique.length === 0) return
188-
await tx
189-
.insert(fileSearchDispatchQueue)
190-
.values(
191-
unique.map((owner) => ({
192-
...owner,
193-
enqueuedAt: now,
194-
updatedAt: now,
195-
lastDispatchedAt: reconciliation ? now : null,
196-
}))
197-
)
198-
.onConflictDoUpdate({
199-
target: [fileSearchDispatchQueue.entityType, fileSearchDispatchQueue.entityId],
200-
set: { updatedAt: now },
201-
})
216+
const target = [fileSearchDispatchQueue.entityType, fileSearchDispatchQueue.entityId]
217+
const insert = tx.insert(fileSearchDispatchQueue).values(
218+
unique.map((owner) => ({
219+
...owner,
220+
enqueuedAt: now,
221+
updatedAt: transactionNow,
222+
lastDispatchedAt: reconciliation ? transactionNow : null,
223+
}))
224+
)
225+
await (reconciliation
226+
? insert.onConflictDoNothing({ target })
227+
: insert.onConflictDoUpdate({ target, set: { updatedAt: transactionNow } }))
202228
}
203229

204230
/**
@@ -675,6 +701,7 @@ export async function prepareWorkspaceFileSearchDispatch(
675701
})
676702
.from(fileSearchDispatchQueue)
677703
.orderBy(
704+
sql`(${wokenSinceDispatch} AND NOT ${ownerSlotsFull}) DESC`,
678705
sql`${fileSearchDispatchQueue.lastDispatchedAt} ASC NULLS FIRST`,
679706
asc(fileSearchDispatchQueue.enqueuedAt),
680707
asc(fileSearchDispatchQueue.entityType),
@@ -687,7 +714,7 @@ export async function prepareWorkspaceFileSearchDispatch(
687714
// Rotate busy owners too; otherwise a full locked page starves every later owner.
688715
await tx
689716
.update(fileSearchDispatchQueue)
690-
.set({ lastDispatchedAt: now, updatedAt: now })
717+
.set({ lastDispatchedAt: transactionNow, updatedAt: transactionNow })
691718
.where(queuedOwnerFilter(candidates))
692719
}
693720
const owners = await lockFileSearchOwners(tx, candidates, { skipBusy: true })

0 commit comments

Comments
 (0)