Skip to content

Commit 1999feb

Browse files
committed
Tags on states: a state is a queue, and progress_all, due and agfsm take a tag to work only the entities waiting in it
1 parent 89dacca commit 1999feb

8 files changed

Lines changed: 201 additions & 15 deletions

File tree

‎CLAUDE.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,10 @@ by whoever knows something new. A machine is three plain Python things.
3030
- **States** (`states.py`): declared like Django model fields, `pending = InitialState("...")`.
3131
`_StatesMeta` replaces each declaration with its stored value before the enum is built, so the
3232
class is a real `str` enum (`Order.paid == "paid"`, usable as a Pydantic type) whose members
33-
keep their description and kind. The description is required; it's the state's definition.
33+
keep their description, kind and tags. The description is required; it's the state's
34+
definition. `tags=` makes a state a queue: `progress_all(tag)` and `due(tag)` try only the
35+
entities in a state carrying the tag, so one worker does one kind of work (`Machine._tagged`;
36+
a tag no state carries raises `MachineError`). `agfsm due` and `progress_all` take `--tag`.
3437
- **Steps**: a named function of the entity that returns the next state (or a `Decision`), or
3538
`None` for "not now"; or a `Decide`, which puts the question to a model (see *Decide*).
3639
`@check` (`machine.py`) marks a function step that only reads, so `due` may run it; it sets

