tickflow-py 0.2.0__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/PKG-INFO +32 -16
  2. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/README.md +31 -15
  3. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/pyproject.toml +31 -31
  4. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tests/test_async.py +11 -5
  5. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tests/test_audit_switch.py +2 -2
  6. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tests/test_checkpoints.py +21 -16
  7. tickflow_py-0.4.0/tests/test_failed_terminal.py +188 -0
  8. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tests/test_persistence.py +42 -11
  9. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tests/test_remap.py +3 -5
  10. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tests/test_storage_window.py +2 -2
  11. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tickflow/async_runner.py +5 -1
  12. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tickflow/persistence.py +601 -597
  13. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tickflow/runner.py +40 -11
  14. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tickflow/state.py +16 -3
  15. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tickflow/views.py +1 -1
  16. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tickflow_py.egg-info/PKG-INFO +32 -16
  17. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tickflow_py.egg-info/SOURCES.txt +1 -0
  18. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/LICENSE +0 -0
  19. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/setup.cfg +0 -0
  20. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tests/test_async_bind.py +0 -0
  21. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tests/test_bind.py +0 -0
  22. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tests/test_bind_validation.py +0 -0
  23. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tests/test_checker.py +0 -0
  24. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tests/test_dispatch.py +0 -0
  25. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tests/test_engine.py +0 -0
  26. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tests/test_failure.py +0 -0
  27. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tests/test_fireable.py +0 -0
  28. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tests/test_guard_view.py +0 -0
  29. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tests/test_hooks.py +0 -0
  30. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tests/test_loop.py +0 -0
  31. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tests/test_node_state.py +0 -0
  32. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tests/test_node_view.py +0 -0
  33. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tests/test_parser.py +0 -0
  34. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tests/test_registry_sig.py +0 -0
  35. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tests/test_snapshot.py +0 -0
  36. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tests/test_status.py +0 -0
  37. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tests/test_visualization.py +0 -0
  38. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tickflow/__init__.py +0 -0
  39. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tickflow/__main__.py +0 -0
  40. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tickflow/checker.py +0 -0
  41. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tickflow/cli.py +0 -0
  42. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tickflow/engine.py +0 -0
  43. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tickflow/ir.py +0 -0
  44. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tickflow/parser.py +0 -0
  45. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tickflow/registry.py +0 -0
  46. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tickflow_py.egg-info/dependency_links.txt +0 -0
  47. {tickflow_py-0.2.0 → tickflow_py-0.4.0}/tickflow_py.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tickflow-py
3
- Version: 0.2.0
3
+ Version: 0.4.0
4
4
  Summary: A small Petri-style workflow control framework
5
5
  Author: MountLynx
6
6
  License: MIT
