mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-11-27 17:00:37 +00:00
fix(runtime): keep run-input appends off the run-change clock (#8479)
`mutate_run_inputs` calls `_next_change_seq` and drops the return value. It
is the only one of the sixteen call sites in that module that does not
assign it, and the only column the method writes is `run_inputs_json`, so
the position it takes never reaches a row: after one append the clock moves
1 -> 2 while the run row's `change_seq` stays at 1.
The clock is a single row, so that write is not free: every queued or
steering message -- `RunInputs.submit`, `acknowledge` and `close` all land
here, and `POST /api/runs/{id}/inputs` reaches it once per message -- buys a
position nothing reads while serializing against every other run mutation in
the database, and against every other writer on SQLite. Progress snapshots,
lease heartbeats and deletes already stay off the clock for the same reason
(#5516), and an append that rewrites one JSON column which no changed-run
cursor observes belongs with them.
The append still reads the row before it writes it, so SQLite needs its
write lock up front; the clock bump had been supplying that as a side
effect. `BEGIN IMMEDIATE` takes it directly, matching `delete` and
`delete_by_thread`. Removing the clock without it would trade a wasted write
for lost updates -- eight concurrent appends leave one item behind and
report no error.
This commit is contained in:
parent
ee54c96300
commit
9bd2bfa859
@ -191,13 +191,18 @@ backend-owned `(change_seq, run_id)` key rather than timestamps or per-thread
|
||||
event sequence numbers. The singleton SQL clock allocates positions in the same
|
||||
transaction as each public record mutation; memory uses a process-local counter.
|
||||
The clock row serializes position-bearing SQL mutations globally until their
|
||||
transactions commit, so every mutator must acquire it before any run-row lock.
|
||||
transactions commit, so every position-bearing mutator must acquire it before
|
||||
any run-row lock.
|
||||
An atomic thread operation uses one position for its interrupted rows and new
|
||||
row, with `run_id` ordering ties. High-frequency progress snapshots and lease
|
||||
heartbeats do not advance this position: they are not lifecycle-discovery
|
||||
signals, progress evidence remains available from the event stream, and
|
||||
excluding them bounds clock contention. A later lifecycle change exposes the
|
||||
run row's latest `updated_at` and accumulated progress fields to internal readers.
|
||||
row, with `run_id` ordering ties. High-frequency progress snapshots, lease
|
||||
heartbeats and run-input appends do not advance this position: they are not
|
||||
lifecycle-discovery signals, progress evidence remains available from the event
|
||||
stream, and excluding them bounds clock contention. A run-input append writes
|
||||
only `run_inputs_json`, so no changed-run cursor could read back a position it
|
||||
took; because it reads the row before it writes it, on SQLite it takes the
|
||||
write lock up front with `BEGIN IMMEDIATE` instead. A later lifecycle change
|
||||
exposes the run row's latest `updated_at` and accumulated progress fields to
|
||||
internal readers.
|
||||
Rows from before the migration retain `change_seq=0` and page deterministically
|
||||
by run id. Because a later mutation only moves a row forward, concurrent paging
|
||||
may replay a run but cannot move an unseen run behind the committed cursor.
|
||||
|
||||
@ -53,9 +53,15 @@ class RunRepository(RunStore):
|
||||
from deerflow.runtime.runs.inputs import InputConflict, empty_input_state
|
||||
|
||||
async with self._sf() as session:
|
||||
# Preserve the existing global-clock -> row lock order (SQLite's
|
||||
# first write serializes peer connections as well).
|
||||
await self._next_change_seq(session)
|
||||
# An input append rewrites ``run_inputs_json`` only, so it publishes
|
||||
# no change position and no changed-run cursor observes it -- like a
|
||||
# progress snapshot, it is not a lifecycle-discovery signal, and
|
||||
# ``delete``/``delete_by_thread`` likewise stay off the clock
|
||||
# (#5516). It does read before it writes, though, so SQLite still
|
||||
# needs its write lock up front; ``BEGIN IMMEDIATE`` takes it
|
||||
# directly instead of borrowing it from a discarded clock bump.
|
||||
if session.bind.dialect.name == "sqlite":
|
||||
await session.execute(text("BEGIN IMMEDIATE"))
|
||||
row = (await session.execute(select(RunRow).where(RunRow.run_id == run_id).with_for_update())).scalar_one_or_none()
|
||||
if row is None or (user_id is not None and row.user_id != user_id):
|
||||
raise InputConflict("Run not found")
|
||||
|
||||
@ -142,6 +142,49 @@ async def test_concurrent_input_retries_are_applied_once(input_store):
|
||||
assert len((await inputs.read())["items"]) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_concurrent_distinct_inputs_are_all_stored(input_store):
|
||||
"""Concurrent appends must not overwrite each other's ``run_inputs_json``.
|
||||
|
||||
An append reads the row before it writes it, so the store has to serialize
|
||||
peers itself; without that, every concurrent append starts from the same
|
||||
state and the last commit wins.
|
||||
"""
|
||||
inputs = RunInputs(input_store, "run", USER_ID, "worker")
|
||||
await asyncio.gather(*(inputs.submit(f"i{n}", f"One correction {n}", "queue") for n in range(8)))
|
||||
assert sorted(item["id"] for item in (await inputs.read())["items"]) == [f"i{n}" for n in range(8)]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_input_append_does_not_take_the_run_change_clock(tmp_path):
|
||||
"""An input append rewrites ``run_inputs_json`` and publishes no position.
|
||||
|
||||
The clock is a single global row, so bumping it without writing the value
|
||||
onto the run row makes every queued or steering message contend for a row
|
||||
that no changed-run cursor can observe afterwards.
|
||||
"""
|
||||
from deerflow.persistence.run.model import RunChangeClockRow
|
||||
|
||||
engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'clock.db'}")
|
||||
try:
|
||||
async with engine.begin() as connection:
|
||||
await connection.run_sync(Base.metadata.create_all)
|
||||
store = RunRepository(async_sessionmaker(engine, expire_on_commit=False))
|
||||
await store.put("run", thread_id="thread", user_id=USER_ID, status="running")
|
||||
|
||||
async def position():
|
||||
async with engine.connect() as connection:
|
||||
clock = await connection.scalar(sa.select(RunChangeClockRow.value).where(RunChangeClockRow.id == 1))
|
||||
return clock, (await store.get("run", user_id=USER_ID))["change_seq"]
|
||||
|
||||
before = await position()
|
||||
queued = await RunInputs(store, "run", USER_ID).submit("q", "Make a presentation", "queue")
|
||||
assert queued["id"] == "q"
|
||||
assert await position() == before
|
||||
finally:
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_removed_steer_cannot_be_consumed_and_claimed_steer_cannot_be_removed(input_store):
|
||||
inputs = RunInputs(input_store, "run", USER_ID, "worker")
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user