Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
23 changes: 21 additions & 2 deletions docs/tasks.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,9 @@ the row recording a task's creation, so an aging calculation can tell
"created here" from "moved here".

Recording happens inside the same transaction as the status write, from all
three paths that can change one: `update_task_status`, `move_task`, and the
full-row `upsert_task` (which is how `task_update` flips status when it also
three paths that can change one: `transition_task` (which `update_task_status`
wraps), `move_task`, and the full-row `upsert_task` (which is how
`task_update` flips status when it also
writes a note). A no-op transition records nothing — that single rule is
what keeps `reindex()` from doubling the table on every run, since it
rewrites every row with the status it already had. The one case where
Expand All @@ -144,6 +145,24 @@ detail view. Tasks whose last transition predates v044 report no entry time
rather than a guessed one, so the UI stays silent instead of showing an age
that isn't true.

### Revisions (`revision`)

Every write to a task row advances `tasks.revision` by one, added in
migration v052. The row routes return it, and `task_read` ends with a
`<!-- nerve: revision=N ... -->` line that `task_write` strips again.

Pass the value you read as `expect_revision` to `task_update` or `task_done`
to make the write conditional: if the row has changed since, nothing is
written and the tool reports a conflict, so re-read and retry. Without it,
writes stay last-write-wins, except that a reopen is always conditional on
the task still being done. In code, `upsert_task`, `update_task_tags` and
`transition_task` take the same argument and return `False` instead of
writing.

The fence protects the row. Two writers that both pass it can still lose one
another's edits to the markdown body, since each builds the new body from its
own read of the file.

### Live Updates

Every task mutation broadcasts a `task_updated` WebSocket event on the
Expand Down
228 changes: 165 additions & 63 deletions nerve/agent/tools/handlers/tasks.py

Large diffs are not rendered by default.

11 changes: 11 additions & 0 deletions nerve/agent/tools/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,15 @@
"required": [],
}

# Presence, not truthiness, like deadline/tags below: no "default".
_EXPECT_REVISION = {
"type": "integer",
"description": "Optional fence: apply only if the task's current revision equals this "
"value (from task_read). On a mismatch neither the task row nor its file "
"is written and the conflict is reported; re-read and retry. Omit for "
"last-write-wins.",
}

TASK_UPDATE_SCHEMA = {
"type": "object",
"properties": {
Expand Down Expand Up @@ -128,6 +137,7 @@
"description": "New task title. Updates the H1 heading in the markdown file and the SQLite index.",
"default": "",
},
"expect_revision": _EXPECT_REVISION,
},
"required": ["task_id"],
}
Expand Down Expand Up @@ -161,6 +171,7 @@
"description": "Completion note",
"default": "",
},
"expect_revision": _EXPECT_REVISION,
},
"required": ["task_id"],
}
Expand Down
13 changes: 0 additions & 13 deletions nerve/db/accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,9 +299,6 @@ async def _bootstrap_first_account(
f"got {credential_source!r}"
)
async with self._atomic():
# Take the write lock before the count, so two processes cannot
# both see an empty table.
await self.db.execute("BEGIN IMMEDIATE")
if await self._count_accounts():
return BootstrapAccount(created=False)
actor_id, account_id, now = _new_id(), _new_id(), _now()
Expand Down Expand Up @@ -368,7 +365,6 @@ async def complete_passwordless_setup(
credential. The caller checks ``auth.password_hash``.
"""
async with self._atomic():
await self.db.execute("BEGIN IMMEDIATE")
async with self.db.execute(
"SELECT credential_source FROM accounts"
) as cursor:
Expand Down Expand Up @@ -403,11 +399,6 @@ async def create_managed_account(

actor_id, account_id = _new_id(), _new_id()
async with self._atomic():
# The write lock up front: the guards below are read-then-write, and
# a deferred transaction would let two callers both read a state
# that permits the insert and then both perform it.
await self.db.execute("BEGIN IMMEDIATE")

async with self.db.execute(
"SELECT username, credential_source FROM accounts"
) as cursor:
Expand Down Expand Up @@ -482,7 +473,6 @@ async def update_account_login(
return await self.get_account(account_id)

async with self._atomic():
await self.db.execute("BEGIN IMMEDIATE")
async with self.db.execute(
"SELECT 1 FROM accounts WHERE id = ?", (account_id,)
) as cursor:
Expand Down Expand Up @@ -567,7 +557,6 @@ async def claim_sole_account(
username = None

async with self._atomic():
await self.db.execute("BEGIN IMMEDIATE")
async with self.db.execute(
"SELECT id, actor_id, credential_source FROM accounts"
) as cursor:
Expand Down Expand Up @@ -618,7 +607,6 @@ async def claim_sole_account(
async def disable_account(self, account_id: str) -> dict | None:
"""Idempotently disable an account unless it is the last enabled one."""
async with self._atomic():
await self.db.execute("BEGIN IMMEDIATE")
account = await self.get_account(account_id)
if account is None:
return None
Expand All @@ -644,7 +632,6 @@ async def disable_account(self, account_id: str) -> dict | None:
async def enable_account(self, account_id: str) -> dict | None:
"""Re-enable an account. Idempotent; ``None`` if there is no such account."""
async with self._atomic():
await self.db.execute("BEGIN IMMEDIATE")
account = await self.get_account(account_id)
if account is None:
return None
Expand Down
8 changes: 7 additions & 1 deletion nerve/db/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -548,7 +548,9 @@ async def _atomic(self) -> AsyncIterator[None]:
"""Serialize a multi-statement write and make it a real transaction.

Once a coroutine begins a multi-statement write, no other coroutine
can interleave writes before the commit. The body's statements are
can interleave writes before the commit. The transaction begins before
the body runs, so its reads and the writes based on them are one
transaction against other connections too. The body's statements are
committed on success and rolled back on any exception — including
task cancellation — so a failed body neither half-commits nor leaves
the shared connection inside an open (poisoned) transaction.
Expand All @@ -559,6 +561,10 @@ async def _atomic(self) -> AsyncIterator[None]:
async with self._write_lock:
await self._heal_leaked_txn()
try:
# IMMEDIATE takes the database write lock before the first read.
# A deferred BEGIN would pin a read snapshot that another
# connection's commit turns into SQLITE_BUSY_SNAPSHOT.
await self.db.execute("BEGIN IMMEDIATE")
yield
# Shield so a cancellation arriving mid-commit cannot abandon
# a half-finished transaction: the inner task runs to
Expand Down
27 changes: 27 additions & 0 deletions nerve/db/migrations/v052_task_revision.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""V52: a per-row revision token for tasks.

The task tools read a row, edit the markdown, then write the row back from
that read, and ``upsert_task`` replaced the row unconditionally. A writer
landing in between was silently undone: a completion could revert to its old
status with ``file_path`` pointing back into active/.

``revision`` starts at 1 and every write to the row advances it by one, so a
caller can pass the value it read as ``expect_revision`` and have the write
refused once the row has moved on. ``updated_at`` cannot serve: it is a
wall-clock value rather than a counter, and not every write advances it.

``NOT NULL DEFAULT 1`` fills existing rows, so there is no backfill.
"""

from __future__ import annotations

import logging

import aiosqlite

logger = logging.getLogger(__name__)


async def up(db: aiosqlite.Connection) -> None:
await db.execute("ALTER TABLE tasks ADD COLUMN revision INTEGER NOT NULL DEFAULT 1")
logger.info("v052: added tasks.revision")
Loading
Loading