@@ -109,7 +109,8 @@ RunState
109
109
  ```
110
110
 
111
111
  - **`_edges`** — windowed fast-lookup index for `resolve()`: only the last two
112
- firings per node stay in memory; older firings live in the backend. Memory
112
+ firings per node stay in memory; older firings live in a persistent
113
+ backend (NullBackend discards them). Memory
113
114
  usage is O(nodes × 2 × output size), independent of how many times a node fired.
114
115
  - **`_fire_counts`** — per-node firing counters; they map window entries back
115
116
  to their `A[k]` ordinals, so index reads stay correct with a windowed index.
@@ -167,10 +168,15 @@ the system temp dir, auto-generates a `session_id`, and removes the database
167
168
  file when the Runner is garbage-collected — so persistence, audit, checkpoints
168
169
  and `A[k]` index reads work out of the box. Pass `NullBackend()` explicitly
169
170
  for a zero-I/O in-memory run, or a concrete backend for a persistent one.
170
- `NullBackend` also enables **fast mode**: per-tick snapshot persistence is
171
- skipped entirely (the audit serialisation it implies was O(n²) over long
172
- runs), at the cost of no cold history — `A[k]` reads outside the window and
173
- full `firings_of()` degrade to `Missing` / the 2-entry window.
171
+ `NullBackend` also enables **fast mode**: every backend write is discarded —
172
+ no per-tick snapshots, no firing history, no named checkpoints. Runner state
173
+ is window-bounded only with `keep_records=False`; with the default
174
+ `keep_records=True`, the in-memory audit (`_records`) still grows with firing
175
+ count. Note that `run_until_idle()` returns every firing (including outputs)
176
+ and therefore retains the whole run; drive long runs with `tick()` or discard
177
+ the returned list. `A[k]` reads outside the window and full `firings_of()`
178
+ degrade to `Missing` / the 2-entry window. Named checkpoints require a
179
+ persistent backend (`JsonBackend` / `SqliteBackend`).
174
180
 
175
181
  ## Semantics
176
182
 
@@ -325,7 +331,8 @@ def call_llm(v):
325
331
 
326
332
  - **`type="llm"`** (default): a logical/recoverable failure. The node's
327
333
  out-edges write `False`, so downstream AND-joins don't fire (= "upstream
328
- failed, skip downstream"). The run continues.
334
+ failed, skip downstream"). The run keeps ticking — unless the skip
335
+ strands pending work, in which case it ends `FAILED` (see below).
329
336
  - **`type="infrastructure"`**: an unrecoverable failure. Out-edges write
330
337
  `False` **and** the runner enters `ABORTED`, halting all further ticks.
331
338
 
@@ -335,7 +342,9 @@ A `Failure` is still recorded in `RunState` and the audit log with
335
342
  > **Important**: a failed node writes `False` to **all** out-edges —
336
343
  > guarded edges are not evaluated. To implement controllable routing
337
344
  > (e.g. retry on failure), have the body return a result dict and let the
338
- > guard inspect the output value, rather than returning `Failure`.
345
+ > guard inspect the output value, rather than returning `Failure`. If the
346
+ > skip strands pending work (an AND-join whose other input already
347
+ > arrived), the run ends `FAILED` (starved) instead of `IDLE`.
339
348
 
340
349
  ### RunStatus
341
350
 
@@ -343,11 +352,11 @@ A `Failure` is still recorded in `RunState` and the audit log with
343
352
 
344
353
  | Status | Meaning |
345
354
  |--------|---------|
346
- | `IDLE` | quiescent (nothing fired last tick, or never started) |
355
+ | `IDLE` | quiescent with nothing pending (all work done, or never started) |
347
356
  | `RUNNING` | a tick fired (transient; becomes IDLE/terminal next) |
348
357
  | `ABORTED` | an infrastructure `Failure` occurred; halted |
349
358
  | `CANCELLED` | `cancel()` was called; halted |
350
- | `FAILED` | (reserved) all nodes failed and nothing fireable |
359
+ | `FAILED` | starved: work is pending (a True slot / armed start) but nothing is fireable; halted |
351
360
 
352
361
  ```python
353
362
  rn.cancel("user requested") # -> CANCELLED; ticks become no-ops
@@ -400,8 +409,9 @@ at the end of every tick: each `NodeState` (the process record, batch-flushed
400
409
  once per tick) and a lightweight snapshot at the new tick index. The persisted
