Skip to content

Commit 0c30c93

Browse files
committed
Only real moves in the log, a row lock instead of a version, progress and progress_all in place of advance
1 parent 1b78c17 commit 0c30c93

12 files changed

Lines changed: 436 additions & 277 deletions

File tree

‎CLAUDE.md‎

Lines changed: 26 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -46,15 +46,20 @@ by whoever knows something new. A machine is three plain Python things.
4646
| `fire(id, step, entity=)` | the same, on the entity already in hand instead of `load(id)` (`brief` takes it too) |
4747
| `fire(id, step, answer=)` | decides a `Decide` in the model's place; no model call, the prompt doesn't run |
4848
| `brief(id, step)` | the `Brief` a `Decide` would give the model: instructions, prompt, choices, schema, tools |
49-
| `advance()` | per unfinished entity, tries the steps out of its state in list order and stops at the first that doesn't return `None`: at most one move per entity per call |
49+
| `progress(id)` | moves one entity until it rests: each round tries the steps out of its state in list order on the entity loaded afresh, and commits its move; it stops when no step moves it, or after a move back to a state this call already left |
50+
| `progress_all()` | per unfinished entity, tries the steps out of its state in list order and stops at the first that doesn't return `None`: at most one move per entity per call, each entity locked and committed on its own |
5051
| `state_of(id)`, `in_state(state)`, `history(id)` | reads |
5152
| `graph()` | states and rows as data |
5253

53-
A result outside the step's rows, or one that isn't a state, is logged as a refused `Move`
54-
(`applied=False`, with a `reason`) and never applied. `fire` raises `TransitionError` when the
55-
move can't even be tried (unknown step, entity not started, step doesn't leave the state). Entity
56-
ids are stored as text, so `load` receives a string. The machine never opens a transaction around
57-
a step: a step may send an email or call a model.
54+
**Every row in the log is a move that happened.** `fire` raises `TransitionError` and writes
55+
nothing when the move can't be made: an unknown step, an entity not started, a step that doesn't
56+
leave the state, a result outside the step's rows or not a state at all (a bug in the step), an
57+
answer that doesn't validate. Entity ids are stored as text, so `load` receives a string.
58+
59+
**The entity is locked from read to write.** `fire` (and each round of `progress` and
60+
`progress_all`) runs inside the backend's `lock(machine, entity)`: it reads the current state,
61+
runs the step and writes the move there, so a second caller waits and reads the state the first
62+
left. A step that raises undoes the move and, on the Django backend, the step's own writes.
5863

5964
## Decide
6065

@@ -70,7 +75,7 @@ its output type, with the model check deferred so no key is needed until it runs
7075
afterwards either way. A model that keeps answering outside them raises Pydantic AI's
7176
`UnexpectedModelBehavior`, and nothing is logged.
7277
- **Answer**: `Decide.parse(answer, targets)` validates a dict, a JSON object or a bare state value
73-
against the same narrowed schema. The machine logs an invalid one as a refused move.
78+
against the same narrowed schema. The machine raises `TransitionError` on an invalid one.
7479
- **Logged**: `decided_by` is `llm:<provider>:<model>` for a run, `agent` for an answer and
7580
`code` for a function, and `Move.decision` holds the whole `Decision`.
7681
- `Brief.instructions` and `Brief.tools` read the agent's plain-text instructions (a private
@@ -86,8 +91,9 @@ reaching a real model.
8691
nothing else. It adds no behaviour: each command loads the machine (`--machine
8792
package.module:name`, or the `MACHINE` setting) and calls one `Machine` method, `show` →
8893
`graph()`, `start`, `list` → `in_state`, `fire` → `fire` / `brief` (`--agent`) /
89-
`fire(answer=)` (`--answer`), `advance`. Each command returns a `Result` (the data for `--json`,
90-
the text, the exit code: 0 applied or "not now", 1 refused, 2 can't be tried).
94+
`fire(answer=)` (`--answer`), `progress`, `progress_all`. Each command returns a `Result` (the
95+
data for `--json`, the text, the exit code: 0 a move made or "not now", 2 one that can't be made,
96+
with the reason on stderr).
9197

9298
- An entity is `<machine name>:<id>`, checked against the loaded machine; a state given to
9399
`list` is its stored value.
@@ -118,16 +124,21 @@ a `base` module holding a `StateBackend`, picked by the package's dotted path (t
118124
setting, e.g. `AGENTIC_FSM_BACKEND=agentic_fsm.backends.django`, or `Machine(..., backend=)`; a
119125
machine with neither raises). `backends/__init__.py:get_backend` imports `<path>.base` on first use.
120126

