From 9bd2bfa859fc185508387c32e27d922fac1f09ff Mon Sep 17 00:00:00 2001 From: Heo Hao <130041734+Shelden-Hao@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:50:30 +0800 Subject: [PATCH] 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. --- backend/docs/runtime-guidance-details.md | 17 +++++--- .../harness/deerflow/persistence/run/sql.py | 12 ++++-- backend/tests/test_run_inputs.py | 43 +++++++++++++++++++ 3 files changed, 63 insertions(+), 9 deletions(-) diff --git a/backend/docs/runtime-guidance-details.md b/backend/docs/runtime-guidance-details.md index 61354b61a0..de45fb8ccf 100644 --- a/backend/docs/runtime-guidance-details.md +++ b/backend/docs/runtime-guidance-details.md @@ -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. diff --git a/backend/packages/harness/deerflow/persistence/run/sql.py b/backend/packages/harness/deerflow/persistence/run/sql.py index 6dafee2dbe..60211d012a 100644 --- a/backend/packages/harness/deerflow/persistence/run/sql.py +++ b/backend/packages/harness/deerflow/persistence/run/sql.py @@ -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") diff --git a/backend/tests/test_run_inputs.py b/backend/tests/test_run_inputs.py index 44e1d77664..4971afa7d8 100644 --- a/backend/tests/test_run_inputs.py +++ b/backend/tests/test_run_inputs.py @@ -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")