401
410
  snapshot strips `records` (they live in the backend's firings table) but keeps
402
411
  `edges`/`state` — it stays self-contained — and adds a `fired` trace listing
403
- the nodes that fired that tick. Fast mode (`NullBackend`) skips per-tick
404
- snapshot persistence entirely.
412
+ the nodes that fired that tick. Fast mode (`NullBackend`) discards every
413
+ backend write entirely: no per-tick snapshots, no firings, no named
414
+ checkpoints.
405
415
 
406
416
  ```python
407
417
  from tickflow import JsonBackend
@@ -426,9 +436,11 @@ rn2.restore(snap)
426
436
  `firings` / `checkpoints` tables. Better for high tick-throughput; writes
427
437
  are serialized behind an internal lock, so one instance is safe to share
428
438
  across threads. This is the default (temp file, auto-cleaned).
429
- - **`NullBackend`**: in-memory fast mode — no disk I/O, no per-tick
430
- snapshots, no cold history (`A[k]` outside the window degrades to
431
- `Missing`). Good for tests and hot loops.
439
+ - **`NullBackend`**: stateless fast mode — no disk I/O, no per-tick
440
+ snapshots, no firings, no checkpoints, no cold history (`A[k]` outside
441
+ the window degrades to `Missing`). Good for hot loops and zero-I/O runs;
442
+ use `JsonBackend` / `SqliteBackend` when history or checkpoints are
443
+ required.
432
444
 
433
445
  ### Named checkpoints
434
446
 
@@ -440,6 +452,10 @@ rn.list_checkpoints() # [(label, tick), ...]
440
452
  rn.rollback_to("after_prep") # restore to that checkpoint
441
453
  ```
442
454
 
455
+ Named checkpoints require a backend that stores snapshots: `JsonBackend` or
456
+ `SqliteBackend`. `NullBackend` raises `RuntimeError` for `checkpoint()` /
457
+ `rollback_to()`.
458
+
443
459
  ### Graph remap (hot-swap graph structure)
444
460
 
445
461
  After a rollback, you can replace the graph structure and/or registry before
@@ -595,7 +611,7 @@ tickflow/
595
611
  views.py DictView, Resolved, Missing
596
612
  persistence.py Backend protocol, JsonBackend, SqliteBackend, NullBackend
597
613
  cli.py python -m tickflow ...
598
- tests/ 17 files, 186 tests
614
+ tests/ 25 files, 293 tests
599
615
  examples/ 8 examples (6 graph + 2 Python scripts)
600
616
  ```
601
617
 
@@ -87,7 +87,8 @@ RunState
87
87
  ```
88
88
 
89
89
  - **`_edges`** — windowed fast-lookup index for `resolve()`: only the last two
90
- firings per node stay in memory; older firings live in the backend. Memory
90
+ firings per node stay in memory; older firings live in a persistent
91
+ backend (NullBackend discards them). Memory
91
92
  usage is O(nodes × 2 × output size), independent of how many times a node fired.
92
93
  - **`_fire_counts`** — per-node firing counters; they map window entries back
93
94
  to their `A[k]` ordinals, so index reads stay correct with a windowed index.
@@ -145,10 +146,15 @@ the system temp dir, auto-generates a `session_id`, and removes the database
145
146
  file when the Runner is garbage-collected — so persistence, audit, checkpoints
146
147
  and `A[k]` index reads work out of the box. Pass `NullBackend()` explicitly
147
148
  for a zero-I/O in-memory run, or a concrete backend for a persistent one.
148
- `NullBackend` also enables **fast mode**: per-tick snapshot persistence is
149
- skipped entirely (the audit serialisation it implies was O(n²) over long
150
- runs), at the cost of no cold history — `A[k]` reads outside the window and
151
- full `firings_of()` degrade to `Missing` / the 2-entry window.
149
+ `NullBackend` also enables **fast mode**: every backend write is discarded —
150
+ no per-tick snapshots, no firing history, no named checkpoints. Runner state
151
+ is window-bounded only with `keep_records=False`; with the default
152
+ `keep_records=True`, the in-memory audit (`_records`) still grows with firing
153
+ count. Note that `run_until_idle()` returns every firing (including outputs)
154
+ and therefore retains the whole run; drive long runs with `tick()` or discard
155
+ the returned list. `A[k]` reads outside the window and full `firings_of()`
156
+ degrade to `Missing` / the 2-entry window. Named checkpoints require a
157
+ persistent backend (`JsonBackend` / `SqliteBackend`).
152
158
 
153
159
  ## Semantics
154
160
 
@@ -303,7 +309,8 @@ def call_llm(v):
303
309
 
304
310
  - **`type="llm"`** (default): a logical/recoverable failure. The node's
305
311
  out-edges write `False`, so downstream AND-joins don't fire (= "upstream
306
- failed, skip downstream"). The run continues.
312
+ failed, skip downstream"). The run keeps ticking — unless the skip
313
+ strands pending work, in which case it ends `FAILED` (see below).
307
314
  - **`type="infrastructure"`**: an unrecoverable failure. Out-edges write
308
315
  `False` **and** the runner enters `ABORTED`, halting all further ticks.
309
316
 
@@ -313,7 +320,9 @@ A `Failure` is still recorded in `RunState` and the audit log with
313
320
  > **Important**: a failed node writes `False` to **all** out-edges —
314
321
  > guarded edges are not evaluated. To implement controllable routing
315
322
  > (e.g. retry on failure), have the body return a result dict and let the
316
- > guard inspect the output value, rather than returning `Failure`.
323
+ > guard inspect the output value, rather than returning `Failure`. If the
324
+ > skip strands pending work (an AND-join whose other input already
325
+ > arrived), the run ends `FAILED` (starved) instead of `IDLE`.
317
326
 
318
327
  ### RunStatus
319
328
 
@@ -321,11 +330,11 @@ A `Failure` is still recorded in `RunState` and the audit log with
321
330
 
322
331
  | Status | Meaning |
323
332
  |--------|---------|
324
- | `IDLE` | quiescent (nothing fired last tick, or never started) |
333
+ | `IDLE` | quiescent with nothing pending (all work done, or never started) |
325
334
  | `RUNNING` | a tick fired (transient; becomes IDLE/terminal next) |
326
335
  | `ABORTED` | an infrastructure `Failure` occurred; halted |
327
336
  | `CANCELLED` | `cancel()` was called; halted |
328
- | `FAILED` | (reserved) all nodes failed and nothing fireable |
337
+ | `FAILED` | starved: work is pending (a True slot / armed start) but nothing is fireable; halted |
329
338
 
330
339
  ```python
331
340
  rn.cancel("user requested") # -> CANCELLED; ticks become no-ops
@@ -378,8 +387,9 @@ at the end of every tick: each `NodeState` (the process record, batch-flushed
378
387
  once per tick) and a lightweight snapshot at the new tick index. The persisted
379
388
  snapshot strips `records` (they live in the backend's firings table) but keeps
380
389
  `edges`/`state` — it stays self-contained — and adds a `fired` trace listing
381
- the nodes that fired that tick. Fast mode (`NullBackend`) skips per-tick
382
- snapshot persistence entirely.
390
+ the nodes that fired that tick. Fast mode (`NullBackend`) discards every
391
+ backend write entirely: no per-tick snapshots, no firings, no named
392
+ checkpoints.
383
393
 
384
394
  ```python
385
395
  from tickflow import JsonBackend
@@ -404,9 +414,11 @@ rn2.restore(snap)
404
414
  `firings` / `checkpoints` tables. Better for high tick-throughput; writes
405
415
  are serialized behind an internal lock, so one instance is safe to share
406
416
  across threads. This is the default (temp file, auto-cleaned).
407
- - **`NullBackend`**: in-memory fast mode — no disk I/O, no per-tick
408
- snapshots, no cold history (`A[k]` outside the window degrades to
409
- `Missing`). Good for tests and hot loops.
417
+ - **`NullBackend`**: stateless fast mode — no disk I/O, no per-tick
418
+ snapshots, no firings, no checkpoints, no cold history (`A[k]` outside
419
+ the window degrades to `Missing`). Good for hot loops and zero-I/O runs;
420
+ use `JsonBackend` / `SqliteBackend` when history or checkpoints are
421
+ required.
410
422
 
411
423
  ### Named checkpoints
412
424
 
@@ -418,6 +430,10 @@ rn.list_checkpoints() # [(label, tick), ...]
418
430
  rn.rollback_to("after_prep") # restore to that checkpoint
419
431
  ```
420
432
 
433
+ Named checkpoints require a backend that stores snapshots: `JsonBackend` or
434
+ `SqliteBackend`. `NullBackend` raises `RuntimeError` for `checkpoint()` /
435
+ `rollback_to()`.
436
+
421
437
  ### Graph remap (hot-swap graph structure)
422
438
 
423
439
  After a rollback, you can replace the graph structure and/or registry before
@@ -573,7 +589,7 @@ tickflow/
573
589
  views.py DictView, Resolved, Missing
574
590
  persistence.py Backend protocol, JsonBackend, SqliteBackend, NullBackend
575
591
  cli.py python -m tickflow ...
576
- tests/ 17 files, 186 tests
592
+ tests/ 25 files, 293 tests
577
593
  examples/ 8 examples (6 graph + 2 Python scripts)
578
594
  ```
579
595
 
@@ -1,31 +1,31 @@
1
- [build-system]
2
- requires = ["setuptools>=68"]
3
- build-backend = "setuptools.build_meta"
4
-
5
- [project]
6
- name = "tickflow-py"
7
- version = "0.2.0"
8
- description = "A small Petri-style workflow control framework"
9
- readme = "README.md"
10
- requires-python = ">=3.10"
11
- license = { text = "MIT" }
12
- authors = [{ name = "MountLynx" }]
13
- keywords = ["petri", "workflow", "graph", "state-machine", "flow"]
14
- classifiers = [
15
- "Development Status :: 4 - Beta",
16
- "Intended Audience :: Developers",
17
- "License :: OSI Approved :: MIT License",
18
- "Programming Language :: Python :: 3",
19
- "Programming Language :: Python :: 3.10",
20
- "Programming Language :: Python :: 3.11",
21
- "Programming Language :: Python :: 3.12",
22
- "Programming Language :: Python :: 3.13",
23
- "Topic :: Software Development :: Libraries",
24
- ]
25
- dependencies = []
26
-
27
- [project.urls]
28
- Homepage = "https://github.com/MountLynx/tickflow-"
29
-
30
- [tool.setuptools]
31
- packages = ["tickflow"]
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "tickflow-py"
7
+ version = "0.4.0"
8
+ description = "A small Petri-style workflow control framework"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "MountLynx" }]
13
+ keywords = ["petri", "workflow", "graph", "state-machine", "flow"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.10",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Topic :: Software Development :: Libraries",
24
+ ]
25
+ dependencies = []
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/MountLynx/tickflow-"
29
+
30
+ [tool.setuptools]
31
+ packages = ["tickflow"]
@@ -6,7 +6,7 @@ import asyncio
6
6
 