121-
- `backends/base/base.py`: `BaseStateBackend` (seven calls: `start`, `move`, `refuse`, `current`,
127+
- `backends/base/base.py`: `BaseStateBackend` (seven calls: `start`, `lock`, `move`, `current`,
122128
`in_state`, `all_current`, `history`), plus the `Move` and `Current` dataclasses.
123-
- `backends/locmem/`: in memory, for tests.
129+
- `backends/locmem/`: in memory, for tests; `lock` is a per-entity `RLock`.
124130
- `backends/django/`: a Django app (`INSTALLED_APPS = ["agentic_fsm.backends.django"]`, label
125131
`agentic_fsm`) with two models, `LogEntry` (append-only) and `CurrentState` (one row per
126-
entity, with a `version`), and their migration. It's the only place Django is imported.
132+
entity), and their migrations. `lock` is `transaction.atomic()` around a `select_for_update`
133+
of the entity's current-state row; SQLite ignores the row lock. It's the only place Django is
134+
imported.
135+
136+
Every backend keeps the same two things and the same rule: `move`, called inside `lock`,
137+
rewrites the entity's current-state row and appends its log row, and both commit when the lock
138+
is released.
127139

128-
Every backend keeps the same two things and the same rule: a move rewrites the entity's
129-
current-state row and appends its log row in one transaction, and only if the entity's version is
130-
still the one read before the step ran. A move that finds another version is logged as refused.
140+
`0002_only_real_moves` deleted the refused log rows and dropped `applied`, `reason` and
141+
`version`. An app whose migration writes those columns through the historical models declares `run_before = [("agentic_fsm", "0002_only_real_moves")]`.
131142

132143
## Tests
133144

‎README.md‎

Lines changed: 26 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ Entity lifecycles declared once and advanced the same way by code, a model or an
44

55
An order, a ticket or an application sits in a state for days and is moved along by whatever
66
knows something new about it. AgenticFSM keeps the allowed moves in one list, records every move
7-
in an append-only log, and refuses a move the list doesn't have.
7+
in an append-only log, and raises on a move the list doesn't have.
88

99
## Install
1010