‎README.md‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,20 @@ reason; nothing is written, and the session answers again.
182182
def payment_cleared(order):
183183
return Order.paid if order.payment_cleared else None
184184
```
185+
- **A tag makes a state a queue.** Give a state `tags=`, and `progress_all(tag)` and `due(tag)`
186+
try only the entities waiting in a state that carries it. One worker then does one kind of
187+
work, on its own schedule: the warehouse's run never calls the model, and a slow model never
188+
holds the warehouse. A state can carry several tags; a tag no state carries raises
189+
`MachineError`.
190+
191+
```python
192+
class Order(States):
193+
pending = InitialState("Placed, not paid yet")
194+
paid = State("Payment cleared, waiting to ship", tags={"warehouse"})
195+
...
196+
197+
orders.progress_all("warehouse") # only the orders in `paid`
198+
```
185199
- **`progress` goes on until the entity rests**: a final state, or one whose steps all say "not
186200
now". It loads the entity afresh after each move, commits each move, and stops after a move
187201
that brings the entity back to a state it already left, so it never loops.
@@ -201,12 +215,12 @@ code can and no other. Each command calls one of the methods above.
201215
| `agfsm show [--mermaid]` | `orders.graph()`: the states with their descriptions, then the rows |
202216
| `agfsm start order:42` | `orders.start(42)` |
203217
| `agfsm list paid` | `orders.in_state(Order.paid)` |
204-
| `agfsm due` | `orders.due()` |
218+
| `agfsm due [--tag warehouse]` | `orders.due()`, or `orders.due("warehouse")` |
205219
| `agfsm fire order:42 payment_cleared` | `orders.fire(42, "payment_cleared")` |
206220
| `agfsm fire order:42 read_message --agent` | `orders.brief(42, "read_message")` |
207221
| `agfsm fire order:42 read_message --answer '{...}'` | `orders.fire(42, "read_message", answer=...)` |
208222
| `agfsm progress order:42` | `orders.progress(42)` |
209-
| `agfsm progress_all` | `orders.progress_all()` |
223+
| `agfsm progress_all [--tag warehouse]` | `orders.progress_all()`, or `orders.progress_all("warehouse")` |
210224

211225
- **The machine** is named as `--machine package.module:name` (a module in the working directory
212226
works), or by the `MACHINE` setting: `export AGENTIC_FSM_MACHINE=shop.lifecycle:orders`.

‎agentic_fsm/cli.py‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ def _parser() -> argparse.ArgumentParser:
7777
listing.set_defaults(command=list_command)
7878

7979
due = commands.add_parser("due", parents=[shared], help="the entities a step could move now")
80+
due.add_argument("--tag", help="only the entities in a state carrying this tag")
8081
due.set_defaults(command=due_command)
8182

8283
fire = commands.add_parser("fire", parents=[shared], help="run one step on one entity")
@@ -92,6 +93,7 @@ def _parser() -> argparse.ArgumentParser:
9293
progress.set_defaults(command=progress_command)
9394

9495
progress_all = commands.add_parser("progress_all", parents=[shared], help="at most one move for every entity")
96+
progress_all.add_argument("--tag", help="only the entities in a state carrying this tag")
9597
progress_all.set_defaults(command=progress_all_command)
9698
return parser
9799

@@ -193,7 +195,7 @@ def list_command(machine: Machine, args) -> Result:
193195

194196

195197
def due_command(machine: Machine, args) -> Result:
196-
ids = machine.due()
198+
ids = machine.due(args.tag)
197199
return Result(ids, "\n".join(f"{machine.name}:{entity_id}" for entity_id in ids) or "nothing due")
198200

199201

@@ -216,7 +218,7 @@ def progress_all_command(machine: Machine, args) -> Result:
216218
"""The moves made; with an entity whose step raised, those moves still print, each failure
217219
goes to stderr, and the exit code is 2."""
218220
try:
219-
return _moves_result(machine.progress_all())
221+
return _moves_result(machine.progress_all(args.tag))
220222
except ProgressError as error:
221223
for entity_id, failure in error.failures.items():
222224
print(f"agfsm: {machine.name}:{entity_id}: {type(failure).__name__}: {failure}", file=sys.stderr)
@@ -246,11 +248,16 @@ def _moves_result(moves: list[Move]) -> Result:
246248

247249

248250
def _graph_text(graph: Graph) -> str:
249-
states = _columns([(s.value, s.kind, s.description) for s in graph.states])
251+
states = _columns([(s.value, s.kind, _described(s)) for s in graph.states])
250252
rows = _columns([("from", "to", "step"), *graph.transitions])
251253
return f"{graph.name}\n\n{states}\n\n{rows}"
252254

253255

256+
def _described(state) -> str:
257+
"""A state's description, followed by its tags when it has any."""
258+
return f"{state.description} [{', '.join(state.tags)}]" if state.tags else state.description
259+
260+
254261
def mermaid(graph: Graph) -> str:
255262
"""The machine as a Mermaid state diagram, each state labelled with its description."""
256263
lines = ["stateDiagram-v2"]

‎agentic_fsm/machine.py‎

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ class StateInfo:
7878
value: str
7979
kind: str
8080
description: str
81+
tags: tuple[str, ...] = ()
8182

8283

8384
@dataclass(frozen=True)
@@ -136,7 +137,9 @@ def graph(self) -> Graph:
136137
"""The states with their descriptions and every row, in declaration order."""
137138
return Graph(
138139
name=self.name,
139-
states=[StateInfo(s.name, s.value, s.kind, s.description) for s in self.states],
140+
states=[
141+
StateInfo(s.name, s.value, s.kind, s.description, tuple(sorted(s.tags))) for s in self.states
142+
],
140143
transitions=[(e.from_state.value, e.to_state.value, _step_name(e.step)) for e in self.edges],
141144
)
142145

@@ -231,19 +234,24 @@ def progress(self, entity_id) -> list[Move]:
231234
break
232235
return moves
233236

234-
def progress_all(self) -> list[Move]:
237+
def progress_all(self, tag: str | None = None) -> list[Move]:
235238
"""Try the steps out of each non-final entity's state, in list order.
236239
237240
The first step that doesn't return ``None`` decides, so each entity makes at most one move
238241
per call. Each entity is locked and committed on its own. Returns the moves made.
239242
243+
With ``tag``, only the entities in a state carrying it are tried: one worker per tag,
244+
each moving its own queue. A tag no state carries raises ``MachineError``.
245+
240246
An entity whose step raises doesn't hold the others: its move is undone, the rest are
241247
tried, and ``ProgressError`` is raised at the end with the moves made and each failure.
242248
"""
249+
tagged = self._tagged(tag)
243250
moves, failures = [], {}
244251
for current in self.backend.all_current(self.name):
245252
try:
246-
if not self._exits.get(self._state(current)):
253+
state = self._state(current)
254+
if not self._exits.get(state) or (tagged is not None and state not in tagged):
247255
continue
248256
move = self._one_move(current.entity)
249257
except Exception as error:
@@ -255,21 +263,35 @@ def progress_all(self) -> list[Move]:
255263
raise ProgressError(moves, failures)
256264
return moves
257265

258-
def due(self) -> list[str]:
266+
def due(self, tag: str | None = None) -> list[str]:
259267
"""The unfinished entities a step could move now; nothing is moved or written.
260268
261269
For a scheduler deciding whether a run is worth starting. Each entity is tried as
262270
``progress_all`` would try it, under its lock: a ``check`` step runs and says whether it
263271
would move the entity; any other step (an outside effect, a ``Decide``) can't be tried
264272
without its effect, so an entity it leaves is due once the checks before it say "not
265-
now". Returns the entity ids, oldest first.
273+
now". With ``tag``, only the entities in a state carrying it, as ``progress_all(tag)``
274+
would try. Returns the entity ids, oldest first.
266275
"""
276+
tagged = self._tagged(tag)
267277
return [
268278
current.entity
269279
for current in self.backend.all_current(self.name)
270-
if self._exits.get(self._state(current)) and self._would_move(current.entity)
280+
if self._exits.get(state := self._state(current))
281+
and (tagged is None or state in tagged)
282+
and self._would_move(current.entity)
271283
]
272284

285+
def _tagged(self, tag: str | None) -> set[States] | None:
286+
"""The states carrying ``tag``; ``None`` for no tag, which is every state."""
287+
if tag is None:
288+
return None
289+
tagged = {state for state in self.states if tag in state.tags}
290+
if not tagged:
291+
known = ", ".join(sorted({t for state in self.states for t in state.tags})) or "none"
292+
raise MachineError(f"no state of {self.name} is tagged {tag!r}; its tags are {known}")
293+
return tagged
294+
273295
def _would_move(self, entity_id: str) -> bool:
274296
"""Under the entity's lock, whether the first step to answer would move it."""
275297
with self.backend.lock(self.name, entity_id) as current:

‎agentic_fsm/states.py‎

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,10 @@ class Order(States):
66
delivered = FinalState("The carrier delivered it")
77
88
``Order`` is a ``str`` enum: ``Order.pending == "pending"``, ``Order("pending") is Order.pending``, and it
9-
works as a Pydantic field type. Each member keeps its description and its kind.
9+
works as a Pydantic field type. Each member keeps its description, its kind and its tags.
1010
"""
1111

12+
from collections.abc import Iterable
1213
from enum import Enum, EnumMeta
1314

1415
INITIAL = "initial"
@@ -20,17 +21,33 @@ class Order(States):
2021

2122

2223
class State:
23-
"""A state with its definition. ``value=`` overrides the stored value (default: the name)."""
24+
"""A state with its definition. ``value=`` overrides the stored value (default: the name).
25+
26+
``tags=`` names the queues the state is: whoever works one tag moves only the entities
27+
waiting in a state that carries it (``Machine.progress_all(tag=)``, ``Machine.due(tag=)``).
28+
"""
2429

2530
kind = PLAIN
2631

27-
def __init__(self, description: str, *, value: str | None = None):
32+
def __init__(self, description: str, *, value: str | None = None, tags: Iterable[str] = ()):
2833
if not isinstance(description, str) or not description.strip():
2934
raise TypeError(f"{type(self).__name__} needs a description, the state's definition")
3035
if value is not None and (not isinstance(value, str) or not value):
3136
raise TypeError(f"value= must be a non-empty string, got {value!r}")
3237
self.description = description
3338
self.value = value
39+
self.tags = _tags(tags)
40+
41+
42+
def _tags(tags) -> frozenset[str]:
43+
"""``tags=`` as a set of non-empty strings; a bare string is refused, not read as letters."""
44+
if isinstance(tags, str) or not isinstance(tags, Iterable):
45+
raise TypeError(f"tags= must be a collection of strings, got {tags!r}")
46+
tags = frozenset(tags)
47+
for tag in tags:
48+
if not isinstance(tag, str) or not tag:
49+
raise TypeError(f"a tag must be a non-empty string, got {tag!r}")
50+
return tags
3451

3552

3653
class InitialState(State):
@@ -99,6 +116,10 @@ def description(self) -> str:
99116
def kind(self) -> str:
100117
return type(self)._declarations[self.name].kind
101118

119+
@property
120+
def tags(self) -> frozenset[str]:
121+
return type(self)._declarations[self.name].tags
122+
102123
@property
103124
def is_initial(self) -> bool:
104125
return self.kind == INITIAL

‎tests/test_cli.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ def test_show_json_is_the_graph(capsys, cli_orders):
101101
"value": "pending",
102102
"kind": "initial",
103103
"description": "Placed, not paid yet",
104+
"tags": [],
104105
}
105106
assert ["pending", "paid", "payment_cleared"] in data["transitions"]
106107

@@ -262,6 +263,21 @@ def test_due_lists_what_a_step_could_move_and_moves_nothing(capsys, backend, tab
262263
assert machine.in_state(Order.pending) == ["1", "2"]
263264

264265

266+
def test_a_tag_narrows_due_and_progress_all_and_show_prints_it(capsys, backend, table, monkeypatch):
267+
from .test_machine_moves import parcels_in_every_state
268+
269+
monkeypatch.setattr(machines, "orders", parcels_in_every_state(backend, table))
270+
271+
assert run(capsys, *ORDERS, "due", "--tag", "carrier")[1].strip() == "parcel:4"
272+
code, data = run_json(capsys, *ORDERS, "progress_all", "--tag", "warehouse")
273+
assert code == EXIT_OK
274+
assert [(m["entity"], m["to_state"]) for m in data] == [("2", "labelling"), ("3", "shipped")]
275+
assert "Packed: the warehouse labels it [printer, warehouse]" in run(capsys, *ORDERS, "show")[1]
276+
code, _, err = run(capsys, *ORDERS, "due", "--tag", "nobody")
277+
assert code == EXIT_ERROR
278+
assert "no state of parcel is tagged 'nobody'" in err
279+
280+
265281
def test_a_django_settings_module_not_installed_here_is_left_alone(capsys, cli_orders, monkeypatch):
266282
"""A container that also runs a Django tool sets the variable for it, not for this machine."""
267283
monkeypatch.setenv("DJANGO_SETTINGS_MODULE", "some_other_tool.settings")

‎tests/test_machine_moves.py‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,13 @@
1111
AlreadyStarted,
1212
Decide,
1313
Decision,
14+
FinalState,
15+
InitialState,
1416
Machine,
17+
MachineError,
1518
ProgressError,
19+
State,
20+
States,
1621
TransitionError,
1722
check,
1823
get_backend,
@@ -508,6 +513,88 @@ def test_a_finished_entity_is_never_due_nor_loaded(backend, table):
508513
assert orders.due() == []
509514

510515

516+
# ── tags ──
517+
518+
519+
class Parcel(States):
520+
pending = InitialState("Placed, not paid yet")
521+
packing = State("Paid: the warehouse packs it", tags={"warehouse"})
522+
labelling = State("Packed: the warehouse labels it", tags={"warehouse", "printer"})
523+
shipped = State("Handed to the carrier", tags={"carrier"})
524+
delivered = FinalState("The carrier delivered it")
525+
526+
527+
@check
528+
def paid(parcel):
529+
return Parcel.packing if parcel.payment_cleared else None
530+
531+
532+
def pack(parcel):
533+
return Parcel.labelling
534+
535+
536+
def label(parcel):
537+
return Parcel.shipped
538+
539+
540+
@check
541+
def parcel_delivered(parcel):
542+
return Parcel.delivered if parcel.delivered else None
543+
544+
545+
PARCEL_ROWS = [
546+
(Parcel.pending, Parcel.packing, paid),
547+
(Parcel.packing, Parcel.labelling, pack),
548+
(Parcel.labelling, Parcel.shipped, label),
549+
(Parcel.shipped, Parcel.delivered, parcel_delivered),
550+
]
551+
552+
553+
def parcels_in_every_state(backend, table):
554+
"""Parcels 1 to 4, one in each unfinished state, each with a move it could make."""
555+
parcels = Machine(Parcel, PARCEL_ROWS, load=lambda parcel_id: table[parcel_id], backend=backend)
556+
for parcel_id in "1234":
557+
table[parcel_id] = new_order(payment_cleared=True, delivered=True)
558+
parcels.start_all("1234")
559+
for parcel_id, steps in (("2", [paid]), ("3", [paid, pack]), ("4", [paid, pack, label])):
560+
for step in steps:
561+
parcels.fire(parcel_id, step)
562+
return parcels
563+
564+
565+
def test_progress_all_with_a_tag_moves_only_the_entities_in_its_states(backend, table):
566+
parcels = parcels_in_every_state(backend, table)
567+
568+
moves = parcels.progress_all("warehouse")
569+
570+
assert [(m.entity, m.to_state) for m in moves] == [("2", "labelling"), ("3", "shipped")]
571+
assert parcels.state_of(1) is Parcel.pending
572+
assert parcels.state_of(4) is Parcel.shipped
573+
574+
575+
def test_a_state_may_carry_several_tags(backend, table):
576+
parcels = parcels_in_every_state(backend, table)
577+
578+
assert [m.entity for m in parcels.progress_all("printer")] == ["3"]
579+
580+
581+
def test_due_with_a_tag_lists_only_the_entities_in_its_states(backend, table):
582+
parcels = parcels_in_every_state(backend, table)
583+
584+
assert parcels.due() == ["1", "2", "3", "4"]
585+
assert parcels.due("carrier") == ["4"]
586+
assert parcels.due("warehouse") == ["2", "3"]
587+
588+
589+
@pytest.mark.parametrize("call", ["progress_all", "due"])
590+
def test_a_tag_no_state_carries_is_refused(backend, table, call):
591+
parcels = parcels_in_every_state(backend, table)
592+
593+
with pytest.raises(MachineError, match="no state of parcel is tagged 'wharehouse'; its tags are carrier"):
594+
getattr(parcels, call)("wharehouse")
595+
assert parcels.state_of(2) is Parcel.packing
596+
597+
511598
def test_check_marks_a_code_step_and_refuses_a_decide():
512599
assert is_check(checked_payment)
513600
assert not is_check(payment_cleared)

‎tests/test_states.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,22 @@ class Legacy(States):
2929
assert Legacy.new.name == "new"
3030

3131

32+
def test_a_state_keeps_its_tags_and_has_none_by_default():
33+
class Tagged(States):
34+
new = InitialState("Just made")
35+
packing = State("Being packed", tags=["warehouse", "printer"])
36+
done = FinalState("Finished")
37+
38+
assert Tagged.packing.tags == {"warehouse", "printer"}
39+
assert Tagged.new.tags == frozenset()
40+
41+
42+
@pytest.mark.parametrize("tags", ["warehouse", [""], [3], 3])
43+
def test_tags_must_be_a_collection_of_non_empty_strings(tags):
44+
with pytest.raises(TypeError, match="tag"):
45+
State("Being packed", tags=tags)
46+
47+
3248
@pytest.mark.parametrize("description", ["", " ", None])
3349
def test_a_state_needs_a_description(description):
3450
with pytest.raises(TypeError, match="needs a description"):

0 commit comments

Comments
 (0)