7
7
  import pytest
8
8
 
9
- from tickflow import parse, Registry, Failure, JsonBackend, RunStatus
9
+ from tickflow import parse, Registry, Failure, JsonBackend, RunStatus, SqliteBackend
10
10
  from tickflow.async_runner import AsyncRunner
11
11
  from tickflow.views import Missing
12
12
 
@@ -146,19 +146,25 @@ def test_async_persistence(tmp_path):
146
146
  assert len(be.list_firings("s1")) == len(rn.audit_log())
147
147
 
148
148
 
149
- def test_async_checkpoint_rollback():
149
+ def test_async_checkpoint_rollback(tmp_path):
150
150
  r = _reg()
151
- from tickflow.persistence import NullBackend
152
- be = NullBackend()
151
+ be = SqliteBackend(tmp_path / "checkpoints.db")
153
152
  rn = AsyncRunner(_loop_graph(r), r, backend=be, session_id="s1")
154
153
  _run(rn.run_until_idle(max_ticks=20, pause_at={3}))
155
154
  rn.checkpoint("cp3")
156
155
  _run(rn.run_until_idle(max_ticks=20))
157
156
  final = [(f.tick, f.node, f.output) for f in rn.audit_log()]
157
+ # Persistent audit() dedupes replayed (tick, node) rows keep-first, so
158
+ # compare the raw appended tail instead.
158
159
  rn.rollback_to("cp3")