@@ -135,8 +135,9 @@ orders.fire(42, "read_message", answer={"to": "cancelled", "reason": "They asked
135135
```
136136

137137
`answer=` takes the fields as a dict or a JSON object, or a bare state value when the schema is
138-
a plain `Decision`. The prompt function doesn't run again. An answer the schema or the step's
139-
rows don't allow is refused and logged, and the move's `decided_by` is `agent`.
138+
a plain `Decision`. The prompt function doesn't run again, and the move's `decided_by` is
139+
`agent`. An answer the schema or the step's rows don't allow raises `TransitionError` with the
140+
reason; nothing is written, and the session answers again.
140141

141142
## Moving entities
142143

@@ -147,23 +148,29 @@ rows don't allow is refused and logged, and the move's `decided_by` is `agent`.
147148
| `orders.fire(42, payment_cleared, entity=order)` | the same, on the order already in hand instead of `load(42)` |
148149
| `orders.fire(42, "read_message", answer=...)` | decides a `Decide` step in the model's place |
149150
| `orders.brief(42, "read_message")` | what a `Decide` step would give the model |
150-
| `orders.advance()` | tries the steps out of each unfinished entity's state |
151+
| `orders.progress(42)` | moves one entity until it rests |
152+
| `orders.progress_all()` | tries the steps out of each unfinished entity's state: at most one move each |
151153
| `orders.state_of(42)` | the entity's current state |
152154
| `orders.in_state(Order.paid)` | the ids of the entities in a state |
153155
| `orders.history(42)` | every move logged for the entity |
154156
| `orders.graph()` | the states and rows as data, for review |
155157

156-
- **A step's targets are the rows it sits on.** If `payment_cleared` returns anything but
157-
`Order.paid`, the move is refused and logged, and the order stays where it is.
158-
- **`fire` returns the logged `Move`**, with `applied` true or false and a `reason` when
159-
refused, or `None` when the step said "not now".
160-
- **`advance` tries steps in list order** and stops at the first that doesn't return `None`, so
161-
each entity makes at most one move per call. When to call it is up to you: a cron job, a
162-
scheduler, a script.
163-
- **Two callers can't both move an entity.** A move is written only if the entity hasn't moved
164-
since it was read. The one that comes second is refused and logged.
158+
- **Every row in the log is a move that happened.** A step's targets are the rows it sits on:
159+
if `payment_cleared` returns anything but `Order.paid`, that's a bug, `fire` raises
160+
`TransitionError`, and nothing is written. Whatever a step can meet (a bounce, a failed
161+
payment) is a state with its own row.
162+
- **`fire` returns the logged `Move`**, or `None` when the step said "not now".
163+
- **`progress_all` tries steps in list order** and stops at the first that doesn't return
164+
`None`, so each entity makes at most one move per call. When to call it is up to you: a cron
165+
job, a scheduler, a script.
166+
- **`progress` goes on until the entity rests**: a final state, or one whose steps all say "not
167+
now". It loads the entity afresh after each move, commits each move, and stops after a move
168+
that brings the entity back to a state it already left, so it never loops.
169+
- **Two callers can't both move an entity.** `fire` locks the entity from the read of its state
170+
to the write of the move; a second caller waits, then reads the state the first left. With
171+
the Django backend the step's own writes commit with the move.
165172
- **A step with an outside effect should be safe to run twice.** If it sends an email and the
166-
process dies before the move is written, the next `advance` runs it again.
173+
process dies before the move commits, the next call runs it again.
167174

168175
## At the command line
169176

@@ -178,14 +185,16 @@ code can and no other. Each command calls one of the methods above.
178185
| `agfsm fire order:42 payment_cleared` | `orders.fire(42, "payment_cleared")` |
179186
| `agfsm fire order:42 read_message --agent` | `orders.brief(42, "read_message")` |
180187
| `agfsm fire order:42 read_message --answer '{...}'` | `orders.fire(42, "read_message", answer=...)` |
181-
| `agfsm advance` | `orders.advance()` |
188+
| `agfsm progress order:42` | `orders.progress(42)` |
189+
| `agfsm progress_all` | `orders.progress_all()` |
182190

183191
- **The machine** is named as `--machine package.module:name` (a module in the working directory
184192
works), or by the `MACHINE` setting: `export AGENTIC_FSM_MACHINE=shop.lifecycle:orders`.
185193
- **An entity** is `<machine name>:<id>`, and the name must be the loaded machine's.
186194
- **`--json`** prints the result as data: the `Move`, `Brief` or `Graph`, with times as ISO text.
187-
- **The exit code** is 0 for a move applied or "not now", 1 for a move refused, 2 for one that
188-
can't be tried (an unknown step, an entity not started, no machine).
195+
- **The exit code** is 0 for a move made or "not now", 2 for one that can't be made (an unknown
196+
step, an entity not started, an answer that doesn't validate, no machine), with the reason on
197+
stderr.
189198
- **With `DJANGO_SETTINGS_MODULE` set**, `agfsm` sets the Django project up before it loads the
190199
machine, as `manage.py` would.
191200

‎agentic_fsm/backends/base/base.py‎

Lines changed: 15 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,36 @@
11
"""What every state backend stores and the calls a machine makes on it.
22
3-
A backend keeps two things: an append-only log of moves, and one current-state row per entity.
4-
A move that's applied rewrites that row in the same transaction as its log row, and only if the
5-
entity's version is still the one the caller read (compare-and-set). A backend stores state,
6-
never the entity.
3+
A backend keeps two things: an append-only log of the moves made, and one current-state row per
4+
entity. A machine reads an entity's row under ``lock``, runs a step, and writes the move inside
5+
that same lock, so a second caller waits and then reads the state the first left. A backend
6+
stores state, never the entity.
77
"""
88

9+
from contextlib import AbstractContextManager
910
from dataclasses import dataclass
1011
from datetime import UTC, datetime
1112

1213

1314
@dataclass(frozen=True)
1415
class Move:
15-
"""One log row: a move applied, or one refused."""
16+
"""One log row: a move that happened."""
1617

1718
machine: str
1819
entity: str
1920
step: str | None
2021
from_state: str | None
2122
to_state: str
22-
applied: bool
2323
decided_by: str
2424
at: datetime
2525
decision: dict | None = None
26-
reason: str | None = None
2726

2827

2928
@dataclass(frozen=True)
3029
class Current:
31-
"""An entity's current state, with the version a move must still find to be applied."""
30+
"""An entity's current state."""
3231

3332
entity: str
3433
state: str
35-
version: int
3634

3735

3836
class AlreadyStarted(Exception):
@@ -53,17 +51,16 @@ def start(self, machine: str, entity: str, state: str) -> Move:
5351
"""Give an entity its first state and log it; raise ``AlreadyStarted`` if it has one."""
5452
raise NotImplementedError("subclasses of BaseStateBackend must override start()")
5553

56-
def move(self, move: Move, version: int) -> Move:
57-
"""Apply ``move`` if the entity is still at ``version``, and log it either way.
54+
def lock(self, machine: str, entity: str) -> AbstractContextManager[Current | None]:
55+
"""Hold the entity from read to write: yields its current state, or ``None`` if it
56+
hasn't started. A ``move`` made inside commits when the block ends; an exception
57+
undoes it."""
58+
raise NotImplementedError("subclasses of BaseStateBackend must override lock()")
5859

59-
Returns the move as logged: applied, or refused because something else moved it first.
60-
"""
60+
def move(self, move: Move) -> Move:
61+
"""Rewrite the entity's current state and log ``move``; called inside ``lock``."""
6162
raise NotImplementedError("subclasses of BaseStateBackend must override move()")
6263

63-
def refuse(self, move: Move) -> Move:
64-
"""Log a refused move; the current state is untouched."""
65-
raise NotImplementedError("subclasses of BaseStateBackend must override refuse()")
66-
6764
# ── Reads ──
6865

6966
def current(self, machine: str, entity: str) -> Current | None:
@@ -79,10 +76,5 @@ def all_current(self, machine: str) -> list[Current]:
7976
raise NotImplementedError("subclasses of BaseStateBackend must override all_current()")
8077

8178
def history(self, machine: str, entity: str) -> list[Move]:
82-
"""Every move logged for the entity, applied and refused, oldest first."""
79+
"""Every move logged for the entity, oldest first."""
8380
raise NotImplementedError("subclasses of BaseStateBackend must override history()")
84-
85-
86-
def lost_race(move: Move) -> str:
87-
"""The reason logged when a move finds the entity no longer at the version it read."""
88-
return f"moved by someone else since it was read in {move.from_state}"

‎agentic_fsm/backends/django/base.py‎

Lines changed: 25 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,69 +1,56 @@
11
"""State kept in a Django project's database, through this package's two models.
22
3-
Add ``"agentic_fsm.backends.django"`` to ``INSTALLED_APPS`` and migrate. Writes go through
4-
Django's own connection, so a caller that wraps ``fire`` in ``transaction.atomic()`` commits its
5-
own rows and the move together.
3+
Add ``"agentic_fsm.backends.django"`` to ``INSTALLED_APPS`` and migrate. ``lock`` opens a
4+
transaction on Django's own connection and takes the entity's current-state row with
5+
``select_for_update``, so the step's own writes commit with the move. SQLite has no row lock and
6+
ignores it; there the transaction holds the database once the step writes.
67
"""
78

8-
from dataclasses import replace
9+
from contextlib import contextmanager
910

1011
from django.db import IntegrityError, transaction
11-
from django.db.models import F
1212

13-
from ..base.base import AlreadyStarted, BaseStateBackend, Current, Move, lost_race, utc_now
13+
from ..base.base import AlreadyStarted, BaseStateBackend, Current, Move, utc_now
1414
from .models import CurrentState, LogEntry
1515

16-
LOG_FIELDS = (
17-
"machine",
18-
"entity",
19-
"step",
20-
"from_state",
21-
"to_state",
22-
"applied",
23-
"decided_by",
24-
"at",
25-
"decision",
26-
"reason",
27-
)
16+
LOG_FIELDS = ("machine", "entity", "step", "from_state", "to_state", "decided_by", "at", "decision")
2817

2918

3019
class StateBackend(BaseStateBackend):
3120
# ── Writes ──
3221

3322
def start(self, machine, entity, state):
34-
move = Move(machine, entity, None, None, state, True, "code", utc_now())
23+
move = Move(machine, entity, None, None, state, "code", utc_now())
3524
try:
3625
with transaction.atomic():
37-
CurrentState.objects.create(
38-
machine=machine, entity=entity, state=state, version=1, updated_at=move.at
39-
)
26+
CurrentState.objects.create(machine=machine, entity=entity, state=state, updated_at=move.at)
4027
_append(move)
4128
except IntegrityError:
4229
raise AlreadyStarted(f"{machine}:{entity} has already started") from None
4330
return move
4431

45-
def move(self, move, version):
32+
@contextmanager
33+
def lock(self, machine, entity):
4634
with transaction.atomic():
47-
still_there = CurrentState.objects.filter(
48-
machine=move.machine, entity=move.entity, version=version
49-
).update(state=move.to_state, version=F("version") + 1, updated_at=move.at)
50-
if not still_there:
51-
move = replace(move, applied=False, reason=lost_race(move))
52-
_append(move)
53-
return move
54-
55-
def refuse(self, move):
35+
row = (
36+
CurrentState.objects.select_for_update()
37+
.filter(machine=machine, entity=entity)
38+
.values_list("entity", "state")
39+
.first()
40+
)
41+
yield Current(*row) if row else None
42+
43+
def move(self, move):
44+
CurrentState.objects.filter(machine=move.machine, entity=move.entity).update(
45+
state=move.to_state, updated_at=move.at
46+
)
5647
_append(move)
5748
return move
5849

5950
# ── Reads ──
6051

6152
def current(self, machine, entity):
62-
row = (
63-
CurrentState.objects.filter(machine=machine, entity=entity)
64-
.values_list("entity", "state", "version")
65-
.first()
66-
)
53+
row = CurrentState.objects.filter(machine=machine, entity=entity).values_list("entity", "state").first()
6754
return Current(*row) if row else None
6855

6956
def in_state(self, machine, state):
@@ -72,7 +59,7 @@ def in_state(self, machine, state):
7259

7360
def all_current(self, machine):
7461
rows = CurrentState.objects.filter(machine=machine).order_by("id")
75-
return [Current(*row) for row in rows.values_list("entity", "state", "version")]
62+
return [Current(*row) for row in rows.values_list("entity", "state")]
7663

7764
def history(self, machine, entity):
7865
rows = LogEntry.objects.filter(machine=machine, entity=entity).order_by("id")

0 commit comments

Comments
 (0)