ai-harness: a thread that a sweep fails to open is never retried (the 30 s wake never reaches the store) #2269
TanStack AI version#
@tanstack/ai-harness 0.4.0, with @tanstack/ai 1.8.0 and @tanstack/ai-persistence 1.1.0. The code involved is unchanged on main (92e8799).
Framework/Library version#
Node.js 24.8, server only (no UI framework)
Describe the bug and the steps to reproduce it#
When host.resumePending (or a worker) takes a log and the thread then fails to open, the docs say the host gives the log back with a wake in 30 seconds, so the next sweep tries again (durable-sessions.md). takeOver means to do this (host.ts):
} catch (error) {
// The log goes back with a wake, so a sweep after the wait tries
// again. With no wake, no sweep lists the log again.
if (isOwn) endSweep(key)
await giveBack(OPEN_RETRY_MS).catch(() => {})
throw error
}
But when the failure comes from SharedLog.write(), which calls SharedLog.fail() (log.ts, log.ts), fail() has already given the ownership back, with no wake (log.ts):
// The host drops this log, so it gives the ownership back.
const { epoch } = this
this.epoch = undefined
if (epoch !== undefined) {
this.ownership.release(this.logId, epoch).catch(() => {})
}
That release removes the log from HostOwnership's owned logs, so the later giveBack(OPEN_RETRY_MS) returns early and never reaches the store (ownership.ts):
const isOwned = epoch !== undefined && this.owned.get(logId) === epoch
if (!isOwned) return Promise.resolve()
The log ends up released with no wake, listLogsWithoutOwner never lists it again, and a thread with an unfinished turn waits until something opens it. A user who opens the thread recovers it, but a background turn or a queued input that only a sweep would resume stays stuck.
I hit this two ways:
- Rolling deploy. A host on a newer harness writes a record type that this version does not know. An old host's sweep takes the log and stops with
LogVersionError, as documented (durable-sessions.md), but then the newer hosts never get the thread back either. - A store error during the sweep. An append that fails twice, as in a database blip, also goes through
write()andfail().
Steps (the repro below, in one process with the memory store):
- Host A starts a turn, and
host.close({ recoverable: true })stops it mid-turn. - Acting as a host on a newer harness, take the log, append
{ type: 'harness.from_a_newer_version' }, and release it withwakeInMs: 0. Withstore-error, skip this step and make host B'sappendthrow instead. - Host B calls
resumePending. The repro records eachreleaseOwnershipcall that B makes. - Move the store clock 31 s ahead and list the logs without an owner.
Expected: B's release carries wakeInMs: 30000, and the list in step 4 includes the log.
Actual (the store-error case differs only in the error and the epoch):
3. B sweep: rejected: LogVersionError: Log :thread-1 has a "harness.from_a_newer_version" record from a newer harness. This host does not write it.
releases B sent to the store: [{"logId":":thread-1","ownerId":"host-…","epoch":3}]
owner record: {"harness":"assistant","ownerId":"host-…","epoch":3,"expiresAt":…,"released":true}
4. logs a sweep 31 s later lists: []
A Postgres LogStore shared by two OS processes shows the same: the log is released with no wake time, and no later sweep takes it.
A possible fix is to let the wake reach the store when fail() released first: for example, leave the release to takeOver while a sweep opens the log, or give fail()'s release a wake when the log still has work. I may be missing a reason for the current order.
Your Minimal, Reproducible Example - (Sandbox Highly Recommended)#
Inline below, one file. In an empty folder, run npm init -y && npm pkg set type=module && npm i @tanstack/ai@1.8.0 @tanstack/ai-harness@0.4.0 @tanstack/ai-persistence@1.1.0 tsx, then npx tsx repro.ts or npx tsx repro.ts store-error.
repro.ts
// @tanstack/ai-harness 0.4.0: a sweep that fails to open a thread gives the
// log back with no wake, so no later sweep lists it again. One process, with
// the memory store.
// npx tsx repro.ts a record from a newer harness version
// npx tsx repro.ts store-error every append of host B fails
import { createHarnessHost, defineHarness, logIdOf } from '@tanstack/ai-harness'
import { memoryLogState, memoryLogStore } from '@tanstack/ai-persistence'
import type { AnyTextAdapter } from '@tanstack/ai'
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
// The store clock: real time plus `skew`, so the end can look 31 s ahead.
let skew = 0
const state = memoryLogState({ now: () => Date.now() + skew })
// A model call that waits until it is aborted, so the turn is still running.
const adapter = {
kind: 'text',
name: 'stub',
model: 'stub',
'~types': {},
chatStream: (options: any) =>
(async function* () {
const signal: AbortSignal | undefined =
options.request?.signal ?? options.abortController?.signal
await new Promise<void>((resolve) =>
signal?.addEventListener('abort', () => resolve(), { once: true }),
)
})(),
structuredOutput: async () => ({ data: {}, rawText: '{}' }),
} as unknown as AnyTextAdapter
const assistant = defineHarness({ name: 'assistant', adapter })
const threadId = 'thread-1'
const logId = logIdOf({ logId: threadId })
// 1. Host A starts a turn. A deploy stops A, which gives the thread back with a wake.
const hostA = createHarnessHost({ persistence: { stores: { log: memoryLogStore({ state }) } } })
const session = await hostA.open(assistant, { threadId })
const sent = Promise.resolve(session.send('Hello')).then(
() => 'settled',
(error) => `rejected: ${error}`,
)
await sleep(100)
await hostA.close({ recoverable: true })
console.log('1. A stopped mid-turn; send:', await sent)
// With `store-error`, step 2 is skipped and every append of B fails instead,
// as in a database outage during the sweep.
const storeError = process.argv[2] === 'store-error'
// 2. A host on a newer harness version takes the thread, writes a record type
// that this version does not know, and is stopped by the deploy too.
if (!storeError) {
const newer = memoryLogStore({ state })
const taken = await newer.acquireOwnership({
logId,
harness: assistant.name,
ownerId: 'newer-host',
ttlMs: 10_000,
})
if (!taken) throw new Error('The newer host did not get the log.')
const kept = state.logs.get(logId)!
await newer.append({
logId,
seq: kept.firstSeq + kept.records.length,
epoch: taken.epoch,
records: [{ type: 'harness.from_a_newer_version' }],
})
await newer.releaseOwnership({ logId, ownerId: 'newer-host', epoch: taken.epoch, wakeInMs: 0 })
console.log('2. newer host wrote a newer record and released with wakeInMs: 0')
}
// 3. Host B, on this version, sweeps. Record each release B sends to the store.
const storeB = memoryLogStore({ state })
if (storeError) {
storeB.append = async () => {
throw new Error('connection reset')
}
}
const releases: Array<unknown> = []
const release = storeB.releaseOwnership.bind(storeB)
storeB.releaseOwnership = (args) => {
releases.push(args)
return release(args)
}
const hostB = createHarnessHost({ persistence: { stores: { log: storeB } } })
const swept = await hostB.resumePending({ harnesses: [assistant] }).then(
(threads) => `took ${threads.length} thread(s)`,
(error) =>
`rejected: ${(error instanceof AggregateError ? error.errors : [error]).map(String).join('; ')}`,
)
await sleep(100)
console.log('3. B sweep:', swept)
console.log(' releases B sent to the store:', JSON.stringify(releases))
console.log(' owner record:', JSON.stringify(state.owners.get(logId)))
await hostB.close()
// 4. Expected: the 30 s wake of `takeOver`, so a sweep after it lists the log.
skew = 31_000
const listed = await storeB.listLogsWithoutOwner({ limit: 10, harnesses: [assistant.name] })
console.log('4. logs a sweep 31 s later lists:', JSON.stringify(listed))
Terms & Code of Conduct#
- I agree to follow this project's Code of Conduct
- I understand that if my bug cannot be reliable reproduced in a debuggable environment, it will probably not be fixed and this issue may even be closed.
tanstack-source added labelsbug
pcbeingused33(GitHub profile, opens in a new tab) linked this to #2270
github-actions[bot](GitHub profile, opens in a new tab) assignedtombeckenham
github-actions[bot](GitHub profile, opens in a new tab) added labelshas-pr
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer
AlemTuzlak closed this
Sign in to join this conversation.
A one-line change fixes both cases in the repro:
SharedLog.fail()gives the ownership back with the retry wake.Patched into the built 0.4.0 (
dist/esm/log.js), B's release carries the wake, and the sweep 31 s later lists the log again, withLogVersionErrorand withstore-error:Because the change is in
fail(), it also covers a write that fails outside a sweep. The cost is that a failed log with no work left is listed again after 30 s.