159
160
  assert rn.tick_count == 3
161
+ before = len(be.list_firings("s1"))
160
162
  _run(rn.run_until_idle(max_ticks=20))
161
- assert [(f.tick, f.node, f.output) for f in rn.audit_log()] == final
163
+ tail = [
164
+ (d["tick"], d["node"], d["output"])
165
+ for d in be.list_firings("s1")[before:]
166
+ ]
167
+ assert tail == [row for row in final if row[0] >= 3]
162
168
 
163
169
 
164
170
  def test_async_snapshot_restore_matches_sync():
@@ -96,8 +96,8 @@ def test_async_runner_keep_records_false():
96
96
  rn = AsyncRunner(_loop_graph(r), r, backend=be, session_id="s1", keep_records=False)
97
97
  asyncio.run(rn.run_until_idle(max_ticks=50))
98
98
  assert rn.audit_log() == []
99
- # Backend still has firings.
100
- assert len(be.list_firings("s1")) > 0
99
+ # NullBackend is stateless: no backend firing history either.
100
+ assert be.list_firings("s1") == []
101
101
 
102
102
 
103
103
  def test_async_runner_to_json_roundtrip():
@@ -3,7 +3,7 @@ from __future__ import annotations
3
3
 
4
4
  import pytest
5
5
 
6
- from tickflow import parse, Runner, Registry, JsonBackend
6
+ from tickflow import parse, Runner, Registry, JsonBackend, SqliteBackend
7
7
  from tickflow.persistence import NullBackend
8
8
  from tickflow.views import Missing
9
9
 
@@ -47,9 +47,9 @@ def test_checkpoint_works_with_default_backend():
47
47
  assert rn.tick_count == 3
48
48
 
49
49
 
50
- def test_checkpoint_save_and_list():
50
+ def test_checkpoint_save_and_list(tmp_path):
51
51
  r = _reg()
52
- be = NullBackend()
52
+ be = SqliteBackend(tmp_path / "checkpoints.db")
53
53
  rn = Runner(_loop_graph(r), r, backend=be, session_id="s1")
