substantial 0.3.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.
- {substantial-0.3.0 → substantial-0.4.0}/.gitignore +0 -1
- {substantial-0.3.0 → substantial-0.4.0}/PKG-INFO +69 -26
- {substantial-0.3.0 → substantial-0.4.0}/README.md +68 -25
- {substantial-0.3.0 → substantial-0.4.0}/pyproject.toml +4 -5
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/__init__.py +21 -3
- substantial-0.4.0/python/substantial/boundary/v1/agent_pb2.py +54 -0
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/boundary/v1/agent_pb2.pyi +33 -16
- substantial-0.4.0/python/substantial/boundary/v1/boundary_pb2.py +51 -0
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/boundary/v1/boundary_pb2.pyi +40 -9
- substantial-0.4.0/python/substantial/boundary/v1/plan_pb2.py +107 -0
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/boundary/v1/plan_pb2.pyi +61 -24
- substantial-0.4.0/python/substantial/boundary/v1/run_pb2.py +103 -0
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/boundary/v1/run_pb2.pyi +72 -25
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/child.py +7 -3
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/client.py +142 -66
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/clock.py +64 -7
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/context.py +35 -11
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/cost.py +14 -8
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/errors.py +43 -37
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/iterate.py +13 -9
- substantial-0.4.0/python/substantial/layout/v1/layout_pb2.py +111 -0
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/layout/v1/layout_pb2.pyi +131 -57
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/machines.py +6 -0
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/messages.py +8 -8
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/observe.py +80 -15
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/replay.py +178 -51
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/saga.py +9 -7
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/schedule.py +23 -13
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/scheduler.py +31 -13
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/settings.py +62 -43
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/step.py +84 -26
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/stores/__init__.py +28 -8
- substantial-0.4.0/python/substantial/stores/base.py +153 -0
- substantial-0.4.0/python/substantial/stores/fs.py +650 -0
- substantial-0.4.0/python/substantial/stores/memory.py +127 -0
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/stores/redis_connect.py +3 -2
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/stores/redis_store.py +114 -27
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/stores/retry.py +58 -8
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/stores/s3.py +24 -16
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/stores/s3_store.py +191 -20
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/testing/__init__.py +2 -1
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/testing/_env.py +27 -14
- substantial-0.4.0/python/substantial/testing/_replay.py +181 -0
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/testing/_store.py +33 -10
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/testing/_workers.py +37 -11
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/testing/_world.py +51 -16
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/worker.py +69 -28
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/workflow.py +46 -17
- substantial-0.4.0/redis/cas.lua +37 -0
- substantial-0.4.0/redis/create.lua +41 -0
- {substantial-0.3.0 → substantial-0.4.0}/redis/delete.lua +6 -6
- substantial-0.4.0/wasm/SHA256SUMS +1 -0
- substantial-0.4.0/wasm/substantial.wasm +0 -0
- substantial-0.3.0/python/substantial/boundary/v1/agent_pb2.py +0 -52
- substantial-0.3.0/python/substantial/boundary/v1/boundary_pb2.py +0 -45
- substantial-0.3.0/python/substantial/boundary/v1/plan_pb2.py +0 -103
- substantial-0.3.0/python/substantial/boundary/v1/run_pb2.py +0 -99
- substantial-0.3.0/python/substantial/layout/v1/layout_pb2.py +0 -103
- substantial-0.3.0/python/substantial/stores/base.py +0 -87
- substantial-0.3.0/python/substantial/stores/fs.py +0 -222
- substantial-0.3.0/python/substantial/stores/memory.py +0 -54
- substantial-0.3.0/redis/create.lua +0 -17
- substantial-0.3.0/wasm/SHA256SUMS +0 -1
- substantial-0.3.0/wasm/substantial.wasm +0 -0
- {substantial-0.3.0 → substantial-0.4.0}/LICENSE +0 -0
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/_proto.py +0 -0
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/core.py +0 -0
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/durations.py +0 -0
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/executor.py +0 -0
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/log.py +0 -0
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/names.py +0 -0
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/plan.py +0 -0
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/py.typed +0 -0
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/stores/attempts.py +0 -0
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/stores/credentials.py +0 -0
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/stores/redis.py +0 -0
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/stores/redis_notify.py +0 -0
- {substantial-0.3.0 → substantial-0.4.0}/python/substantial/testing/_time.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: substantial
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: Brokerless durable execution: the Python host of the Substantial core
|
|
5
5
|
Project-URL: Repository, https://github.com/zifeo/substantial
|
|
6
6
|
License-Expression: MPL-2.0
|
|
@@ -72,7 +72,7 @@ shipping a-42 to 1 rue du Lac, Lausanne
|
|
|
72
72
|
```
|
|
73
73
|
|
|
74
74
|
- `charge` and `ship` are steps: their results are recorded, and the function, replayed from its first line at every wakeup, gets them back without running them again. A step can be declared, as `charge` is with its retry of up to five attempts and an exponential backoff, or wrapped inline on the fly under a name, as `c.step("ship", ...)` does with `ship`, a plain function.
|
|
75
|
-
- `c.receive("address")` takes the message the client sends with `run.send`. A message sent before the workflow asks for it waits in the
|
|
75
|
+
- `c.receive("address")` takes the message the client sends with `run.send`. A message sent before the workflow asks for it waits in the store until the workflow takes it.
|
|
76
76
|
- `c.sleep` is a durable timer: while it waits, the run is suspended and holds no process.
|
|
77
77
|
- The worker runs the workflow; the client starts it, messages it and awaits its result. They can be the same process, as here, or many processes on many machines sharing the store. Leaving `async with` stops the worker, then closes the client.
|
|
78
78
|
- `id="order-a-42"` makes the start idempotent: starting it again finds the same run.
|
|
@@ -98,7 +98,7 @@ struct Receipt {
|
|
|
98
98
|
tracking: String,
|
|
99
99
|
}
|
|
100
100
|
|
|
101
|
-
#[s::step(retry = s::Retry { max_attempts: 5, initial: s::seconds(1), max: s::minutes(1), multiplier: 2.0 })]
|
|
101
|
+
#[s::step(retry = s::Retry { max_attempts: 5, initial: s::seconds(1), max: s::minutes(1), multiplier: 2.0, deadline: None })]
|
|
102
102
|
async fn charge(order: &str, amount: u32) -> anyhow::Result<String> {
|
|
103
103
|
println!("charging {amount} for {order}");
|
|
104
104
|
Ok(format!("pay-{order}"))
|
|
@@ -237,6 +237,14 @@ A run replays its function from the first line at every wakeup. So side effects
|
|
|
237
237
|
async def upload(archive: str, target: str) -> str:
|
|
238
238
|
return await s3.put(archive, target, idempotency_key=s.step_key())
|
|
239
239
|
|
|
240
|
+
@s.step(timeout=s.hours(2), heartbeat_timeout=s.minutes(1))
|
|
241
|
+
async def export(table: str) -> int:
|
|
242
|
+
rows = 0
|
|
243
|
+
async for page in db.pages(table):
|
|
244
|
+
rows += await upload_page(page)
|
|
245
|
+
s.heartbeat() # alive: a hung page fails within a minute
|
|
246
|
+
return rows
|
|
247
|
+
|
|
240
248
|
size = await c.step("size", lambda: os.path.getsize(archive)) # an inline step
|
|
241
249
|
a, b = await asyncio.gather(fetch(url_a), fetch(url_b)) # steps in parallel
|
|
242
250
|
sizes = await asyncio.gather(*[c.step("size", os.path.getsize, f) for f in files]) # arguments after the function
|
|
@@ -246,7 +254,7 @@ sizes = await asyncio.gather(*[c.step("size", os.path.getsize, f) for f in files
|
|
|
246
254
|
<summary>In Rust and TypeScript</summary>
|
|
247
255
|
|
|
248
256
|
```rust
|
|
249
|
-
#[s::step(retry = s::Retry { max_attempts: 5, initial: s::seconds(1), max: s::minutes(1), multiplier: 2.0 }, timeout = s::minutes(10))]
|
|
257
|
+
#[s::step(retry = s::Retry { max_attempts: 5, initial: s::seconds(1), max: s::minutes(1), multiplier: 2.0, deadline: None }, timeout = s::minutes(10))]
|
|
250
258
|
async fn upload(archive: &str, target: &str) -> anyhow::Result<String> {
|
|
251
259
|
s3.put(archive, target, s::step_key()).await
|
|
252
260
|
}
|
|
@@ -268,7 +276,7 @@ const [a, b] = await Promise.all([fetch(urlA), fetch(urlB)]); // st
|
|
|
268
276
|
|
|
269
277
|
</details>
|
|
270
278
|
|
|
271
|
-
An inline step takes its name first; in Python, the function's arguments may follow it, since a lambda in a comprehension would read the loop's last value. A crash during a step runs it again, so a step runs at least once: `s.step_key()` is the same for every attempt and replay, for an idempotency key. `raise s.Permanent(...)` fails a step without retrying it. Every attempt has a timeout: the step's own, else its workflow's `step_timeout`, else the worker's, 5 minutes by default. A step out of attempts raises `StepFailed`, whose `cause` is the last attempt's failure, such as `StepTimeout`. More in [I-6].
|
|
279
|
+
An inline step takes its name first; in Python, the function's arguments may follow it, since a lambda in a comprehension would read the loop's last value. A crash during a step runs it again, so a step runs at least once: `s.step_key()` is the same for every attempt and replay, for an idempotency key. `raise s.Permanent(...)` fails a step without retrying it. Every attempt has a timeout: the step's own, else its workflow's `step_timeout`, else the worker's, 5 minutes by default. A long step that calls `s.heartbeat()` as it progresses takes a `heartbeat_timeout` too, so an attempt that hangs fails long before its timeout. `s.Retry(..., deadline=s.minutes(5))` bounds the retries as a whole: no attempt starts once 5 minutes passed since the first one started. A step out of attempts raises `StepFailed`, whose `cause` is the last attempt's failure, such as `StepTimeout`. More in [I-6].
|
|
272
280
|
|
|
273
281
|
### Sleeping and waiting
|
|
274
282
|
|
|
@@ -401,6 +409,7 @@ Messages come from clients (`run.send`) or other runs (`c.send`), and a message
|
|
|
401
409
|
check = await c.start(verify, {"archive": archive}) # a run of its own
|
|
402
410
|
ok = await check.result()
|
|
403
411
|
await other.cancel("not needed") # a child ends cancelled
|
|
412
|
+
await c.start(reindex, {"archive": archive}, abandon=True) # goes on after this run ends
|
|
404
413
|
paid = await c.result("payment-42") # the end of any chain, a child or not
|
|
405
414
|
```
|
|
406
415
|
|
|
@@ -411,6 +420,7 @@ paid = await c.result("payment-42") # the end of any chain,
|
|
|
411
420
|
let check = c.start(&verify, VerifyInput { archive }).await?; // a run of its own
|
|
412
421
|
let ok = check.result().await?;
|
|
413
422
|
other.cancel("not needed").await?;
|
|
423
|
+
c.start(&reindex, ReindexInput { archive }).abandon().await?;
|
|
414
424
|
let paid: Paid = c.result("payment-42").await?;
|
|
415
425
|
```
|
|
416
426
|
|
|
@@ -418,12 +428,13 @@ let paid: Paid = c.result("payment-42").await?;
|
|
|
418
428
|
const check = await c.start(verify, { archive }); // a run of its own
|
|
419
429
|
const ok = await check.result();
|
|
420
430
|
await other.cancel("not needed");
|
|
431
|
+
await c.start(reindex, { archive }, { abandon: true });
|
|
421
432
|
const paid = await c.result<Paid>("payment-42");
|
|
422
433
|
```
|
|
423
434
|
|
|
424
435
|
</details>
|
|
425
436
|
|
|
426
|
-
A parent cancels a child it started as a client would, its outcome recorded. `c.result` awaits the end of any chain, without polling: the awaited run tells the waiting one when it ends. A child may start itself, for recursion over a tree, and may be a workflow of another language, through a stub of the same name. More in [I-11] and [I-5].
|
|
437
|
+
A parent cancels a child it started as a client would, its outcome recorded. A run's end, completed, failed or cancelled, cancels its children still running, but those started with `abandon`. `c.result` awaits the end of any chain, without polling: the awaited run tells the waiting one when it ends. A child may start itself, for recursion over a tree, and may be a workflow of another language, through a stub of the same name. More in [I-11] and [I-5].
|
|
427
438
|
|
|
428
439
|
### Loops and continue as new
|
|
429
440
|
|
|
@@ -467,7 +478,7 @@ for await (const w of c.iterate(new Walk())) {
|
|
|
467
478
|
|
|
468
479
|
</details>
|
|
469
480
|
|
|
470
|
-
Once the history passes a threshold, `iterate` continues the run as a new one carrying the loop's state, and only it, so a loop can run forever on a short history. `await c.continue_as_new(input)` does it by hand. More in [I-12].
|
|
481
|
+
Once the history passes a threshold, `iterate` continues the run as a new one carrying the loop's state, and only it, so a loop can run forever on a short history. `await c.continue_as_new(input)` does it by hand. A loop keeps its version through its continuations; `c.iterate(Walk(), upgrade=True)` (TypeScript `{ upgrade: true }`, Rust `.upgrade()`) moves it at its next iteration to the highest version of its workflow the worker serves, and `c.schedule(upgrade=True)` does the same for a schedule, which `sub.schedule` with the new version then moves instead of raising `RunExists`. More in [I-12] and [I-31].
|
|
471
482
|
|
|
472
483
|
### Undo and sagas
|
|
473
484
|
|
|
@@ -561,9 +572,10 @@ async with s.Substantial.open(url) as sub: ... # closed at the end
|
|
|
561
572
|
run = await sub.start(checkout, {"order": "a-42", "amount": 1999}, id="order-a-42")
|
|
562
573
|
run = sub.run(checkout, "order-a-42") # a handle on an existing run
|
|
563
574
|
await run.send("address", "1 rue du Lac", id="address-a-42")
|
|
564
|
-
status = await run.status() # pending, running, suspended, completed, failed, cancelled
|
|
575
|
+
status = await run.status() # pending, running, suspended, blocked, completed, failed, cancelled
|
|
565
576
|
result = await run.result(timeout=s.hours(2))
|
|
566
577
|
progress = await run.read("progress") # what the run published with c.publish
|
|
578
|
+
cart = await sub.start(shopping, {}, id="cart-7", message=s.Message("add", item, id="add-1")) # starts or finds it, then sends
|
|
567
579
|
```
|
|
568
580
|
|
|
569
581
|
<details>
|
|
@@ -577,6 +589,7 @@ run.send("address", "1 rue du Lac").id("address-a-42").await?;
|
|
|
577
589
|
let status = run.status().await?; // an s::RunStatus
|
|
578
590
|
let result = run.result().timeout(s::hours(2)).await?;
|
|
579
591
|
let progress: Option<Progress> = run.read("progress").await?;
|
|
592
|
+
let cart = sub.start(shopping, Cart {}).id("cart-7").message(s::Message::new("add", item).id("add-1")).await?;
|
|
580
593
|
```
|
|
581
594
|
|
|
582
595
|
```ts
|
|
@@ -587,17 +600,18 @@ await run.send("address", "1 rue du Lac", { id: "address-a-42" });
|
|
|
587
600
|
const status = await run.status();
|
|
588
601
|
const result = await run.result({ timeout: s.hours(2) });
|
|
589
602
|
const progress = await run.read("progress");
|
|
603
|
+
const cart = await sub.start(shopping, {}, { id: "cart-7", message: { name: "add", value: item, id: "add-1" } });
|
|
590
604
|
```
|
|
591
605
|
|
|
592
606
|
</details>
|
|
593
607
|
|
|
594
|
-
`create` makes the namespace or opens it; `open` refuses one that does not exist. A Rust `Substantial` is freed when dropped. More in [I-16] and [I-17].
|
|
608
|
+
`create` makes the namespace or opens it; `open` refuses one that does not exist. A start given a `message` sends it once the run is created or found, so the first event of a cart both starts it and lands in it. A Rust `Substantial` is freed when dropped. More in [I-16] and [I-17].
|
|
595
609
|
|
|
596
610
|
### Live runs, history and retry
|
|
597
611
|
|
|
598
612
|
```python
|
|
599
|
-
async for info in sub.runs(checkout): # pending, waiting on time or messages, every version
|
|
600
|
-
print(info.run, info.version, info.waiting_on, info.due_at)
|
|
613
|
+
async for info in sub.runs(checkout): # pending, waiting on time or messages, blocked, every version
|
|
614
|
+
print(info.run, info.version, info.waiting_on, info.due_at, info.error)
|
|
601
615
|
|
|
602
616
|
for event in await run.history(): # the events its replays read
|
|
603
617
|
print(event.segment, event.at, event.kind, event.data)
|
|
@@ -607,6 +621,13 @@ try:
|
|
|
607
621
|
except s.RunFailed:
|
|
608
622
|
... # fix the code, or wait out the outage
|
|
609
623
|
await run.retry() # recorded steps return their values, the failed step runs again
|
|
624
|
+
|
|
625
|
+
await run.retry(keep=3) # an ended run reset: its first 3 events kept, the rest run again
|
|
626
|
+
|
|
627
|
+
@s.workflow
|
|
628
|
+
async def refund(c: s.Context, order: str) -> None:
|
|
629
|
+
if not await c.step("eligible", is_eligible, order):
|
|
630
|
+
raise s.Fail("NotEligible", f"order {order} is past its refund window") # ends the run failed
|
|
610
631
|
```
|
|
611
632
|
|
|
612
633
|
<details>
|
|
@@ -625,6 +646,9 @@ for event in run.history().await? {
|
|
|
625
646
|
if run.result().await.is_err() {
|
|
626
647
|
run.retry().await?;
|
|
627
648
|
}
|
|
649
|
+
run.retry().keep(3).await?; // an ended run reset
|
|
650
|
+
|
|
651
|
+
return Err(s::Error::fail("NotEligible", format!("order {order} is past its refund window")));
|
|
628
652
|
```
|
|
629
653
|
|
|
630
654
|
```ts
|
|
@@ -636,11 +660,14 @@ try {
|
|
|
636
660
|
if (!(e instanceof s.RunFailed)) throw e;
|
|
637
661
|
await run.retry();
|
|
638
662
|
}
|
|
663
|
+
await run.retry({ keep: 3 }); // an ended run reset
|
|
664
|
+
|
|
665
|
+
throw new s.Fail("NotEligible", `order ${order} is past its refund window`);
|
|
639
666
|
```
|
|
640
667
|
|
|
641
668
|
</details>
|
|
642
669
|
|
|
643
|
-
`runs` reads a workflow's queue, never its histories: ended runs are not listed, though one that just ended may be for a moment. `retry` starts a new run of the chain that replays the failed one without its failure, so a payment that succeeded is not charged again and the failed step gets a fresh retry budget; `s.step_key()` stays the same. More in [I-17].
|
|
670
|
+
A bug of the code, an exception it lets out or a change its history does not match, blocks the run instead of failing it: nothing is recorded, the worker logs a warning and tells its observer, `status` reads `blocked`, `runs` lists the run with its error, and the run is tried again with a backoff until a deploy fixes or rolls back the code, then goes on as if nothing happened. A run fails only with an outcome Substantial recorded, a step out of attempts, a budget passed, a rollback, or `s.Fail`, which the code raises on purpose. `runs` reads a workflow's queue, never its histories: ended runs are not listed, though one that just ended may be for a moment. `retry(keep=n)` resets an ended run, completed, failed or cancelled, to its first `n` events of `history()` and runs the code live from there. `retry` starts a new run of the chain that replays the failed one without its failure, so a payment that succeeded is not charged again and the failed step gets a fresh retry budget; `s.step_key()` stays the same. More in [I-17].
|
|
644
671
|
|
|
645
672
|
### Cost, budgets and observing
|
|
646
673
|
|
|
@@ -724,6 +751,9 @@ The core counts each run's store requests, the adapter's retries included, and w
|
|
|
724
751
|
```python
|
|
725
752
|
@s.workflow(name="checkout", version=2)
|
|
726
753
|
async def checkout_v2(c: s.Context, order: str, amount: int) -> dict: ...
|
|
754
|
+
|
|
755
|
+
if c.patched("fraud-check"): # true for runs that reach it with this code, false for older ones
|
|
756
|
+
await c.step("fraud", check_fraud, order)
|
|
727
757
|
```
|
|
728
758
|
|
|
729
759
|
<details>
|
|
@@ -732,15 +762,28 @@ async def checkout_v2(c: s.Context, order: str, amount: int) -> dict: ...
|
|
|
732
762
|
```rust
|
|
733
763
|
#[s::workflow(name = "checkout", version = 2)]
|
|
734
764
|
async fn checkout_v2(c: s::Context, input: Order) -> s::Result<Receipt> { ... }
|
|
765
|
+
|
|
766
|
+
if c.patched("fraud-check")? {
|
|
767
|
+
check_fraud(order.clone()).await?;
|
|
768
|
+
}
|
|
735
769
|
```
|
|
736
770
|
|
|
737
771
|
```ts
|
|
738
772
|
const checkoutV2 = s.workflow("checkout", async (c, input: Order) => { ... }, { version: 2 });
|
|
773
|
+
|
|
774
|
+
if (c.patched("fraud-check")) await checkFraud(order);
|
|
739
775
|
```
|
|
740
776
|
|
|
741
777
|
</details>
|
|
742
778
|
|
|
743
|
-
A run started with a version is replayed only by that version's code, so old and new code serve their runs side by side through a deploy.
|
|
779
|
+
A run started with a version is replayed only by that version's code, so old and new code serve their runs side by side through a deploy. A smaller change needs no version: `c.patched(id)` records which branch a run takes, true when the run first reaches it with the new code, false when it replays a history recorded before, so runs in flight keep their histories. To know whether new code still matches the runs in flight, replay them in CI before the deploy: the replay tester copies them from the store and replays them against their histories, writing nothing to the store and running no step.
|
|
780
|
+
|
|
781
|
+
```python
|
|
782
|
+
replayed = await s.testing.replay(url, [checkout], runs=[info.run async for info in sub.runs(checkout)], credentials="env")
|
|
783
|
+
assert [r.run for r in replayed if r.outcome == "diverged"] == [] # else give the change a new version
|
|
784
|
+
```
|
|
785
|
+
|
|
786
|
+
More in [I-5] and [I-19].
|
|
744
787
|
|
|
745
788
|
### Stores
|
|
746
789
|
|
|
@@ -748,7 +791,7 @@ A run started with a version is replayed only by that version's code, so old and
|
|
|
748
791
|
| --- | --- |
|
|
749
792
|
| `memory://<ns>` | memory, in the process, for tests |
|
|
750
793
|
| `file:<path>` | a directory, for development and one machine |
|
|
751
|
-
| `s3://<endpoint>/<bucket>/<ns>?region=<r>` | S3 with conditional writes: AWS, MinIO, Ceph RGW, R2 |
|
|
794
|
+
| `s3://<endpoint>/<bucket>/<ns>?region=<r>` | a versioned S3 bucket with conditional writes: AWS, MinIO, Ceph RGW, R2 |
|
|
752
795
|
| `redis://<host>:<port>/<ns>?db=0&replicas=0`, `redis+sentinel://`, `redis+cluster://` | Redis or Valkey 7.2+ with AOF, one server, Sentinel or a cluster, every create fsynced on every replica; workers wake as soon as a run is started or messaged |
|
|
753
796
|
|
|
754
797
|
```python
|
|
@@ -780,7 +823,7 @@ const sub = await s.Substantial.open(redisUrl, {
|
|
|
780
823
|
|
|
781
824
|
</details>
|
|
782
825
|
|
|
783
|
-
S3 takes `"env"` (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN`), explicit `s.Credentials(...)`, or a function, sync or async, returning keys with an optional `expires_at`: it is called at open and again within 5 minutes of that expiry, for roles and other temporary keys. `s3+http://` reaches a local server. Redis takes none, `"env"` (`REDIS_PASSWORD`, `REDIS_USERNAME`), a password, or such a function returning one (`s::Credentials::password_provider` in Rust).
|
|
826
|
+
S3 takes `"env"` (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN`), explicit `s.Credentials(...)`, or a function, sync or async, returning keys with an optional `expires_at`: it is called at open and again within 5 minutes of that expiry, for roles and other temporary keys. `s3+http://` reaches a local server. Redis takes none, `"env"` (`REDIS_PASSWORD`, `REDIS_USERNAME`), a password, or such a function returning one (`s::Credentials::password_provider` in Rust). An ended run stays readable by its id, and its id refused to a new start, for 30 days after it ends, or the `retention` in whole days a worker or a workflow sets (Python `retention=30`, TypeScript `retention: 30`, Rust `.set("retention", "30d")` or `.with_retention(30)`), and as long as a run it started is kept; then the store removes it by itself, with no worker involved. On S3, each retention in use needs one lifecycle rule of the bucket, which a worker checks when it starts, failing with the JSON of the rule to add. Bucket versioning is optional. Never delete keys under a namespace yourself. More in [I-16].
|
|
784
827
|
|
|
785
828
|
### Workers
|
|
786
829
|
|
|
@@ -827,7 +870,7 @@ await sub.worker([nightly, report], { preset: "script" }).drain({ within: s.minu
|
|
|
827
870
|
|
|
828
871
|
</details>
|
|
829
872
|
|
|
830
|
-
`drain` serves every run due now or within 2 minutes, takes over the runs of crashed workers whose
|
|
873
|
+
`drain` serves every run due now or within 2 minutes, takes over the runs of crashed workers whose leases expire by then, and returns once nothing is due within that horizon and nothing is in flight; between two jobs no worker lists the store. A schedule it serves needs a `backfill` of at least the job's period divided by the cron's. More in [I-18] and the [integration] guide.
|
|
831
874
|
|
|
832
875
|
### Wasm workflows
|
|
833
876
|
|
|
@@ -881,9 +924,10 @@ A Wasm workflow has no network, clock or filesystem: its workflow code calls onl
|
|
|
881
924
|
|
|
882
925
|
## How it works
|
|
883
926
|
|
|
884
|
-
- **No broker, no server.** Workers and clients coordinate through the store alone, with
|
|
885
|
-
- **Checked at open.** Opening a namespace
|
|
886
|
-
- **
|
|
927
|
+
- **No broker, no server.** Workers and clients coordinate through the store alone, with six operations: an exclusive create, a compare-and-set naming an ETag, a get, a list, a delete, and an expiry in days that every write carries. A chain of runs is one object, its head, rewritten at every commit only if it is still the value its writer read, so of two workers racing on a run one wins. Every run stays readable by its id, the runs a chain continued from in archives. A worker leases a run in its head before it runs a step, and finds due runs, timers and messages by listing the entries of each workflow it serves, one prefix per workflow.
|
|
928
|
+
- **Checked at open.** Opening a namespace refuses a store that accepts two creates of one key, writes under an ETag that is not the key's, or brings a deleted key back, as an S3-compatible store ignoring conditional writes would.
|
|
929
|
+
- **Removed by the store.** An ended run expires with its retention: S3 lifecycle rules, Redis expiries and the file store's sweep remove it, with no worker collecting anything, so a namespace stops growing.
|
|
930
|
+
- **What it costs.** On S3 a run costs its requests: a commit is one write of its head, a wakeup one read. The per-verb counts and the monthly cost of typical workflows are in [the architecture](https://github.com/zifeo/substantial/blob/main/docs/architecture.md). An idle worker of the `service` preset lists each workflow it serves every 30 s, $0.43 a month per workflow.
|
|
887
931
|
- **One core.** The protocol lives in a core compiled to WebAssembly, with no I/O, clock or randomness of its own. Every host loads the same module and only runs your code and talks to the store, so a namespace can be shared by workers and clients in all three languages.
|
|
888
932
|
|
|
889
933
|
The store contract and the core's boundary are in [the reference][I-22]. What each verb does to the store, its round trips, its failure behaviour and its monthly cost on S3 are in [the architecture](https://github.com/zifeo/substantial/blob/main/docs/architecture.md).
|
|
@@ -896,17 +940,15 @@ uv run pytest
|
|
|
896
940
|
npm ci && npm run check && npm test
|
|
897
941
|
```
|
|
898
942
|
|
|
899
|
-
The
|
|
900
|
-
|
|
901
|
-
The S3 tests run when `SUBSTANTIAL_S3_URL` is set, against a local RustFS:
|
|
943
|
+
The tests run against every store, S3 on a local RustFS and Redis on Valkey standalone, with Sentinel and as a cluster, all in `dev/compose.yaml`. Start them first: a test whose store does not answer fails, none is skipped.
|
|
902
944
|
|
|
903
945
|
```sh
|
|
904
|
-
docker compose -f dev/
|
|
905
|
-
|
|
906
|
-
SUBSTANTIAL_S3_URL='s3+http://127.0.0.1:39400/substantial/tests?region=us-east-1' \
|
|
907
|
-
cargo test --workspace # or uv run pytest, or npm test
|
|
946
|
+
docker compose -f dev/compose.yaml up -d --wait
|
|
947
|
+
cargo test --workspace --all-features # or uv run pytest, or npm test
|
|
908
948
|
```
|
|
909
949
|
|
|
950
|
+
`dev/stores.env` gives the tests of every host and `dev/cross` the URL and test credentials of each store; a variable set in the environment wins over its line there. The Rust Redis tests need the `redis` feature.
|
|
951
|
+
|
|
910
952
|
Each host has two examples on a file or memory store, `first_workflow` and `backup`: `cargo run -p substantial --example first_workflow -- /tmp/demo`, `uv run python/examples/first_workflow.py /tmp/demo-py`, `node --conditions=substantial-source typescript/examples/first_workflow.ts /tmp/demo-ts`.
|
|
911
953
|
|
|
912
954
|
`rust/wasm` and `rust/proto` are symlinks to `wasm/` and `proto/`, so that the published crate carries them. `npm run gen` regenerates the TypeScript protobuf code from `proto/`.
|
|
@@ -929,6 +971,7 @@ Each host has two examples on a file or memory store, `first_workflow` and `back
|
|
|
929
971
|
[I-16]: https://github.com/zifeo/substantial/blob/main/docs/interfaces.md#i-16-creating-and-opening-a-namespace
|
|
930
972
|
[I-17]: https://github.com/zifeo/substantial/blob/main/docs/interfaces.md#i-17-starting-and-following-runs
|
|
931
973
|
[I-18]: https://github.com/zifeo/substantial/blob/main/docs/interfaces.md#i-18-workers
|
|
974
|
+
[I-19]: https://github.com/zifeo/substantial/blob/main/docs/interfaces.md#i-19-testing
|
|
932
975
|
[I-21]: https://github.com/zifeo/substantial/blob/main/docs/interfaces.md#i-21-actions-in-each-host
|
|
933
976
|
[I-22]: https://github.com/zifeo/substantial/blob/main/docs/interfaces.md#i-22-for-implementers
|
|
934
977
|
[I-27]: https://github.com/zifeo/substantial/blob/main/docs/interfaces.md#i-27-cost-and-charges
|
|
@@ -54,7 +54,7 @@ shipping a-42 to 1 rue du Lac, Lausanne
|
|
|
54
54
|
```
|
|
55
55
|
|
|
56
56
|
- `charge` and `ship` are steps: their results are recorded, and the function, replayed from its first line at every wakeup, gets them back without running them again. A step can be declared, as `charge` is with its retry of up to five attempts and an exponential backoff, or wrapped inline on the fly under a name, as `c.step("ship", ...)` does with `ship`, a plain function.
|
|
57
|
-
- `c.receive("address")` takes the message the client sends with `run.send`. A message sent before the workflow asks for it waits in the
|
|
57
|
+
- `c.receive("address")` takes the message the client sends with `run.send`. A message sent before the workflow asks for it waits in the store until the workflow takes it.
|
|
58
58
|
- `c.sleep` is a durable timer: while it waits, the run is suspended and holds no process.
|
|
59
59
|
- The worker runs the workflow; the client starts it, messages it and awaits its result. They can be the same process, as here, or many processes on many machines sharing the store. Leaving `async with` stops the worker, then closes the client.
|
|
60
60
|
- `id="order-a-42"` makes the start idempotent: starting it again finds the same run.
|
|
@@ -80,7 +80,7 @@ struct Receipt {
|
|
|
80
80
|
tracking: String,
|
|
81
81
|
}
|
|
82
82
|
|
|
83
|
-
#[s::step(retry = s::Retry { max_attempts: 5, initial: s::seconds(1), max: s::minutes(1), multiplier: 2.0 })]
|
|
83
|
+
#[s::step(retry = s::Retry { max_attempts: 5, initial: s::seconds(1), max: s::minutes(1), multiplier: 2.0, deadline: None })]
|
|
84
84
|
async fn charge(order: &str, amount: u32) -> anyhow::Result<String> {
|
|
85
85
|
println!("charging {amount} for {order}");
|
|
86
86
|
Ok(format!("pay-{order}"))
|
|
@@ -219,6 +219,14 @@ A run replays its function from the first line at every wakeup. So side effects
|
|
|
219
219
|
async def upload(archive: str, target: str) -> str:
|
|
220
220
|
return await s3.put(archive, target, idempotency_key=s.step_key())
|
|
221
221
|
|
|
222
|
+
@s.step(timeout=s.hours(2), heartbeat_timeout=s.minutes(1))
|
|
223
|
+
async def export(table: str) -> int:
|
|
224
|
+
rows = 0
|
|
225
|
+
async for page in db.pages(table):
|
|
226
|
+
rows += await upload_page(page)
|
|
227
|
+
s.heartbeat() # alive: a hung page fails within a minute
|
|
228
|
+
return rows
|
|
229
|
+
|
|
222
230
|
size = await c.step("size", lambda: os.path.getsize(archive)) # an inline step
|
|
223
231
|
a, b = await asyncio.gather(fetch(url_a), fetch(url_b)) # steps in parallel
|
|
224
232
|
sizes = await asyncio.gather(*[c.step("size", os.path.getsize, f) for f in files]) # arguments after the function
|
|
@@ -228,7 +236,7 @@ sizes = await asyncio.gather(*[c.step("size", os.path.getsize, f) for f in files
|
|
|
228
236
|
<summary>In Rust and TypeScript</summary>
|
|
229
237
|
|
|
230
238
|
```rust
|
|
231
|
-
#[s::step(retry = s::Retry { max_attempts: 5, initial: s::seconds(1), max: s::minutes(1), multiplier: 2.0 }, timeout = s::minutes(10))]
|
|
239
|
+
#[s::step(retry = s::Retry { max_attempts: 5, initial: s::seconds(1), max: s::minutes(1), multiplier: 2.0, deadline: None }, timeout = s::minutes(10))]
|
|
232
240
|
async fn upload(archive: &str, target: &str) -> anyhow::Result<String> {
|
|
233
241
|
s3.put(archive, target, s::step_key()).await
|
|
234
242
|
}
|
|
@@ -250,7 +258,7 @@ const [a, b] = await Promise.all([fetch(urlA), fetch(urlB)]); // st
|
|
|
250
258
|
|
|
251
259
|
</details>
|
|
252
260
|
|
|
253
|
-
An inline step takes its name first; in Python, the function's arguments may follow it, since a lambda in a comprehension would read the loop's last value. A crash during a step runs it again, so a step runs at least once: `s.step_key()` is the same for every attempt and replay, for an idempotency key. `raise s.Permanent(...)` fails a step without retrying it. Every attempt has a timeout: the step's own, else its workflow's `step_timeout`, else the worker's, 5 minutes by default. A step out of attempts raises `StepFailed`, whose `cause` is the last attempt's failure, such as `StepTimeout`. More in [I-6].
|
|
261
|
+
An inline step takes its name first; in Python, the function's arguments may follow it, since a lambda in a comprehension would read the loop's last value. A crash during a step runs it again, so a step runs at least once: `s.step_key()` is the same for every attempt and replay, for an idempotency key. `raise s.Permanent(...)` fails a step without retrying it. Every attempt has a timeout: the step's own, else its workflow's `step_timeout`, else the worker's, 5 minutes by default. A long step that calls `s.heartbeat()` as it progresses takes a `heartbeat_timeout` too, so an attempt that hangs fails long before its timeout. `s.Retry(..., deadline=s.minutes(5))` bounds the retries as a whole: no attempt starts once 5 minutes passed since the first one started. A step out of attempts raises `StepFailed`, whose `cause` is the last attempt's failure, such as `StepTimeout`. More in [I-6].
|
|
254
262
|
|
|
255
263
|
### Sleeping and waiting
|
|
256
264
|
|
|
@@ -383,6 +391,7 @@ Messages come from clients (`run.send`) or other runs (`c.send`), and a message
|
|
|
383
391
|
check = await c.start(verify, {"archive": archive}) # a run of its own
|
|
384
392
|
ok = await check.result()
|
|
385
393
|
await other.cancel("not needed") # a child ends cancelled
|
|
394
|
+
await c.start(reindex, {"archive": archive}, abandon=True) # goes on after this run ends
|
|
386
395
|
paid = await c.result("payment-42") # the end of any chain, a child or not
|
|
387
396
|
```
|
|
388
397
|
|
|
@@ -393,6 +402,7 @@ paid = await c.result("payment-42") # the end of any chain,
|
|
|
393
402
|
let check = c.start(&verify, VerifyInput { archive }).await?; // a run of its own
|
|
394
403
|
let ok = check.result().await?;
|
|
395
404
|
other.cancel("not needed").await?;
|
|
405
|
+
c.start(&reindex, ReindexInput { archive }).abandon().await?;
|
|
396
406
|
let paid: Paid = c.result("payment-42").await?;
|
|
397
407
|
```
|
|
398
408
|
|
|
@@ -400,12 +410,13 @@ let paid: Paid = c.result("payment-42").await?;
|
|
|
400
410
|
const check = await c.start(verify, { archive }); // a run of its own
|
|
401
411
|
const ok = await check.result();
|
|
402
412
|
await other.cancel("not needed");
|
|
413
|
+
await c.start(reindex, { archive }, { abandon: true });
|
|
403
414
|
const paid = await c.result<Paid>("payment-42");
|
|
404
415
|
```
|
|
405
416
|
|
|
406
417
|
</details>
|
|
407
418
|
|
|
408
|
-
A parent cancels a child it started as a client would, its outcome recorded. `c.result` awaits the end of any chain, without polling: the awaited run tells the waiting one when it ends. A child may start itself, for recursion over a tree, and may be a workflow of another language, through a stub of the same name. More in [I-11] and [I-5].
|
|
419
|
+
A parent cancels a child it started as a client would, its outcome recorded. A run's end, completed, failed or cancelled, cancels its children still running, but those started with `abandon`. `c.result` awaits the end of any chain, without polling: the awaited run tells the waiting one when it ends. A child may start itself, for recursion over a tree, and may be a workflow of another language, through a stub of the same name. More in [I-11] and [I-5].
|
|
409
420
|
|
|
410
421
|
### Loops and continue as new
|
|
411
422
|
|
|
@@ -449,7 +460,7 @@ for await (const w of c.iterate(new Walk())) {
|
|
|
449
460
|
|
|
450
461
|
</details>
|
|
451
462
|
|
|
452
|
-
Once the history passes a threshold, `iterate` continues the run as a new one carrying the loop's state, and only it, so a loop can run forever on a short history. `await c.continue_as_new(input)` does it by hand. More in [I-12].
|
|
463
|
+
Once the history passes a threshold, `iterate` continues the run as a new one carrying the loop's state, and only it, so a loop can run forever on a short history. `await c.continue_as_new(input)` does it by hand. A loop keeps its version through its continuations; `c.iterate(Walk(), upgrade=True)` (TypeScript `{ upgrade: true }`, Rust `.upgrade()`) moves it at its next iteration to the highest version of its workflow the worker serves, and `c.schedule(upgrade=True)` does the same for a schedule, which `sub.schedule` with the new version then moves instead of raising `RunExists`. More in [I-12] and [I-31].
|
|
453
464
|
|
|
454
465
|
### Undo and sagas
|
|
455
466
|
|
|
@@ -543,9 +554,10 @@ async with s.Substantial.open(url) as sub: ... # closed at the end
|
|
|
543
554
|
run = await sub.start(checkout, {"order": "a-42", "amount": 1999}, id="order-a-42")
|
|
544
555
|
run = sub.run(checkout, "order-a-42") # a handle on an existing run
|
|
545
556
|
await run.send("address", "1 rue du Lac", id="address-a-42")
|
|
546
|
-
status = await run.status() # pending, running, suspended, completed, failed, cancelled
|
|
557
|
+
status = await run.status() # pending, running, suspended, blocked, completed, failed, cancelled
|
|
547
558
|
result = await run.result(timeout=s.hours(2))
|
|
548
559
|
progress = await run.read("progress") # what the run published with c.publish
|
|
560
|
+
cart = await sub.start(shopping, {}, id="cart-7", message=s.Message("add", item, id="add-1")) # starts or finds it, then sends
|
|
549
561
|
```
|
|
550
562
|
|
|
551
563
|
<details>
|
|
@@ -559,6 +571,7 @@ run.send("address", "1 rue du Lac").id("address-a-42").await?;
|
|
|
559
571
|
let status = run.status().await?; // an s::RunStatus
|
|
560
572
|
let result = run.result().timeout(s::hours(2)).await?;
|
|
561
573
|
let progress: Option<Progress> = run.read("progress").await?;
|
|
574
|
+
let cart = sub.start(shopping, Cart {}).id("cart-7").message(s::Message::new("add", item).id("add-1")).await?;
|
|
562
575
|
```
|
|
563
576
|
|
|
564
577
|
```ts
|
|
@@ -569,17 +582,18 @@ await run.send("address", "1 rue du Lac", { id: "address-a-42" });
|
|
|
569
582
|
const status = await run.status();
|
|
570
583
|
const result = await run.result({ timeout: s.hours(2) });
|
|
571
584
|
const progress = await run.read("progress");
|
|
585
|
+
const cart = await sub.start(shopping, {}, { id: "cart-7", message: { name: "add", value: item, id: "add-1" } });
|
|
572
586
|
```
|
|
573
587
|
|
|
574
588
|
</details>
|
|
575
589
|
|
|
576
|
-
`create` makes the namespace or opens it; `open` refuses one that does not exist. A Rust `Substantial` is freed when dropped. More in [I-16] and [I-17].
|
|
590
|
+
`create` makes the namespace or opens it; `open` refuses one that does not exist. A start given a `message` sends it once the run is created or found, so the first event of a cart both starts it and lands in it. A Rust `Substantial` is freed when dropped. More in [I-16] and [I-17].
|
|
577
591
|
|
|
578
592
|
### Live runs, history and retry
|
|
579
593
|
|
|
580
594
|
```python
|
|
581
|
-
async for info in sub.runs(checkout): # pending, waiting on time or messages, every version
|
|
582
|
-
print(info.run, info.version, info.waiting_on, info.due_at)
|
|
595
|
+
async for info in sub.runs(checkout): # pending, waiting on time or messages, blocked, every version
|
|
596
|
+
print(info.run, info.version, info.waiting_on, info.due_at, info.error)
|
|
583
597
|
|
|
584
598
|
for event in await run.history(): # the events its replays read
|
|
585
599
|
print(event.segment, event.at, event.kind, event.data)
|
|
@@ -589,6 +603,13 @@ try:
|
|
|
589
603
|
except s.RunFailed:
|
|
590
604
|
... # fix the code, or wait out the outage
|
|
591
605
|
await run.retry() # recorded steps return their values, the failed step runs again
|
|
606
|
+
|
|
607
|
+
await run.retry(keep=3) # an ended run reset: its first 3 events kept, the rest run again
|
|
608
|
+
|
|
609
|
+
@s.workflow
|
|
610
|
+
async def refund(c: s.Context, order: str) -> None:
|
|
611
|
+
if not await c.step("eligible", is_eligible, order):
|
|
612
|
+
raise s.Fail("NotEligible", f"order {order} is past its refund window") # ends the run failed
|
|
592
613
|
```
|
|
593
614
|
|
|
594
615
|
<details>
|
|
@@ -607,6 +628,9 @@ for event in run.history().await? {
|
|
|
607
628
|
if run.result().await.is_err() {
|
|
608
629
|
run.retry().await?;
|
|
609
630
|
}
|
|
631
|
+
run.retry().keep(3).await?; // an ended run reset
|
|
632
|
+
|
|
633
|
+
return Err(s::Error::fail("NotEligible", format!("order {order} is past its refund window")));
|
|
610
634
|
```
|
|
611
635
|
|
|
612
636
|
```ts
|
|
@@ -618,11 +642,14 @@ try {
|
|
|
618
642
|
if (!(e instanceof s.RunFailed)) throw e;
|
|
619
643
|
await run.retry();
|
|
620
644
|
}
|
|
645
|
+
await run.retry({ keep: 3 }); // an ended run reset
|
|
646
|
+
|
|
647
|
+
throw new s.Fail("NotEligible", `order ${order} is past its refund window`);
|
|
621
648
|
```
|
|
622
649
|
|
|
623
650
|
</details>
|
|
624
651
|
|
|
625
|
-
`runs` reads a workflow's queue, never its histories: ended runs are not listed, though one that just ended may be for a moment. `retry` starts a new run of the chain that replays the failed one without its failure, so a payment that succeeded is not charged again and the failed step gets a fresh retry budget; `s.step_key()` stays the same. More in [I-17].
|
|
652
|
+
A bug of the code, an exception it lets out or a change its history does not match, blocks the run instead of failing it: nothing is recorded, the worker logs a warning and tells its observer, `status` reads `blocked`, `runs` lists the run with its error, and the run is tried again with a backoff until a deploy fixes or rolls back the code, then goes on as if nothing happened. A run fails only with an outcome Substantial recorded, a step out of attempts, a budget passed, a rollback, or `s.Fail`, which the code raises on purpose. `runs` reads a workflow's queue, never its histories: ended runs are not listed, though one that just ended may be for a moment. `retry(keep=n)` resets an ended run, completed, failed or cancelled, to its first `n` events of `history()` and runs the code live from there. `retry` starts a new run of the chain that replays the failed one without its failure, so a payment that succeeded is not charged again and the failed step gets a fresh retry budget; `s.step_key()` stays the same. More in [I-17].
|
|
626
653
|
|
|
627
654
|
### Cost, budgets and observing
|
|
628
655
|
|
|
@@ -706,6 +733,9 @@ The core counts each run's store requests, the adapter's retries included, and w
|
|
|
706
733
|
```python
|
|
707
734
|
@s.workflow(name="checkout", version=2)
|
|
708
735
|
async def checkout_v2(c: s.Context, order: str, amount: int) -> dict: ...
|
|
736
|
+
|
|
737
|
+
if c.patched("fraud-check"): # true for runs that reach it with this code, false for older ones
|
|
738
|
+
await c.step("fraud", check_fraud, order)
|
|
709
739
|
```
|
|
710
740
|
|
|
711
741
|
<details>
|
|
@@ -714,15 +744,28 @@ async def checkout_v2(c: s.Context, order: str, amount: int) -> dict: ...
|
|
|
714
744
|
```rust
|
|
715
745
|
#[s::workflow(name = "checkout", version = 2)]
|
|
716
746
|
async fn checkout_v2(c: s::Context, input: Order) -> s::Result<Receipt> { ... }
|
|
747
|
+
|
|
748
|
+
if c.patched("fraud-check")? {
|
|
749
|
+
check_fraud(order.clone()).await?;
|
|
750
|
+
}
|
|
717
751
|
```
|
|
718
752
|
|
|
719
753
|
```ts
|
|
720
754
|
const checkoutV2 = s.workflow("checkout", async (c, input: Order) => { ... }, { version: 2 });
|
|
755
|
+
|
|
756
|
+
if (c.patched("fraud-check")) await checkFraud(order);
|
|
721
757
|
```
|
|
722
758
|
|
|
723
759
|
</details>
|
|
724
760
|
|
|
725
|
-
A run started with a version is replayed only by that version's code, so old and new code serve their runs side by side through a deploy.
|
|
761
|
+
A run started with a version is replayed only by that version's code, so old and new code serve their runs side by side through a deploy. A smaller change needs no version: `c.patched(id)` records which branch a run takes, true when the run first reaches it with the new code, false when it replays a history recorded before, so runs in flight keep their histories. To know whether new code still matches the runs in flight, replay them in CI before the deploy: the replay tester copies them from the store and replays them against their histories, writing nothing to the store and running no step.
|
|
762
|
+
|
|
763
|
+
```python
|
|
764
|
+
replayed = await s.testing.replay(url, [checkout], runs=[info.run async for info in sub.runs(checkout)], credentials="env")
|
|
765
|
+
assert [r.run for r in replayed if r.outcome == "diverged"] == [] # else give the change a new version
|
|
766
|
+
```
|
|
767
|
+
|
|
768
|
+
More in [I-5] and [I-19].
|
|
726
769
|
|
|
727
770
|
### Stores
|
|
728
771
|
|
|
@@ -730,7 +773,7 @@ A run started with a version is replayed only by that version's code, so old and
|
|
|
730
773
|
| --- | --- |
|
|
731
774
|
| `memory://<ns>` | memory, in the process, for tests |
|
|
732
775
|
| `file:<path>` | a directory, for development and one machine |
|
|
733
|
-
| `s3://<endpoint>/<bucket>/<ns>?region=<r>` | S3 with conditional writes: AWS, MinIO, Ceph RGW, R2 |
|
|
776
|
+
| `s3://<endpoint>/<bucket>/<ns>?region=<r>` | a versioned S3 bucket with conditional writes: AWS, MinIO, Ceph RGW, R2 |
|
|
734
777
|
| `redis://<host>:<port>/<ns>?db=0&replicas=0`, `redis+sentinel://`, `redis+cluster://` | Redis or Valkey 7.2+ with AOF, one server, Sentinel or a cluster, every create fsynced on every replica; workers wake as soon as a run is started or messaged |
|
|
735
778
|
|
|
736
779
|
```python
|
|
@@ -762,7 +805,7 @@ const sub = await s.Substantial.open(redisUrl, {
|
|
|
762
805
|
|
|
763
806
|
</details>
|
|
764
807
|
|
|
765
|
-
S3 takes `"env"` (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN`), explicit `s.Credentials(...)`, or a function, sync or async, returning keys with an optional `expires_at`: it is called at open and again within 5 minutes of that expiry, for roles and other temporary keys. `s3+http://` reaches a local server. Redis takes none, `"env"` (`REDIS_PASSWORD`, `REDIS_USERNAME`), a password, or such a function returning one (`s::Credentials::password_provider` in Rust).
|
|
808
|
+
S3 takes `"env"` (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN`), explicit `s.Credentials(...)`, or a function, sync or async, returning keys with an optional `expires_at`: it is called at open and again within 5 minutes of that expiry, for roles and other temporary keys. `s3+http://` reaches a local server. Redis takes none, `"env"` (`REDIS_PASSWORD`, `REDIS_USERNAME`), a password, or such a function returning one (`s::Credentials::password_provider` in Rust). An ended run stays readable by its id, and its id refused to a new start, for 30 days after it ends, or the `retention` in whole days a worker or a workflow sets (Python `retention=30`, TypeScript `retention: 30`, Rust `.set("retention", "30d")` or `.with_retention(30)`), and as long as a run it started is kept; then the store removes it by itself, with no worker involved. On S3, each retention in use needs one lifecycle rule of the bucket, which a worker checks when it starts, failing with the JSON of the rule to add. Bucket versioning is optional. Never delete keys under a namespace yourself. More in [I-16].
|
|
766
809
|
|
|
767
810
|
### Workers
|
|
768
811
|
|
|
@@ -809,7 +852,7 @@ await sub.worker([nightly, report], { preset: "script" }).drain({ within: s.minu
|
|
|
809
852
|
|
|
810
853
|
</details>
|
|
811
854
|
|
|
812
|
-
`drain` serves every run due now or within 2 minutes, takes over the runs of crashed workers whose
|
|
855
|
+
`drain` serves every run due now or within 2 minutes, takes over the runs of crashed workers whose leases expire by then, and returns once nothing is due within that horizon and nothing is in flight; between two jobs no worker lists the store. A schedule it serves needs a `backfill` of at least the job's period divided by the cron's. More in [I-18] and the [integration] guide.
|
|
813
856
|
|
|
814
857
|
### Wasm workflows
|
|
815
858
|
|
|
@@ -863,9 +906,10 @@ A Wasm workflow has no network, clock or filesystem: its workflow code calls onl
|
|
|
863
906
|
|
|
864
907
|
## How it works
|
|
865
908
|
|
|
866
|
-
- **No broker, no server.** Workers and clients coordinate through the store alone, with
|
|
867
|
-
- **Checked at open.** Opening a namespace
|
|
868
|
-
- **
|
|
909
|
+
- **No broker, no server.** Workers and clients coordinate through the store alone, with six operations: an exclusive create, a compare-and-set naming an ETag, a get, a list, a delete, and an expiry in days that every write carries. A chain of runs is one object, its head, rewritten at every commit only if it is still the value its writer read, so of two workers racing on a run one wins. Every run stays readable by its id, the runs a chain continued from in archives. A worker leases a run in its head before it runs a step, and finds due runs, timers and messages by listing the entries of each workflow it serves, one prefix per workflow.
|
|
910
|
+
- **Checked at open.** Opening a namespace refuses a store that accepts two creates of one key, writes under an ETag that is not the key's, or brings a deleted key back, as an S3-compatible store ignoring conditional writes would.
|
|
911
|
+
- **Removed by the store.** An ended run expires with its retention: S3 lifecycle rules, Redis expiries and the file store's sweep remove it, with no worker collecting anything, so a namespace stops growing.
|
|
912
|
+
- **What it costs.** On S3 a run costs its requests: a commit is one write of its head, a wakeup one read. The per-verb counts and the monthly cost of typical workflows are in [the architecture](https://github.com/zifeo/substantial/blob/main/docs/architecture.md). An idle worker of the `service` preset lists each workflow it serves every 30 s, $0.43 a month per workflow.
|
|
869
913
|
- **One core.** The protocol lives in a core compiled to WebAssembly, with no I/O, clock or randomness of its own. Every host loads the same module and only runs your code and talks to the store, so a namespace can be shared by workers and clients in all three languages.
|
|
870
914
|
|
|
871
915
|
The store contract and the core's boundary are in [the reference][I-22]. What each verb does to the store, its round trips, its failure behaviour and its monthly cost on S3 are in [the architecture](https://github.com/zifeo/substantial/blob/main/docs/architecture.md).
|
|
@@ -878,17 +922,15 @@ uv run pytest
|
|
|
878
922
|
npm ci && npm run check && npm test
|
|
879
923
|
```
|
|
880
924
|
|
|
881
|
-
The
|
|
882
|
-
|
|
883
|
-
The S3 tests run when `SUBSTANTIAL_S3_URL` is set, against a local RustFS:
|
|
925
|
+
The tests run against every store, S3 on a local RustFS and Redis on Valkey standalone, with Sentinel and as a cluster, all in `dev/compose.yaml`. Start them first: a test whose store does not answer fails, none is skipped.
|
|
884
926
|
|
|
885
927
|
```sh
|
|
886
|
-
docker compose -f dev/
|
|
887
|
-
|
|
888
|
-
SUBSTANTIAL_S3_URL='s3+http://127.0.0.1:39400/substantial/tests?region=us-east-1' \
|
|
889
|
-
cargo test --workspace # or uv run pytest, or npm test
|
|
928
|
+
docker compose -f dev/compose.yaml up -d --wait
|
|
929
|
+
cargo test --workspace --all-features # or uv run pytest, or npm test
|
|
890
930
|
```
|
|
891
931
|
|
|
932
|
+
`dev/stores.env` gives the tests of every host and `dev/cross` the URL and test credentials of each store; a variable set in the environment wins over its line there. The Rust Redis tests need the `redis` feature.
|
|
933
|
+
|
|
892
934
|
Each host has two examples on a file or memory store, `first_workflow` and `backup`: `cargo run -p substantial --example first_workflow -- /tmp/demo`, `uv run python/examples/first_workflow.py /tmp/demo-py`, `node --conditions=substantial-source typescript/examples/first_workflow.ts /tmp/demo-ts`.
|
|
893
935
|
|
|
894
936
|
`rust/wasm` and `rust/proto` are symlinks to `wasm/` and `proto/`, so that the published crate carries them. `npm run gen` regenerates the TypeScript protobuf code from `proto/`.
|
|
@@ -911,6 +953,7 @@ Each host has two examples on a file or memory store, `first_workflow` and `back
|
|
|
911
953
|
[I-16]: https://github.com/zifeo/substantial/blob/main/docs/interfaces.md#i-16-creating-and-opening-a-namespace
|
|
912
954
|
[I-17]: https://github.com/zifeo/substantial/blob/main/docs/interfaces.md#i-17-starting-and-following-runs
|
|
913
955
|
[I-18]: https://github.com/zifeo/substantial/blob/main/docs/interfaces.md#i-18-workers
|
|
956
|
+
[I-19]: https://github.com/zifeo/substantial/blob/main/docs/interfaces.md#i-19-testing
|
|
914
957
|
[I-21]: https://github.com/zifeo/substantial/blob/main/docs/interfaces.md#i-21-actions-in-each-host
|
|
915
958
|
[I-22]: https://github.com/zifeo/substantial/blob/main/docs/interfaces.md#i-22-for-implementers
|
|
916
959
|
[I-27]: https://github.com/zifeo/substantial/blob/main/docs/interfaces.md#i-27-cost-and-charges
|