54
54
  rn.run_until_idle(max_ticks=20, pause_at={3})
55
55
  rn.checkpoint("after_3")
@@ -60,25 +60,30 @@ def test_checkpoint_save_and_list():
60
60
  assert ("after_5", 5) in cps
61
61
 
62
62
 
63
- def test_rollback_to_checkpoint_restores_state():
63
+ def test_rollback_to_checkpoint_restores_state(tmp_path):
64
64
  r = _reg()
65
- be = NullBackend()
65
+ be = SqliteBackend(tmp_path / "checkpoints.db")
66
66
  rn = Runner(_loop_graph(r), r, backend=be, session_id="s1")
67
67
  rn.run_until_idle(max_ticks=20, pause_at={3})
68
68
  rn.checkpoint("cp3")
69
69
  rn.run_until_idle(max_ticks=20) # finish
70
70
  final_audit = [(f.tick, f.node, f.output) for f in rn.audit_log()]
71
- # Rollback to cp3 and replay.
71
+ # Rollback to cp3 and replay. Persistent audit() dedupes replayed
72
+ # (tick, node) rows keep-first, so compare the raw appended tail instead.
72
73
  rn.rollback_to("cp3")
73
74
  assert rn.tick_count == 3
75
+ before = len(be.list_firings("s1"))
74
76
  rn.run_until_idle(max_ticks=20)
75
- replayed = [(f.tick, f.node, f.output) for f in rn.audit_log()]
76
- assert replayed == final_audit
77
+ tail = [
78
+ (d["tick"], d["node"], d["output"])
79
+ for d in be.list_firings("s1")[before:]
80
+ ]
81
+ assert tail == [row for row in final_audit if row[0] >= 3]
77
82
 
78
83
 
79
- def test_rollback_to_missing_label_raises():
84
+ def test_rollback_to_missing_label_raises(tmp_path):
80
85
  r = _reg()
81
- be = NullBackend()
86
+ be = SqliteBackend(tmp_path / "checkpoints.db")
82
87
  rn = Runner(_loop_graph(r), r, backend=be, session_id="s1")
83
88
  rn.run_until_idle(max_ticks=5, pause_at={3})
84
89
  with pytest.raises(KeyError):
@@ -105,9 +110,9 @@ def test_json_backend_checkpoints(tmp_path):
105
110
  assert snap["tick"] == 3
106
111
 
107
112
 
108
- def test_checkpoint_overwrites_same_label():
113
+ def test_checkpoint_overwrites_same_label(tmp_path):
109
114
  r = _reg()
110
- be = NullBackend()
115
+ be = SqliteBackend(tmp_path / "checkpoints.db")
111
116
  rn = Runner(_loop_graph(r), r, backend=be, session_id="s1")
112
117
  rn.run_until_idle(max_ticks=20, pause_at={2})
113
118
  rn.checkpoint("cp")
@@ -197,11 +202,11 @@ def test_set_registry_missing_guard_raises():
197
202
  rn.set_registry(bad)
198
203
 
199
204
 
200
- def test_rollback_to_then_set_registry():
205
+ def test_rollback_to_then_set_registry(tmp_path):
201
206
  """rollback_to rewinds state; set_registry swaps the body separately.
202
207
  The two-step flow replaces the old one-call ``registry=`` argument."""
203
208
  r = _reg()
204
- be = NullBackend()
209
+ be = SqliteBackend(tmp_path / "checkpoints.db")
205
210
  rn = Runner(_loop_graph(r), r, backend=be, session_id="s1")
206
211
  rn.run_until_idle(max_ticks=20, pause_at={3})
207
212
  rn.checkpoint("cp3")
@@ -244,14 +249,14 @@ def test_async_set_registry():
244
249
  asyncio.run(_run())
245
250
 
246
251
 
247
- def test_async_rollback_to_then_set_registry():
252
+ def test_async_rollback_to_then_set_registry(tmp_path):
248
253
  """AsyncRunner.rollback_to + set_registry two-step flow."""
249
254
  import asyncio
250
255
  from tickflow.async_runner import AsyncRunner
251
256
 
252
257
  async def _run():
253
258
  r = _reg()
254
- be = NullBackend()
259
+ be = SqliteBackend(tmp_path / "checkpoints.db")
255
260
  rn = AsyncRunner(_loop_graph(r), r, backend=be, session_id="s1")
256
261
  await rn.run_until_idle(max_ticks=20, pause_at={3})
257
262
  rn.checkpoint("cp3")
@@ -0,0 +1,188 @@
1
+ """Tests for the FAILED terminal state: a starved run (pending work, nothing
2
+ fireable) must end FAILED, not IDLE. Spec: SpecModule
3
+ 2026-09-30-tickflow-failed-terminal-design.md."""
4
+ from __future__ import annotations
5
+
6
+ import asyncio
7
+
8
+ import pytest
9
+
10
+ from tickflow import parse, Runner, Registry, RunStatus, Failure
11
+ from tickflow.async_runner import AsyncRunner
12
+
13
+
14
+ def _reg():
15
+ r = Registry()
16
+
17
+ @r.body("ok")
18
+ def _ok(v):
19
+ return "ok"
20
+
21
+ @r.body("fail_llm")
22
+ def _fllm(v):
23
+ return Failure("bad output", type="llm")
24
+
25
+ @r.body("bump")
26
+ def _bump(v):
27
+ v.state["n"] = v.state.get("n", 0) + 1
28
+ return v.state["n"]
29
+
30
+ r.guard("lt3", lambda out: out < 3)
31
+ return r
32
+
33
+
34
+ def _starved_graph(r):
35
+ # A ok -> slot (C,A)=True; B llm-fail -> slot (C,B)=False.
36
+ # AND-join C waits forever for (C,B): pending but nothing fireable.
37
+ return parse(
38
+ "[A]-->C\n[B]-->C\nC.join: AND\nA.body: ok\nB.body: fail_llm",
39
+ registry=r,
40
+ )
41
+
42
+
43
+ def test_starved_sync_ends_failed():
44
+ r = _reg()
45
+ rn = Runner(_starved_graph(r), r)
46
+ rn.run_until_idle(max_ticks=10)
47
+ assert rn.status == RunStatus.FAILED
48
+ assert rn.is_terminal()
49
+ assert not rn.is_idle()
50
+ # FAILED 已在 _TERMINAL:后续 tick 空操作。
51
+ before = len(rn.audit_log())
52
+ rn.tick()
53
+ assert len(rn.audit_log()) == before
54
+
55
+
56
+ def test_starved_status_set_inside_tick_before_break():
57
+ # 状态判定发生在 tick 内、run_until_idle 空 tick break 读取之前:
58
+ # 首个空 tick 返回 [] 时 status 已是 FAILED。
59
+ r = _reg()
60
+ rn = Runner(_starved_graph(r), r)
61
+ rn.tick() # tick 0: A ok + B fail_llm(双双点火)
62
+ assert rn.status == RunStatus.RUNNING
63
+ firings = rn.tick() # tick 1: 空 tick
64
+ assert firings == []
65
+ assert rn.status == RunStatus.FAILED
66
+
67
+
68
+ def test_starved_status_set_inside_tick_before_break_async():
69
+ # sync 版的 async 对偶:空 tick 返回 [] 时 status 已在 tick 内定为 FAILED。
70
+ r = _reg()
71
+ rn = AsyncRunner(_starved_graph(r), r)
72
+
73
+ async def _drive():
74
+ await rn.tick() # tick 0: A ok + B fail_llm
75
+ assert rn.status == RunStatus.RUNNING
76
+ firings = await rn.tick() # tick 1: 空 tick
77
+ assert firings == []
78
+ assert rn.status == RunStatus.FAILED
79
+
80
+ asyncio.run(_drive())
81
+
82
+
83
+ def test_starved_async_ends_failed():
84
+ r = _reg()
85
+ rn = AsyncRunner(_starved_graph(r), r)
86
+ asyncio.run(rn.run_until_idle(max_ticks=10))
87
+ assert rn.status == RunStatus.FAILED
88
+ assert rn.is_terminal()
89
+
90
+
91
+ # --- 不误伤面:语义矩阵其余各行不受状态判定改动影响 -----------------------
92
+
93
+
94
+ def test_full_completion_still_idle():
95
+ # 全部工作完成(无 pending)→ IDLE(Module 层照旧映射 done)。
96
+ r = _reg()
97
+ g = parse("[A]-->B\nA.body: ok\nB.body: ok", registry=r)
98
+ rn = Runner(g, r)
99
+ rn.run_until_idle(max_ticks=10)
100
+ assert rn.status == RunStatus.IDLE
101
+ assert not rn._has_pending()
102
+ assert rn.is_terminal() # IDLE 且无事可做仍是终局
103
+
104
+
105
+ def test_or_join_loop_exit_stays_idle():
106
+ # OR-join repair 环(producer 条件到场,波间衔接无空 tick):守卫关闭
107
+ # 循环边后所有槽位 False → 空 tick → IDLE 而非 FAILED。
108
+ r = _reg()
109
+ g = parse(
110
+ "[P]-->W\nP.body: ok\nW.body: bump\nW--|lt3|-->W\nW.join: OR",
111
+ registry=r,
112
+ )
113
+ rn = Runner(g, r)
114
+ rn.run_until_idle(max_ticks=50)
115
+ assert rn.status == RunStatus.IDLE
116
+ w_outputs = [f.output for f in rn.audit_log() if f.node == "W"]
117
+ assert w_outputs == [1, 2, 3]
118
+
119
+
120
+ def test_or_join_loop_exit_stays_idle_async():
121
+ r = _reg()
122
+ g = parse(
123
+ "[P]-->W\nP.body: ok\nW.body: bump\nW--|lt3|-->W\nW.join: OR",
124
+ registry=r,
125
+ )
126
+ rn = AsyncRunner(g, r)
127
+ asyncio.run(rn.run_until_idle(max_ticks=50))
128
+ assert rn.status == RunStatus.IDLE
129
+
130
+
131
+ def test_failed_upstream_false_slot_still_idle():
132
+ # 失败上游写 False ≠ pending:下游被跳过,照旧 IDLE
133
+ #(与 tests/test_failure.py::test_llm_failure_writes_false_downstream 互为锚)。
134
+ r = _reg()
135
+ g = parse("[A]-->B\nA.body: fail_llm\nB.body: ok", registry=r)
136
+ rn = Runner(g, r)
137
+ rn.run_until_idle(max_ticks=10)
138
+ assert rn.status == RunStatus.IDLE
139
+
140
+
141
+ def test_max_ticks_cutoff_stays_running():
142
+ # max_ticks 耗尽停在 RUNNING(Module 层映射 truncated,可 resume),
143
+ # 不经过空 tick 判定——不得变成 FAILED/IDLE。
144
+ r = _reg()
145
+ rn = Runner(_starved_graph(r), r)
146
+ rn.run_until_idle(max_ticks=1) # tick 0 点火 A、B 后即达上限
147
+ assert rn.status == RunStatus.RUNNING
148
+
149
+
150
+ def test_pause_breaks_before_status_judgement():
151
+ # pause 在 tick 前 break,不进状态判定。
152
+ r = _reg()
153
+ rn = Runner(_starved_graph(r), r)
154
+ rn.run_until_idle(max_ticks=10, pause_at={1})
155
+ assert rn.status == RunStatus.RUNNING
156
+
157
+
158
+ def test_cancel_before_run_and_after_failed():
159
+ r = _reg()
160
+ rn = Runner(_starved_graph(r), r)
161
+ rn.cancel("user")
162
+ assert rn.status == RunStatus.CANCELLED
163
+ assert rn.cancel_reason == "user"
164
+ rn2 = Runner(_starved_graph(r), r)
165
+ rn2.run_until_idle(max_ticks=10)
166
+ assert rn2.status == RunStatus.FAILED
167
+ rn2.cancel("late")
168
+ assert rn2.status == RunStatus.FAILED # 终态 cancel 是 no-op
169
+
170
+
171
+ def test_reset_from_failed_back_to_idle():
172
+ r = _reg()
173
+ rn = Runner(_starved_graph(r), r)
174
+ rn.run_until_idle(max_ticks=10)
175
+ assert rn.status == RunStatus.FAILED
176
+ rn.reset()
177
+ assert rn.status == RunStatus.IDLE
178
+
179
+
180
+ def test_restore_failed_snapshot_resumes_as_idle():
181
+ # restore() 把终态快照重置回 IDLE(既有 resume 语义),快照本身带 failed。
182
+ r = _reg()
183
+ rn = Runner(_starved_graph(r), r)
184
+ rn.run_until_idle(max_ticks=10)
185
+ snap = rn.snapshot()
186
+ assert snap["status"] == "failed"
187
+ rn.restore(snap)
188
+ assert rn.status == RunStatus.IDLE