durable-workflow 4.25.0

Rust client and worker SDK for Durable Workflow Cloud and self-hosted Server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
# Durable Workflow Rust SDK

[![Quality Gate](https://sonarcloud.io/api/project_badges/measure?project=durable-workflow_sdk-rust&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=durable-workflow_sdk-rust)
[![CI](https://github.com/durable-workflow/sdk-rust/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/durable-workflow/sdk-rust/actions/workflows/ci.yml)
[![Crates.io](https://img.shields.io/crates/v/durable-workflow.svg)](https://crates.io/crates/durable-workflow)
[![API docs](https://img.shields.io/badge/docs-rust.durable--workflow.com-0f766e.svg)](https://rust.durable-workflow.com/)
[![Rust 1.86+](https://img.shields.io/badge/rust-1.86%2B-orange.svg)](https://github.com/durable-workflow/sdk-rust/blob/main/Cargo.toml)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/durable-workflow/sdk-rust/blob/main/LICENSE)

`durable-workflow` is the first-party Rust client and worker SDK for
[Durable Workflow](https://durable-workflow.com/). Rust applications can start
and inspect workflows, run workflow and activity handlers, and exchange typed
Avro values with PHP, Python, and Rust workers through one durable runtime.

Use the SDK with a self-hosted Durable Workflow Server or a managed Durable
Workflow Cloud namespace. Your workers remain ordinary Rust processes and
scale independently from the runtime.

## Install

Rust `1.86` or newer is required.

```sh
cargo add durable-workflow
```

Applications using Tokio entry points should also enable the Tokio features
they need:

```sh
cargo add tokio --features macros,rt-multi-thread
```

## Run the example

[`examples/hello_world.rs`](https://github.com/durable-workflow/sdk-rust/blob/main/examples/hello_world.rs) is a complete typed
workflow and activity example. It starts a workflow, runs two activities,
demonstrates retry and failure handling, waits for completion, and prints the
result.

Start a bootstrapped [self-hosted Server](https://durable-workflow.com/docs/2.0/polyglot/server/),
then run the example from this repository:

```sh
DURABLE_WORKFLOW_SERVER_URL=http://127.0.0.1:8080 \
DURABLE_WORKFLOW_TOKEN=dev-token \
cargo run --example hello_world
```

Pass the Server origin without a trailing `/api`. `TASK_QUEUE` changes the
default `rust-workers` queue, and `GREETING_NAME` changes the example input.

For a provisioned Cloud namespace, use the exact runtime URL and the separate
client and worker credentials shown in Cloud:

```sh
DURABLE_WORKFLOW_RUNTIME_URL=https://cloud.durable-workflow.com/api/runtime/v1/namespaces/your-namespace-id \
DURABLE_WORKFLOW_RUNTIME_NAMESPACE=your.namespace \
DURABLE_WORKFLOW_CLIENT_TOKEN=your-client-token \
DURABLE_WORKFLOW_WORKER_TOKEN=your-worker-token \
cargo run --example hello_world
```

The namespace runtime URL is already complete. Do not append another `/api`.

## Migrate from Rust SDK 3

Nexus calls add `Error::NexusOperationFailed` and
`CancellationCallKind::ServiceOperation`. Both enums are now `non_exhaustive`.
Include a fallback arm when matching either enum outside this crate so future
error or cancellation kinds can be handled without another exhaustive-match
migration. Handle a Nexus failure at its original durable call; a committed
admission is separate from a synchronous completion.

`WorkflowTask`, `ActivityTask` and `QueryTask` retain optional, untrusted
observability metadata. `ActivityTask` also exposes optional workflow, run and
activity execution identities supplied by the runtime. When constructing task
structs directly, initialize the new optional fields to `None`. Receiving these
fields does not enable tracing, authorize work or invent missing correlation.
Task structs remain directly constructible. Future additions to their public
fields require another major release; extensible metadata inside the existing
optional JSON fields does not require new task literal fields.

Existing workflow histories are unchanged. Preserve the workflow's recorded
command sequence and verify representative histories before deployment. Nexus
authoring requires explicit worker opt-in and an installed Server capability;
ordinary worker registration does not enable it.

## Core API

- `Client` starts, signals, queries, updates, cancels, terminates, describes,
  and awaits workflow executions.
- `Worker` registers workflow, activity, query and update handlers and update
  validators, declares workflow signals, and long-polls task queues.
- `WorkflowContext` provides durable activities, timers, conditions, child
  workflows, side effects, version markers, parallel operations, selection,
  sagas, message streams, memo, search attributes, and continue-as-new.
- Typed registration and result helpers preserve Serde request and result
  types over the fixed Avro Value protocol.
- Activity options cover retries, start-to-close, schedule-to-start,
  schedule-to-close, heartbeat timeouts, cancellation, and heartbeats.

### Signal and update request IDs

Every signal and update sends a `request_id` body field: the key you pass to a
`*_with_request_id` method or `update_workflow`, or one generated per call. The
receipt carries it. The SDK never resends a signal or update by itself, so keep
the key (`Client::generate_signal_request_id()` gives you one up front) to retry
after a lost response.

On a Server that advertises `capabilities.command_request_keys` in
`Client::cluster_info()` (native 3.9.0 and later), the key is a durable command
key on the workflow instance. A retry with the same name, arguments and run
target returns the original receipt. The same key with a different name,
arguments or run target is refused with HTTP 409 `request_id_conflict`, and
nothing is written. Detect it with `Error::request_id_conflict()`, which names
the differing parts (`name`, `arguments` or `target_or_arguments`), the
`retained_command_id` and the key you sent. Don't retry it unchanged: send the
original input to recover the receipt, or use a new key.

```rust,no_run
# async fn approve(client: &durable_workflow::Client) -> durable_workflow::Result<()> {
match client
    .signal_workflow_with_request_id("order-1", "approve", ["Grace"], "approve-order-1")
    .await
{
    Err(error) if error.is_request_id_conflict() => {
        let conflict = error.request_id_conflict().expect("conflict details");
        eprintln!("{} is already {:?}", conflict.request_id, conflict.retained_command_id);
    }
    other => {
        other?;
    }
}
# Ok(())
# }
```

Keys are case-sensitive and 1 to 255 Unicode characters; a longer or empty key
is refused before anything is sent.

A key retained before the Server compared intent (for example a row written by
an older Server and kept through an upgrade) reads back as the original receipt
with `retained: true` and `intent_verified: false`. That is not a verified
match: the Server could not check that the retry's name and arguments equal the
original's. Signal receipts carry the flags; for an update, call
`update_workflow_receipt` (or `WorkflowHandle::update_receipt`) to get the full
receipt rather than only the result. If such a key matches more than one
retained command, the Server selects no receipt, writes nothing and answers 409
`request_id_ambiguous`: `Error::is_request_id_ambiguous()` and
`Error::request_id_ambiguous()` report it with the key you sent. Inspect the
workflow history, and use a new key for any new command.

Older Servers (PHP Server 2.x and native up to 3.8) don't compare input under
a key: a repeated signal key records a second signal, and an update retried
with changed arguments returns the original receipt.

### Pending updates and reading an outcome later

`update_workflow` waits for the update to complete. If the Server's wait ends
first, it answers HTTP 202 with no result, and the SDK returns
`Error::UpdateStillPending` with the `update_id`, `request_id`, current
`run_id` and full receipt. A handler that returned null is still `Ok(Null)`.

On a Server that advertises `capabilities.update_outcome_reads` in
`Client::cluster_info()` (native 3.6.0 and later),
`Client::update_outcome(workflow_id, update_id, wait_timeout_seconds)` reads
the same update by its id without submitting it again. It waits for the
outcome and returns the decoded result, or `Error::UpdateStillPending` again
while the update is still running. A failed update is `Error::Http` with status
422, and an unknown or pruned update id is 404 `update_not_found`
(`Error::is_update_not_found()`), which does not prove the update was never
admitted. `update_outcome_receipt` returns the raw receipt and can answer at
once with `UpdateWaitStage::Accepted`. Workflow and update ids must each be one
path segment (not empty, `.` or `..`), and an answer that is not a receipt for
the requested update is `Error::UnrecognizedUpdateOutcome`, never a result.

On any other Server, `update_outcome` returns
`Error::UpdateOutcomeReadsUnavailable` before reading anything; the SDK never
resubmits an update in place of reading it. There, call `update_workflow` again
with the same `request_id` to keep waiting.

```rust,no_run
# async fn rename(client: &durable_workflow::Client) -> durable_workflow::Result<()> {
use durable_workflow::Error;

let result = match client
    .update_workflow("order-1", "rename", ["Grace"], Some("rename-order-1"))
    .await
{
    Err(Error::UpdateStillPending(pending)) => {
        let update_id = pending.update_id.expect("Server receipt names the update");
        client.update_outcome("order-1", &update_id, Some(30)).await?
    }
    other => other?,
};
# let _ = result;
# Ok(())
# }
```

### Update validators

Register a validator next to an update handler to reject a bad request before
the update is accepted. The Server runs the validator first; nothing is
accepted until it approves. Returning an `UpdateRejection` rejects the update
with reason `update_validator_rejected`: the handler never runs, workflow code
never sees the update and no acceptance is recorded. The Server records only
the rejected update. `Ok(())` approves it, and the update is then accepted and
handled as usual.

```rust,no_run
# use std::sync::Arc;
# use durable_workflow::{json, UpdateRejection, Value, Worker};
# #[derive(Clone, Default)]
# struct Order { limit: u64 }
# fn configure(worker: &mut Worker) {
worker.register_update("orders", "approve", |_ctx, args| async move { Ok(args) });

// Reads only the arguments and the committed history in the QueryContext.
worker.register_update_validator("orders", "approve", |_ctx, args: Value| {
    if args[0].as_u64().unwrap_or_default() == 0 {
        return Err(UpdateRejection::new("amount must be positive")
            .with_validation_error("amount", "must be positive"));
    }
    Ok(())
});

// Or read the replayed state of a workflow registered with
// `register_replayed_workflow::<Order, _, _, _>`.
worker.register_replayed_update_validator(
    "orders",
    "increase",
    |_ctx, order: Arc<Order>, args: Value| {
        if args[0].as_u64().unwrap_or_default() > order.limit {
            return Err(UpdateRejection::new("amount exceeds the order limit"));
        }
        Ok(())
    },
);
# }
```

Validators are read-only and replay-stable. They receive the update's
arguments and a `QueryContext` over the run's committed history; the replayed
variant also gets a detached snapshot of the workflow's state, reconstructed as
for a replayed query. A validator has no way to schedule durable work, and if
one adds a workflow command through a context kept in state, the update is
rejected with failure type `UpdateValidatorCommandRefused` and nothing is
scheduled. State changes are discarded. Validators are not part of workflow
history, so they never run during replay. A validator that panics, or that the
worker cannot run (for example because replay fails), reports
`update_validation_worker_failed`, which is distinct from a rejection.

Each validator needs a registered update handler for the same workflow type
and update name, and a replayed validator needs the workflow registered with
`register_replayed_workflow` and the same state type; registration checks both. A worker with validators advertises them in its workflow
command contract (`update_validators`) and the `update_validation_tasks`
capability. `Worker::register` refuses a Server that does not advertise
synchronous update validation with multiplexed polling
(`Error::UpdateValidationUnavailable`); native Server already serves update
validation tasks. The worker's workflow long poll then also leases validation
tasks, under the same `max_concurrent_workflow_tasks` capacity, and answers each
one with an approval or a rejection, also while the worker is stopping. A
completion the Server fences because the lease moved on is logged, not retried.
Worker task metrics use `task_kind` `update_validation` with outcome `approved`,
`rejected`, `failed` or `expired`. Inside the worker a validator's refusal is
`Error::UpdateRejection`; callers never see that variant.

Worker interceptors wrap each validation task through
`execute_update_validation_task` (see [Worker interceptors](#worker-interceptors)).
They observe the validator's decision but cannot change it; a broken
interceptor chain reports `update_validation_worker_failed`, so nothing is
accepted.

Callers tell a rejection from a failed update without parsing messages.
`Error::update_validator_rejection()` returns the message, validation errors and
ids of an update the validator rejected; `Error::is_update_validation_failed()`
is true when no validator answered in time or the worker could not run it.
Updates to a validated workflow need a `request_id`, which `update_workflow`
always sends.

```rust,no_run
# async fn approve(client: &durable_workflow::Client) -> durable_workflow::Result<()> {
match client
    .update_workflow("order-1", "approve", [0], Some("approve-order-1"))
    .await
{
    Err(error) if error.is_update_validator_rejected() => {
        let rejection = error.update_validator_rejection().expect("rejection");
        eprintln!("rejected: {} {:?}", rejection.message, rejection.validation_errors);
    }
    other => {
        other?;
    }
}
# Ok(())
# }
```

### Condition predicate identities

`wait_condition!` derives the recorded predicate identity from the call site's
module path and the predicate's Rust tokens. Moving or renaming the workflow
module changes the identity even when the predicate behaves the same. Rust also
allows [`stringify!` output to change between compiler versions](https://doc.rust-lang.org/std/macro.stringify.html).
The SDK's minimum-supported and stable Rust CI jobs pin representative macro
fingerprints to detect that change before a toolchain upgrade is accepted.

Keep the module path and predicate identity stable while affected waits are
open, or drain those runs before moving the workflow. For workflows that need
identities independent of module moves, use
`ConditionWaitOptions::new("approval", "approval-rule-v1")` from the start.
An explicit identity must still change when predicate behavior changes.
Switching an existing macro fingerprint to a new label does not migrate its
recorded history; preserve the original fingerprint for those runs or drain
them first.

### Private certificate authorities

The SDK trusts bundled Mozilla public roots by default. It does not load the
operating system trust store or `SSL_CERT_FILE`. For a self-hosted Server or a
proxy using a private certificate authority, add its PEM root certificates:

```rust,no_run
use durable_workflow::Client;
# fn client() -> Result<Client, Box<dyn std::error::Error>> {
let client = Client::builder("https://workflow.internal")
    .additional_root_certificates_pem(std::fs::read("company-ca.pem")?)?
    .build()?;
# Ok(client)
# }
```

The bundle can contain multiple certificates, and repeated calls add more
roots. Bundled public roots remain enabled. The same configured HTTP client
handles control requests, worker polling and external payload transfers.
Certificate-chain and hostname verification remain enabled. A private CA does
not make a certificate for the wrong hostname valid. Client certificates
(mTLS) are not configured by this option.

If a certificate cannot be verified at all, `.danger_accept_invalid_certs(true)`
turns off certificate and hostname verification for every request the client
makes. It defaults to `false`. With it on, anyone on the network path can read
and change traffic, including bearer tokens, so prefer a private CA root.

### Raw Server requests

Typed `Client` methods are the API for applications. Tools that must reach
every Server route and report the Server's response unchanged, such as the
`dw` CLI, can send raw requests over the same configured transport:

```rust,no_run
use durable_workflow::{Client, RawRequest};
# async fn list(client: &Client) -> Result<(), durable_workflow::Error> {
let response = client
    .control_plane_request(
        RawRequest::get(["workflows", "order/42", "runs"]).query("page_size", "50"),
    )
    .await?;
if let Some(refusal) = response.refusal() {
    eprintln!("refused: {:?}", refusal.reason);
}
let body = response.error_for_status()?.json()?;
# let _ = body;
# Ok(())
# }
```

The SDK percent-encodes each path segment, keeps any path prefix in the base
URL, and sends the namespace, the plane's token and both version headers.
Every HTTP status comes back as a `RawResponse` with its exact body bytes and
headers. A raw request makes one attempt and never rewrites its body.
`worker_plane_request` also requires 2xx responses to echo a same-major,
equal-or-newer-minor worker protocol version.

### Worker concurrency

`Worker::max_concurrent_workflow_tasks(...)` and
`Worker::max_concurrent_activity_tasks(...)` each default to 10. `run` and
`run_until` keep up to those limits active independently for workflows and
activities. Each family has one long poll. After a claim is validated and
hydrated, the poller can fill another free slot while earlier tasks execute or
report completion. Use a value of 1 for serial execution within a task family.
Clones share their configured capacity, including concurrent `run_once` calls.

Heartbeats report unused slots from actual claimed tasks, including input and
history loading, callback execution and settlement. An empty long poll keeps
its capacity available. Success, failure, refusal and cancellation release the
local slot. Inline local activities occupy their workflow-task slot and bypass
the remote activity pool. Queries retain their separate polling lane.

Handlers run as async futures on Tokio and must yield. Use
`tokio::task::spawn_blocking` or a separate process for blocking work, with its own
cancellation boundary. A concurrency setting does not provide CPU isolation or
make blocking code cancellable.

### Worker response size

Every request sends `Accept-Encoding: gzip` and decodes compressed answers.
Worker-plane requests also send `X-Durable-Workflow-Server-Capabilities-Digest`
with the digest of the Server capabilities this Client already holds, or `none`.
A Server that supports it (native Server 3.17 or later) then replaces each repeated
`server_capabilities` object with that digest, or sends a full copy tagged with
a `digest` member when the capabilities changed. The Client captures the
digest and object when it sends each request and restores that request's
answer before anything reads it, so readers always see the full object, even
when requests overlap a rolling deploy. Clones share what they learned. An
answer naming a digest that request did not send, and that the answer itself
does not carry, makes the Client forget its digest. A task poll is resent once
asking for full capabilities. Any other request is never resent, since it may
already have committed: its answer is kept as received and the capabilities
are read from `GET /api/cluster/info`. If that read fails, the answer is still
used without the field and later requests learn the capabilities again. A
poll whose resend names an unknown digest again is `Error::Protocol` with
reason `server_capabilities_digest_unknown`. Older Servers ignore both headers and
answer in full.

A decoded response body is capped at 128 MiB by default. Set
`ClientBuilder::max_response_bytes` to change it; a larger body fails with
`Error::ResponseBodyTooLarge` without being read to the end.

### Query execution authority

On a runtime advertising `query_task_authority` with worker protocol 1.20,
`Worker` captures the original query claim before loading external inputs. It
checks ownership without renewing the lease during loading and execution, before
calling the handler, and before submitting its outcome. The original caller
deadline and lease bound the entire operation. Expiry, shutdown or an unavailable
observation drops the work without sending a completion or failure for it.

Use `Worker::require_query_task_authority(true)` to refuse registration unless
worker-authenticated discovery advertises this support. Without this requirement,
older runtimes and explicit protocol 1.19 keep compatibility: disclosed original
timing supplies a local bound, while deliveries without timing retain legacy
behavior. This path cannot observe live revocation and never calls the 1.20
query-status endpoint.

Async handlers must yield to Tokio to be cancelled promptly. Synchronous or
CPU-bound callbacks cannot be interrupted while they block, but their late result
is fenced before submission. Query handlers should avoid side effects. Direct
`Client` completion and failure methods remain available for inspecting an
original committed receipt.

### Handler registration

Register each workflow and activity wire name once per Worker. Named query and
update handlers are also scoped to their workflow type. Dynamic, typed, Avro and
replayed adapters share these namespaces. Repeating a registration, including
the same callback, is an error. Different Workers or handler kinds may reuse a
name, and queries or updates on different workflow types may reuse a name.

Registration methods keep their existing signatures. A duplicate preserves the
first handler and invalidates that Worker. Call `worker.validate_registration()?`
after configuring it for a local check. `register`, `run`, `run_until` and
`run_once` also reject it before contacting Server with `Error::WorkerLoop`
and a `duplicate_registration` diagnostic. Local validation returns the typed
`DuplicateRegistrationError`, exposing the handler kind, wire name, optional
workflow scope, and both source locations and authoring adapters. It converts
into the existing worker-error variant when used with `?`, preserving exhaustive
matches on the SDK's existing `Error` enum.
Construct a new Worker to correct an invalid configuration. Choose the desired
handler before registration instead of relying on replacement order.

After registering a workflow, declare every signal name it reads through
`wait_signal` or `signals` before starting the worker:

```rust,no_run
# fn declare_signals(worker: &mut durable_workflow::Worker) -> durable_workflow::Result<()> {
worker.declare_workflow_signals("orders", &["finish", "changed"])?;
# Ok(())
# }
```

Server records those names and positional argument contracts when starting a
run. Changing worker declarations does not change existing runs.

The SDK writes Avro payloads only. The fixed recursive Value schema preserves
nulls, booleans, signed 64-bit integers, finite doubles, bytes, UTF-8 strings,
lists, and string-keyed maps across official SDKs without customer-managed
schemas or a registry.

Large payloads are uploaded automatically when the namespace advertises runtime
storage. The SDK follows its inline threshold and upload limit, including batches
that exceed the ordinary request limit. Uploads and downloads use the same
runtime URL, namespace, and credential role, with size and SHA-256 verification.
`Client::builder(...).max_external_payload_bytes(...)` limits unique downloaded
bytes per response (64 MiB by default). Provider credentials are not needed;
payload fetches never follow redirects.

Workers confirm and renew the exact workflow task claim while loading external
inputs and paged history, then confirm it again before replay. Loading stops on
lost authority or Worker shutdown without executing workflow code. Pending
cooperative cancellation retains its original identity and cleanup deadline.

External activity inputs retain their original lease and execution deadline
bounds while loading. Without the optional lease-renewal capability, protocol 1.20 observes the exact activity attempt before,
during and after the transfer, and immediately before callback entry. Unconfirmed
authority stops loading without invoking the callback. These observations do not
renew the lease or record application heartbeats. Explicit protocol 1.19 uses
the original local lease/deadline bounds and completion fencing; it cannot
observe live revocation or ownership. Live authority supervision requires 1.20.
Shutdown and dropping a poll stop its loading and observation together.

The optional `Client::renew_activity_task_lease` request is available only when
actual runtime discovery advertises `activity_lease_renewal=true`. Pass the
original task ID, attempt ID, lease owner and a positive request window of at
most five seconds. Discovery and renewal share that window and use worker
credentials. This request records no application progress. Validate the full
original identity, granted lease and business deadlines before using its reply
to extend local authority. Direct Client users manage their own renewal lifecycle.

When registration, cluster discovery or the actual poll advertises that boolean
capability, `Worker` confirms and automatically maintains the original activity
claim throughout input loading, the yielding callback and terminal publication.
Missing or changed task, attempt, holder or run identity prevents callback entry.
Lost authority, exhausted original timeouts or managed shutdown drop the callback
future and fence retained callback Clients against late completion, failure,
heartbeat or result upload. Retryable renewal errors grant no additional time.
Older runtimes keep their existing path.

A delivered lease is measured from when the poll request was sent, so local
time never overstates the Server's grant. A timeout, transport error, 429 or 5xx
on a renewal, including the first one before the callback, keeps the claim under
its last acknowledged grant. The renewal is retried after a wait drawn uniformly
from `[0, min(4 s, 0.25 s * 2^n)]` after the n-th consecutive failure (n from 0,
full jitter), the same schedule in every Durable Workflow SDK. A single attempt
spends at most half of the remaining grant, capped at five seconds.

The Worker keeps a reserve at the end of the lease: at most 10 s and at most a
fifth of the grant. If renewal still has not succeeded when only the reserve is
left, the Worker drops the callback future and, once it has confirmed the
callback stopped, releases the claim with a retryable failure whose
`failure.type` is `worker_lost` (`failure.class` `ActivityWorkerLost`). The
Server's retry policy then acts at once, and `worker_lost` can be listed in
`non_retryable_error_types`. Callbacks run inline in the poll task, so dropping
the future stops them; a callback that blocks its thread stops only when it
yields. If the callback is not confirmed stopped while more than a small margin
of the lease is left (at most 1 s), nothing is sent and the Server records
`lease_expired`, so one attempt never runs twice. A Server refusal such as
`lease_expired` ends the claim without a release. In workflow code,
`ActivityFailure::lease_loss_reason()` reports `WorkerLost`, `LeaseExpired` or
`WorkerDeregistered`.

Runtime lease pings do not record application progress or satisfy a configured
heartbeat timeout. Continue calling `ctx.heartbeat(...)` for real progress; only
acknowledged same-attempt progress advances that recorded interval. Session-bound
activities also require an acknowledged same-holder session grant and retain
their original absolute TTL. The maintainer starts before callback entry, so
a spare executor thread can keep it running if a callback temporarily blocks.
Callbacks must still yield to Tokio: maintenance cannot progress if every
executor thread is blocked. Use `tokio::task::spawn_blocking` for blocking I/O
and CPU work, and give that work its own cancellation or process boundary.
Dropping an async callback cannot stop detached threads or reverse external
side effects.

Completion still uses the runtime's attempt fence. Server 2.6.1 refuses
superseded attempts but can accept an expired, unreclaimed attempt; see
[Workflow #769](https://github.com/durable-workflow/workflow/issues/769).

The Client's default 60-second HTTP timeout includes connection and the complete
response body. `Client::builder(...).timeout(Duration::from_secs(120))` selects a
larger total budget before starting a Worker. Claimed input and history loading
share that budget across all pages. Lease renewals do not restart it. Low-level
cooperative polls retain their long-poll timeout plus five seconds, and explicit
canonical cancellation refreshes retain their five-second budget.

### Workflow time and the replay clock

`WorkflowContext::replay_now()` returns a replay-safe UTC
`chrono::DateTime<Utc>` that advances with consumed history. Every replay of
the same history returns the same values, so workflow code can use it for
deadlines and elapsed time.

- **At workflow entry**, before any durable step, it returns the run's start
  from the workflow task's `replay_clock` carrier (`WorkerReplayClock` v1, sent
  by Server 3.6.0 and later). A redrive successor whose history proves the
  original start uses that start.
- **After a supported durable step** (a remote activity, a plain timer, a child
  workflow, a persisted signal delivery, a condition wait, or a validated
  all-group of activities, timers or children) it returns that step's recorded
  time.
- **Repeated reads** between two durable steps return the same value.

A deadline loop around a durable timer therefore terminates, and the difference
between two reads taken after two durable steps is their recorded elapsed time:

```rust,no_run
use std::time::Duration;
use durable_workflow::{json, Worker};
# fn configure(worker: &mut Worker) {
worker.register_workflow("orders.wait-ready", |ctx, args| async move {
    let deadline = ctx.replay_now()? + chrono::Duration::hours(1);
    while ctx.replay_now()? < deadline {
        if ctx.activity("orders.poll", args.clone()).await? == json!(true) {
            return Ok(json!("ready"));
        }
        ctx.sleep(Duration::from_secs(60)).await?;
    }
    Ok(json!("timed out"))
});
# }
```

Where the SDK cannot prove a time, `replay_now()` returns
`Error::ReplayClockUnavailable` instead of using wall time or any other value.
An unhandled `Error::ReplayClockUnavailable` fails the workflow like any other
error. The clock is unavailable:

- at entry when the task carries no valid `replay_clock` (Servers older than
  3.6.0, a run whose start the Server cannot prove, or a `WorkflowTask` executed
  directly without a poll);
- after inline and local operations: side effects, version markers, local
  activities and memo or search-attribute upserts. These stay unavailable until
  the platform defines a persisted time for those steps;
- after group modes other than the validated all-groups, and inside condition
  predicates;
- in cancellation callbacks.

Query handlers read the time of the rebuilt workflow prefix only when its final
boundary is proved, and update handlers read their committed `UpdateAccepted`
time; otherwise they are unavailable too. A query or replayed update validator
that rebuilds the workflow body uses its own task's `replay_clock`. Server
sends that key on query and update-validation tasks from the release that
includes server#1338, with `null` meaning the run has no provable start. When
the key is absent, as on older Servers, a rebuild in which the workflow reads
the clock at entry fails instead of answering, even if the workflow handles the
error: a query reports `query_workflow_state_unavailable`, and a replayed
update validator reports `update_validation_worker_failed`. Neither answers
with state its workflow task did not compute.

Do not use timestamps to order emitted events. Order them by stream offset,
outbox sequence or a workflow-local counter.

**Upgrading:** earlier releases reported `replay_now()` as unavailable at
entry. A running workflow whose code branches on that, for example with
`replay_now().ok()` at entry, takes the other branch when it replays on the
new SDK, or when the Server is upgraded to 3.6.0 or later. Version such code or
drain those runs before you upgrade.

See [the replay-clock source notes](https://github.com/durable-workflow/sdk-rust/blob/main/docs/replay-clock-source.md)
for the exact boundary rules.

## Testing without a Server

`testing::WorkflowEnvironment` runs registered workflows and activities in the
current process. Use `from_worker(worker)` to reuse your application's complete
registration set, or register test callbacks directly. `worker_mut()` exposes
the existing typed and replayed-state registration APIs.

```rust
use durable_workflow::{json, testing::WorkflowEnvironment};
# async fn test() -> durable_workflow::Result<()> {
let mut env = WorkflowEnvironment::new()?;
env.register_activity("greet", |_, args| async move {
    Ok(json!(format!("Hello, {}!", args[0].as_str().unwrap())))
});
env.register_workflow("hello", |ctx, args| async move {
    ctx.activity("greet", args).await
});
assert_eq!(env.run_activity("greet", "Ada").await?, json!("Hello, Ada!"));
env.mock_activity("greet", |_, _| async { Ok(json!("mock greeting")) });
assert_eq!(env.run_workflow("hello", "Ada").await?, json!("mock greeting"));
# Ok(())
# }
```

Workflow execution uses the worker's cold-replay engine, codec and activity
adapters. Real or mocked remote/local activity failures become the same typed
`Error::ActivityFailed` inside workflow code, including exception type, attempt
number and non-retryable marker. Retry policies apply before workflow code
receives a terminal failure. Timer and retry delays are skipped; activity
callbacks still execute normally and must yield. An uncaught workflow error is
returned with its original Rust error variant. Direct `run_activity` executes
one attempt. Heartbeats are captured locally and closed when the attempt ends.
The `*_avro_value` methods preserve fixed-Avro bytes, integers and other values
that have no lossless JSON representation.

The executor handles activities, local activities, timers, side effects,
version markers, memo/search-attribute upserts and ordered parallel commands.
Parallel callbacks run in command order. Activity timeout simulation, new select
races, signals, child workflows, services, sessions, continue-as-new and cancellation require
integration tests; unsupported commands return `Error::Testing` explicitly.
`signal_external_workflow` is one of those integration-only commands, while
`replay` resolves a recorded external signal from its history.
This environment does not simulate queues, leases or deployment behavior.
`max_steps(n)` bounds durable turns, commands and attempts (default 10,000);
use `tokio::time::timeout` to bound asynchronous callbacks as well.

### Replay before deploying changed workflow code

Load a self-contained JSON bundle from `dw workflow:history-export` or
`Client::export_workflow_history(workflow_id, run_id).await?`, register the
candidate workflow code, then replay without a Server:

```rust,no_run
use durable_workflow::testing::{WorkflowEnvironment, WorkflowHistory};
# fn replay(env: WorkflowEnvironment) -> std::result::Result<(), Box<dyn std::error::Error>> {
let export = serde_json::from_slice(&std::fs::read("workflow-history.json")?)?;
let history = WorkflowHistory::from_export(export)?;
let report = env.replay(&history)?;
assert!(report.completed); // A running snapshot can remain durably pending.
# Ok(())
# }
```

A workflow that reads `replay_now()` at entry also needs the original workflow
task's `replay_clock` object: pass it with
`WorkflowHistory::from_export(export)?.replay_clock(carrier)?`. The builder
refuses an invalid carrier or one for another run. `WorkflowHistory::export()`
does not include it, and `WorkflowEnvironment::run_workflow` supplies none, so
entry stays unavailable there.

For the raw history API, combine **all** pages and call
`WorkflowHistory::from_history("hello", original_input, response)?`.
Set `.task_queue("original-queue")` if that context is absent. Exports must
include original input and required recorded results. Redacted/pruned payloads,
unresolved external references and remaining page tokens are refused. The SDK
export helper resolves payload references while downloading; replay itself
never contacts a Server. `env.last_history()` captures a new in-process run and
can be exported for regression tests, including after an execution error.

Replay uses the worker's decoding, side-effect, version-marker and persisted
select-resolution paths. Activity callbacks do not run. Reordered or changed
commands return `Error::NonDeterministicReplay(ReplayFailure)` with `sequence`,
`expected` and `actual`. New commands beyond the snapshot also fail; use a
fresh in-process run to test new logic. A report contains the reconstructed
terminal commands or an empty decision for a recorded pending operation.

When a direct `ctx.activity(...)`, `ctx.local_activity(...)`, or `ctx.sleep(...)`
call disagrees with history, read `ReplayFailure.message` for the source filename
and line where the SDK future was built. The SDK can capture that call's source
coordinates from Rust's caller metadata. It has no function name or location for
typed and Avro async wrappers, grouped operations, or errors raised while
validating history before a call runs.

Keep workflow command order deterministic:

| Pattern | Durable replacement |
| --- | --- |
| Iterating a `HashMap` while scheduling | Sort keys first or use a `BTreeMap` |
| Reading the system clock for a deadline or elapsed time | `ctx.replay_now()?` |
| Reading randomness, a UUID or another wall-clock snapshot | `ctx.side_effect(...)` for a recorded snapshot, or an activity |
| `tokio::time::sleep`, `std::thread::sleep` | `ctx.sleep(...)` / `ctx.start_timer(...)` |
| `tokio::select!`, racing ordinary futures | `ctx.select(...)` / `ctx.select_keyed(...)` |
| Untracked concurrent durable calls | SDK `ctx.parallel(...)` with stable input ordering |
| Network, filesystem or other external I/O | A registered activity |
| Changing existing command order on deployment | A stable `ctx.get_version(...)` branch, checked against recorded history |

See the runnable [`workflow_testing`](examples/workflow_testing.rs) example and
[`workflow_testing` tests](tests/workflow_testing.rs).

### Choose the successor build when continuing as new

`ctx.continue_as_new(args)` keeps the current run's build pin. To use the
promoted build eligible for the successor's queue and workflow type, return
`ctx.continue_as_new_with_target(ContinueAsNewOptions::new(),
ContinueAsNewTarget::Promoted, args)` from the workflow handler. The successor
starts with fresh history. Pass arguments that the promoted code can decode
and accept.

The worker requires an acknowledgement of explicit build targeting in its
current registration. Both explicit targets return
`Error::ContinueAsNewTargetUnsupported` locally without that acknowledgement.
If no promoted build qualifies when the server admits the command, the worker
reports `promoted_build_unavailable` on the same task attempt and the server
applies its ordinary task retry policy. A committed continuation replays its
recorded choice without looking up the current promotion.

## Workflow logging

Use `ctx.logger()` for observations written from workflow code. It sends events
to the application's existing `tracing` subscriber with the target
`durable_workflow::workflow` and SDK-bound `namespace`, `workflow_instance_id`
and `workflow_run_id` fields. No global subscriber is installed.

```rust,no_run
# use durable_workflow::{Client, Worker, json};
# fn configure(client: Client) {
let mut worker = Worker::new(client, "orders");
worker.register_workflow("order", |ctx, _input| async move {
    ctx.logger().info("processing order");
    let result = ctx.activity("charge", json!([])).await?;
    ctx.logger().info("charge completed");
    Ok(result)
});
# }
```

Ordinary `tracing` calls execute again when a worker reconstructs a workflow.
The workflow logger suppresses the committed prefix, query/offline replay and
completed histories, including after a cold worker replacement. It emits when
execution reaches new code beyond that prefix. `ctx.replay_state()` exposes
that live boundary as `WorkflowReplayState`; a retained context outside its
invocation is `Unavailable`. Use the logger for observations and keep durable
command order independent of the observation state.

This is process logging. A log from an uncommitted task attempt can repeat if
that attempt crashes or retries. It is not an exactly-once outbox. Keep host
handlers bounded and nonblocking, for example with an application-owned logging
queue, so they do not stall the worker. Unwinding subscriber panics are isolated
from the workflow result; aborting processes and blocking handlers remain the
application's responsibility.

## Worker interceptors

Interceptors add cross-cutting behaviour, such as audit logging, metric tags
or tenant context, once for every task a worker runs. Implement
`WorkerInterceptor` and register it with `Worker::interceptor` (or several with
`Worker::interceptors`). Every hook defaults to passing the call on, so
implement only the hooks you need; `PassthroughWorkerInterceptor` is a no-op
interceptor.

| Hook | Runs around | Context | `next` |
| --- | --- | --- | --- |
| `execute_workflow_task` | one workflow task, including replay | `WorkflowTaskInterceptorContext` | `next.run()` returns a read-only `WorkflowTaskOutcome` |
| `execute_activity` | one activity or local activity attempt | `ActivityInterceptorContext` | `next.run(context)` returns the activity result |
| `execute_query_task` | one query task | `QueryTaskInterceptorContext` | `next.run()` returns the query result or `QueryTaskFailure` |
| `execute_update_validation_task` | one update-validation task | `UpdateValidationInterceptorContext` | `next.run()` returns a read-only `UpdateValidationOutcome` |

Contexts are read-only. They carry the worker id, task queue, namespace and the
task's identity: task id, workflow id, run id, workflow or activity type,
attempt and, for workflow tasks, history length, the task's trace carrier and
replay state. An activity context also exposes the decoded arguments, whether
the attempt is a local activity, and the `ActivityContext` the handler receives.

An audit log that records every workflow task outcome and activity attempt:

```rust,no_run
use durable_workflow::interceptors::{
    ActivityInterceptorContext, ActivityNext, InterceptorFuture,
    WorkflowTaskInterceptorContext, WorkflowTaskNext, WorkflowTaskOutcome,
};
use durable_workflow::{AvroValue, Client, Result, Worker, WorkerInterceptor};

struct AuditLog;

impl WorkerInterceptor for AuditLog {
    fn execute_workflow_task<'a>(
        &'a self,
        context: &'a WorkflowTaskInterceptorContext,
        next: WorkflowTaskNext<'a>,
    ) -> InterceptorFuture<'a, Result<WorkflowTaskOutcome>> {
        Box::pin(async move {
            let outcome = next.run().await;
            match &outcome {
                // The commands are new for this task even when it replayed
                // history first. A retry of a failed task has attempt > 1.
                Ok(outcome) => tracing::info!(
                    workflow_id = context.workflow_id(),
                    task_id = context.task_id(),
                    attempt = context.attempt(),
                    commands = outcome.commands().len(),
                    "workflow task completed"
                ),
                Err(error) => tracing::warn!(%error, "workflow task failed"),
            }
            outcome
        })
    }

    fn execute_activity(
        &self,
        context: ActivityInterceptorContext,
        next: ActivityNext,
    ) -> InterceptorFuture<'_, Result<AvroValue>> {
        Box::pin(async move {
            let activity_type = context.activity_type().to_owned();
            let attempt = context.attempt();
            let result = next.run(context).await;
            tracing::info!(%activity_type, attempt, ok = result.is_ok(), "activity attempt");
            result
        })
    }
}

# fn configure(client: Client) {
let worker = Worker::new(client, "orders").interceptor(AuditLog);
# let _ = worker;
# }
```

Interceptors run in registration order. The first one registered is the
outermost: it runs first before the task and last after it. Each hook must call
`next` to continue the chain; the innermost `next` runs the SDK's own handling.
Errors from the task pass back out through every interceptor unchanged unless
an activity or query interceptor deliberately handles them. Activity
interceptors can change arguments with `context.with_args(..)` and transform
results, and activity and query interceptors may answer without calling `next`.
Built-in `ExecutionTelemetry` spans stay outermost around the whole chain.

Workflow-task interceptors cannot change what a workflow records:

- `next.run()` takes no input, so the task always runs as received.
- The worker submits exactly the commands the workflow produced. The outcome is
  a read-only view of them.
- If the task fails, the worker reports that failure even when an interceptor
  returns `Ok`. Interceptors see it as `Error::WorkflowTaskFailed`, a read-only
  description with `.kind()`, `.message()` and `.debug()`; the worker keeps
  the original error.
- An interceptor error after the task succeeded, returning or failing without
  running `next`, or dropping the task partway fails the workflow task with
  `Error::WorkflowTaskInterceptor`. Nothing is recorded and the Server retries
  the task. The workflow does not fail. With cooperative cancellation enabled,
  a replay dropped partway (possibly during a cancellation delivery) is not
  reported: the poll returns the error and the task's lease expires.
- Interceptors run on every workflow task. `context.replay_state()` is
  `Replaying` when the task re-ran commands committed by earlier tasks before
  new execution, and `Executing` for a task with no committed history. The
  worker never resubmits replayed commands, so an outcome's commands are always
  new for that task: audit every successful outcome, whatever the replay
  state. If a task fails after an interceptor observed it, its retry can
  repeat the same outcome; `context.attempt()` above 1 identifies a retry.

Update-validation interceptors cannot change whether an update is accepted:

- `next.run()` takes no input, so the validator always runs on the task as
  received, and the worker sends the validator's own approval or rejection.
  The outcome is a read-only view: `is_approved()`, `is_rejected()`,
  `is_worker_failure()`, `reason()` and `rejection()`.
- An interceptor error, returning or failing without running `next`, or
  dropping the validation partway makes the worker report
  `update_validation_worker_failed` instead. The update is not accepted, and
  the caller's retry with the same request id asks the validator again.
- The context carries the worker, task queue, namespace, validation task id
  and attempt, workflow id, run id, workflow type, update name and trace
  carrier.

The offline `WorkflowEnvironment` runs activity interceptors registered on the
worker it wraps. It has no workflow or query tasks, so those hooks do not run
there.

## Schedule origin

A run started by a schedule can read the fire that started it with
`ctx.schedule_origin()`. It returns a `ScheduleOrigin` with the `schedule_id`,
the `occurrence_time` the scheduler evaluated (RFC 3339, as recorded) and the
`trigger_number`, or `None` for a run that no schedule started. The value comes
from the run's `ScheduleTriggered` history event, so it is available on the
first workflow task and identical on replay.

Use `occurrence_time` to pick the window a scheduled workflow processes. For a
tick it is the jittered fire time. For a backfill it is the enumerated past
occurrence. It is not the run's start time, so it does not drift with scheduler
delay:

```rust,no_run
# use durable_workflow::{Client, Error, Worker, json};
# fn configure(client: Client) {
let mut worker = Worker::new(client, "reports");
worker.register_workflow("reports.daily", |ctx, _input| async move {
    let window_end = ctx
        .schedule_origin()?
        .and_then(|origin| origin.occurrence_time)
        .ok_or_else(|| Error::Codec("start this workflow from a schedule".into()))?;
    ctx.activity("reports.build", json!([window_end])).await
});
# }
```

`occurrence_time` is `None` for a manual trigger, which records no occurrence.
A continue-as-new successor keeps its predecessor's origin when the Server
copies `ScheduleTriggered` into it (native Server 3.5.0 and later).

## Signal another workflow

`ctx.signal_external_workflow(workflow_id, signal_name, args)` signals another
workflow in the same namespace as a durable workflow command. The Server
records `ExternalSignalRequested` in the sender's history, delivers the signal
in the same transaction and records the outcome beside it. Awaiting the call
returns an `ExternalSignalResult`. Replay reads the recorded outcome and never
sends the signal again. Add `.run_id(run_id)` to signal only one run of the
target; without it the signal goes to the instance's current run.

```rust,no_run
# use durable_workflow::{Client, ExternalSignalOutcome, Worker, json};
# fn configure(client: Client) {
let mut worker = Worker::new(client, "orders");
worker.register_workflow("orders.approve", |ctx, _input| async move {
    let sent = ctx
        .signal_external_workflow("order-42", "approve", json!(["manager"]))
        .await?;
    match sent.outcome {
        ExternalSignalOutcome::Delivered => Ok(json!("approved")),
        // target_not_found, target_closed or rejected, with a stable reason
        // such as instance_not_found, run_not_active or unknown_signal.
        _ => Ok(json!({"not_delivered": sent.outcome.as_str(), "reason": sent.reason})),
    }
});
# }
```

A failed delivery is a returned value, not an error: `outcome` is
`TargetNotFound`, `TargetClosed` or `Rejected` and `reason` names why, so
workflow code decides what to do. A delivered result carries the target run,
the command and signal it recorded, and `retained: true` when the same command
key had already been delivered. Arguments are encoded like child-workflow
arguments.

The call returns an error only for an invalid target or signal name
(`Error::InvalidExternalSignal`, checked in workflow code before any command is
emitted: a signal name must not be blank or contain a control character, and is
at most 191 characters and 255 bytes, as the Server requires), for replay that no longer matches history (a
different target, run, signal name or arguments at the recorded sequence is
`Error::NonDeterministicReplay`), and for a Server that does not advertise the
`signal_external_workflow` command. The Worker reads that advertisement from
each workflow poll's `server_capabilities`. Without it the call returns
`Error::SignalExternalWorkflowUnavailable` before anything is submitted. If the
workflow returns that error, the Worker fails the workflow task, not the run.
Native Server 3.15.0 and later advertise the command (Server #1134); published
PHP Server 2.x does not.

## Inspect a run's activities

Use `Client::get_run_activities(workflow_id, run_id)` next to the selected run's
description to inspect its activities, attempts and last heartbeat:

```rust,no_run
# async fn inspect(client: durable_workflow::Client) -> durable_workflow::Result<()> {
let description = client.describe_workflow_run("workflow-id", "run-id").await?;
let view = client.get_run_activities("workflow-id", "run-id").await?;
println!("run status: {}", description.status.as_deref().unwrap_or("unavailable"));
for activity in view.activities {
    println!(
        "activity {:?}: status {:?}, attempts {:?}, last heartbeat {:?}",
        activity.activity_type,
        activity.status,
        activity.attempt_count,
        activity.last_heartbeat_at,
    );
}
# Ok(())
# }
```

The result belongs to that exact run in the client's namespace. Optional
metadata stays `None` when unavailable; zero attempts and `false` flags remain
explicit values. An omitted attempt list is distinct from an empty list.
Unsupported, diagnostic and future status strings are preserved, and unknown
response fields remain in each model's `raw` map. Heartbeat progress retains its
structured JSON types. Attempt flags describe the received snapshot and do not
grant worker authority. This read does not fetch or decode workflow payloads.
A handle with a selected run also offers `WorkflowHandle::get_activities()`;
it refuses a missing run ID instead of following the instance's current run.

## Workflow lists and complete run history

`Client::list_workflows(WorkflowListOptions)` and
`Client::get_workflow_history(workflow_id, run_id, WorkflowHistoryOptions)`
each return **one page**. Inspect `next_page_token` to resume manually, or use
the lazy iterators for complete reads. These methods wrap the published Server
APIs and preserve their filters, validation and namespace scope; they add no
Server query fields or grammar.

For example, find an open run by a registered keyword search attribute:

```rust,no_run
use durable_workflow::WorkflowListOptions;
# async fn find(client: durable_workflow::Client) -> durable_workflow::Result<()> {
let mut matches = client.iter_workflows(
    WorkflowListOptions::new()
        .workflow_type("payments")
        .status("running")
        .query("OrderRef = 'order-42'")
        .page_size(2),
);
match (matches.next().await?, matches.next().await?) {
    (Some(run), None) => println!("open run: {} / {}", run.workflow_id, run.run_id),
    (None, _) => println!("no open run"),
    _ => println!("multiple open runs; refine the query"),
}
# Ok(())
# }
```

The Server's `status=running` filter selects the active **status bucket**,
including runs whose raw status is `pending` or `waiting`. `WorkflowSummary`
preserves `status`, `status_bucket`, `is_terminal`, search attributes and unknown
metadata in `raw`. Search attributes do not impose a uniqueness constraint.
Create the client with the intended namespace before constructing the iterator;
the same namespace and filters are retained across every opaque token.

Read an entire selected run without loading every page at once:

```rust,no_run
use durable_workflow::WorkflowHistoryOptions;
# async fn audit(client: durable_workflow::Client) -> durable_workflow::Result<()> {
let mut events = client.iter_workflow_history(
    "payment-42", "selected-run-id", WorkflowHistoryOptions::new().page_size(100),
);
while let Some(event) = events.next().await? {
    println!("{}", event.event_type);
}
# Ok(())
# }
```

Similarly, `iter_workflows(options)` yields each `WorkflowSummary` through
`next().await`. Both iterators also provide `into_stream()` for standard
`futures_util::TryStreamExt` consumers; pin the returned stream before polling.
Constructing an iterator performs no I/O. It fetches only when
the current page is exhausted, holds one page, and ends on a null or empty
continuation token. Empty pages with a continuation are followed. Repeated or
cyclic tokens produce `Error::Pagination` using bounded token state. A page
failure is returned with its original typed error; that iterator then ends.
Handle the error rather than treating a partial read as a complete result.

Iterating history keeps the original workflow/run identity and does not follow
continue-as-new into another run. It enumerates available history rather than
subscribing indefinitely. History payloads retain their wire envelopes and
lossless event metadata. For offline replay, use the existing
`Client::export_workflow_history` and `testing::WorkflowHistory::from_export`
instead of passing a partial page to the replay API.

Published Server 2.11 defaults to 50 list rows (maximum 200) and 100 history
events (maximum 1,000) per page. Page sizes are sent unchanged for Server
validation. Stop the iterator when you have enough results, choose an appropriate
page size, and bound work with your application's timeout. List pagination
inherits the Server's ordering/consistency contract; it does not add snapshot
isolation while runs change concurrently. See the read-only
[`workflow_pagination` example](examples/workflow_pagination.rs).

## Examples

### Activity retry policies

`ActivityRetryPolicy::new(max_attempts).backoff_intervals(...)` preserves the
complete explicit list, including entries that the attempt budget will not use.
One attempt uses no retry delay. The server repeats the last entry when further
retries are allowed, while the attempt budget still limits execution. Replay
compares the complete stored list and the other known policy fields exactly;
changing an unused entry is also a policy change. The default remains one
attempt with an empty backoff list.

For generated backoff, `exponential_backoff(initial, coefficient, None)` selects
no maximum interval. Nine total attempts with an initial one-second delay and
coefficient two encode `1, 2, 4, 8, 16, 32, 64, 128` seconds. Pass `Some(maximum)`
to cap the intervals explicitly. The attempt budget and original schedule-to-close
deadline still bound retries; omission does not select a 60-second cap. Arithmetic
or protocol overflow returns `ActivityOptionsErrorKind::BackoffOverflow` during
validation. Replay preserves the recorded delay list. A cap that changes that
list also changes the policy compared during replay.

Activity handlers can use `ctx.activity_execution_id()` as the logical Server
activity key, stable across retries, and read its `workflow_id()` and `run_id()`.
These immutable optional accessors preserve the original claim. An older Server
can omit an ID; use an application business key in that case. Task IDs and attempt
IDs identify individual attempts and are not substitutes for a logical key.

```rust
# use durable_workflow::{json, Client, Worker};
# let mut worker = Worker::new(Client::builder("http://localhost:8080").build()?, "orders");
worker.register_activity("charge", |ctx, _| async move {
    let key = ctx.activity_execution_id();
    // Pass the available key (or an explicit business key) to your payment API.
    Ok(json!({"activity_key": key, "workflow": ctx.workflow_id(), "run": ctx.run_id()}))
});
# Ok::<(), durable_workflow::Error>(())
```

Worker-session activities expose the same received IDs. Inline local activities
expose their parent workflow/run IDs when present, but have no Server activity
execution ID before their command is recorded. Server-free activity/workflow
tests report no Server IDs. Use application business keys for those paths rather
than inferring a key from a task or attempt ID.

In a service activity, `ctx.retry_info()` exposes the original attempt number
and immutable Server retry snapshot. Use the configured budget for a final-attempt
fallback:

```rust
# use durable_workflow::{json, Client, Worker};
# let mut worker = Worker::new(Client::builder("http://localhost:8080").build()?, "orders");
worker.register_activity("charge", |ctx, _| async move {
    if ctx.retry_info().is_last_configured_attempt() == Some(true) {
        // Select a final-attempt fallback or record an application alert.
    }
    Ok(json!({"attempt": ctx.retry_info().attempt_number()}))
});
# Ok::<(), durable_workflow::Error>(())
```

`ActivityAttemptLimit::Bounded(n)` includes the first attempt. `Unlimited` requires
an explicit `max_attempts: null` in the received policy object. Omitted policies,
root null and missing or invalid limits are `Unknown`; `policy()` retains their
original JSON, including unknown fields. `is_last_configured_attempt()` returns
`None` for unknown metadata, `Some(false)` for unlimited, and checks whether the
original attempt has reached the bounded limit. A remaining budget does not
promise a retry: non-retryable failures, cancellation, workflow closure and elapsed
deadlines can end execution earlier. Local activities and direct `run_activity`
tests have no received Server snapshot and report unknown policy; fresh
`run_workflow` tests expose the modeled snapshot recorded in their history.

### Acknowledged activity checkpoints

A service activity claim can carry a read-only checkpoint from an earlier attempt
of the same logical execution. The Worker advertises `activity_heartbeat_resume`
and accepts its version-1 Server contract. `ctx.last_heartbeat_checkpoint()` returns
`Ok(Some(checkpoint))` for received details, `Ok(None)` when the supported claim
explicitly has no checkpoint, and `Err(ActivityHeartbeatResumeUnavailable)` when
support or the participating claim fields are unavailable. Older Servers, unknown
contract versions, inline local activities and Server-free tests are unavailable;
they do not invent an empty checkpoint.

`last_heartbeat_details()` and `last_heartbeat_at()` expose the same snapshot.
`checkpoint.details_as::<T>()` deserializes application JSON, while
`checkpoint.acknowledged_at()` retains a typed UTC timestamp and its fractional
precision. `heartbeat_resume_version()` and `checkpoint.contract_version()` refer
to the negotiated protocol; v1 supplies no checkpoint write-sequence number.

```rust
# use durable_workflow::{json, ActivityError, Client, Worker};
# use serde::Deserialize;
# #[derive(Deserialize)]
# struct Progress { next_item: u64 }
# let mut worker = Worker::new(Client::new("http://localhost:8080")?, "batch");
worker.register_activity("batch", |ctx, _| async move {
    let next_item = match ctx.last_heartbeat_checkpoint() {
        Ok(Some(checkpoint)) => checkpoint.details_as::<Progress>()?.next_item,
        Ok(None) => 0,
        Err(_) => return Err(ActivityError::new(
            "CheckpointUnavailable", "this activity requires acknowledged resume support"
        ).non_retryable(true).into()),
    };
    Ok(json!({"next_item": next_item}))
});
# Ok::<(), durable_workflow::Error>(())
```

The received snapshot stays immutable throughout the invocation. Calling
`heartbeat(...)` does not advance it, whether the write is acknowledged, rejected,
stale, or its response is uncertain. A later attempt receives whatever checkpoint
the Server retained; a lost response may follow a durable commit. Server v1
resumes only recorded non-null details. Receipt of a checkpoint does not atomically
commit an external business effect. Continue using stable application idempotency
keys, provider reconciliation and external fencing when effects can repeat.
Original retry policies and timeout budgets remain unchanged.

The [bounded batch example](examples/CHECKPOINTED_BATCH.md) uses these accessors
and a synthetic provider receipt store to explain failures around external commit
and checkpoint acknowledgement. Its source tests are separate from published
worker-loss qualification.

Activity handlers can return an application-defined failure type with
`ActivityError`. The same type, message and retry marker are reported for remote
and local activities, including cooperative workers:

```rust
use durable_workflow::{ActivityError, Worker};
# fn register(worker: &mut Worker) {
worker.register_activity("charge", |_, _| async {
    Err(ActivityError::new("PaymentDeclined", "card declined")
        .non_retryable(true)
        .into())
});
# }
```

`ActivityError::new(...)` is retryable by default. An activity's
`ActivityRetryPolicy::non_retryable_error_types(["PaymentDeclined"])` also stops
retries when the returned type matches exactly. Setting `.non_retryable(true)`
stops retries regardless of that list. Workflow code receives the terminal
`Error::ActivityFailed` with its `exception_type`, `non_retryable` and attempt
number. Application types must contain 1 to 255 bytes and cannot be blank;
invalid types produce a non-retryable `ActivityFailureMetadataError`.

Other errors retain the generic `RustActivityFailure` type for remote execution
and `RustActivityError` for local execution. Use `ActivityError` when a retry
policy must match the same application failure in both modes.

### Failure report limits

Outgoing failure reports use a 64 KiB message budget, reserving 2 KiB for
published Server timeline prefixes, so message content including its marker is
at most 62 KiB. They bound stacks to 128 KiB and
combined serialized details, diagnostics and optional metadata to 64 KiB. The
complete encoded request is at most 1 MiB, including JSON escaping, markers,
identity and every other field, or less when a lower transport limit is known.
Oversized messages include a visible truncation marker. Existing
`diagnostics.sdk_failure_truncation` records original byte sizes and omitted
fields. Workflow/query-task schemas without diagnostics and plain command
messages carry original sizes and omissions in the message marker instead.
Small reports keep their original content. Incoming history is never truncated.

`Client::fail_activity_task_with_failure` and
`Client::fail_workflow_task_with_failure` accept the published Server failure
schema for low-level task consumers. Keep `details` as valid Avro envelopes or
runtime references. Oversized details are omitted whole and marked, never cut as
base64. Original type and retry flags are preserved. Claim identity is exact;
`Error::FailureReporting` refuses a report whose required data cannot fit.
This reporting failure does not decide the application's retry outcome.

Local failures are bounded before returning to workflow code, with the published
Server's whitespace/NUL trimming applied to the observed outcome. The final request
check never rewrites already observed local messages or unrelated business
payloads; if those fixed inputs cannot fit, reporting refuses explicitly.

### Workflow task completion size

A workflow task's commands travel to the Server in one completion request.
The SDK reads the optional `limits.max_workflow_task_completion_bytes` from
Server discovery for the completion's encoded JSON request size. Each command's
arguments still obey the per-payload limit. An explicit positive aggregate cap
allows individually valid values to remain in one inline batch when namespace
payload storage is unconfigured, disabled or unsupported. Configured storage
retains its upload and lease checks.

Without that discovery field, the planner conservatively uses the ordinary
request cap. It can require external storage for an aggregate above that cap
even if the Server would accept the batch inline. The field's publication and
installed fan-out qualification are tracked in
[Server #1136](https://github.com/durable-workflow/server/issues/1136) and
[SDK #254](https://github.com/durable-workflow/sdk-rust/issues/254).

A completion above the Server's aggregate allowance is refused with HTTP 413,
`reason: "payload_too_large"` and `limit_kind: "workflow_task_completion_bytes"`.

Automatic structural failure requires the HTTP 413 to reach the worker. A
current native Server transport defect can close an over-limit request before
that response is read. In that case the SDK reports a transport error, and the
run is not yet guaranteed to fail structurally. Follow the
[aggregate transport correction](https://github.com/durable-workflow/server/issues/1136)
and [published fan-out acceptance](https://github.com/durable-workflow/.github/issues/228)
before relying on automatic recovery from an over-limit completion.

When the typed refusal reaches the SDK, it is a structural limit. It
never resends the oversized completion. `Client::complete_workflow_task` returns
`Error::WorkflowTaskCompletionTooLarge`, which carries the Server's `limit`, the
encoded request `size` the SDK sent, and the Server's message. A `Worker`
completes the same task once with a non-retryable `fail_workflow` command whose
message starts with `Structural limit exceeded: workflow_task_completion_bytes:`
and names both sizes, so the run fails with failure category
`structural_limit` instead of retrying the task forever or parking the run. The
failure's exception properties record `structural_limit_kind`,
`structural_limit_value` (the request size) and `structural_limit_configured`
(the limit); the Server's message is not copied into workflow history.
Other 413 responses and 5xx responses are unchanged.

To stay under the limit, split the fan-out into smaller batches across workflow
tasks, move groups of work into child workflows, or continue as new; offload
large payloads with external payload storage.

The Server records a completion in one history transaction, bounded by its
`history_transaction_size` (events), `history_transaction_bytes` and
`history_transaction_rows` structural limits. `ActivityScheduled` events repeat
their arguments, so a fan-out within the completion size can still exceed a
lowered `DW_V2_LIMIT_HISTORY_TRANSACTION_BYTES`. Native Server 3.13.0 defaults
that budget to four times the completion size limit and refuses a completion
over it with HTTP 409 `history_transaction_limit_exceeded`, naming `limit_kind`,
the measured `current_value` and the `configured_limit`; nothing is recorded.
`Client::complete_workflow_task` returns `Error::WorkflowTaskHistoryLimitExceeded`
for that refusal (and for `completion_budget_exceeded`), and a `Worker` handles
it like the 413 above: one non-retryable `fail_workflow` whose message starts
with `Structural limit exceeded: <limit kind>:`, with the same
`structural_limit_*` exception properties in the limit's unit. Replaying the
recorded failure produces the refused commands again; it is not a replay block,
and `testing::WorkflowEnvironment::replay` reports such a history as completed
rather than as a divergence.
`tests/history_limit_server.rs` checks this against published native Server
3.13.0 with a lowered budget. Other 409 responses are unchanged.

### Local activities

Enable inline local execution with `Worker::new(client, queue).local_activities(true)`.
Register the callback with the ordinary activity registration methods, then call
`ctx.local_activity(...)`, `local_activity_typed(...)` or
`local_activity_avro_value(...)` from workflow code. `LocalActivityOptions` sets
bounded retries and start-to-close, schedule-to-close and heartbeat timeouts.

Local activities run in the workflow worker and bypass the activity queue.
Server records their attempts, heartbeat details and terminal result. Committed
results replay without running the callback. A worker lost before completion is
acknowledged can execute the callback again, so external effects must be idempotent.

Callbacks must yield to Tokio. Timeout or lost workflow lease drops the async
callback without requiring application heartbeats. Blocking work needs separate
process supervision. Inline local execution and cooperative prepared local
supervision use separate worker profiles. Registration rejects combining them.
Database-generated execution and failure IDs become available after Server
commits history. Use the failure kind, timeout kind and attempt number to branch
during fresh execution, rather than testing whether an ID has been assigned.

Available since SDK 3.1.0. Default workers keep local execution disabled.
Opted-in workers negotiate their local capability during registration.

### Worker sessions

Enable `Worker::worker_sessions(true)` and declare the resource requirements that
the worker actually satisfies with `capabilities(...)`. Route a remote call with
`ctx.activity(...).in_worker_session(options)` and use `.typed::<Output>()` or
`.avro_value()` for its result. A parallel group's `in_worker_session(...)` applies
the same routing to each activity leaf.

Server creates a session on the first admitted activity. After registration,
`worker.worker_session(options)` also provides an explicit shared handle for
`create()`, `renew()` and `close(reason)`. `ActivityContext::worker_session()` exposes
the current handle. Heartbeats renew the holder lease without extending the
absolute TTL. Graceful worker shutdown drains activities and closes held sessions
before deregistering.

`lease_seconds(...)` bounds holder authority and `ttl_seconds(...)` bounds the
session's total lifetime. Reacquisition retains the original TTL deadline. Renew
the handle explicitly while keeping an idle resource alive. Activity heartbeats
also renew the lease. An async callback is dropped when its locally observed lease
or TTL ends, even without application heartbeats. Callbacks must yield to Tokio.

Set `max_concurrent_worker_sessions(...)` to bound the worker's session registry
and `max_concurrent_activities(...)` on the options to bound each session's activity
concurrency. Uncreated or failed handles release their local slot when dropped.
An admitted session keeps its slot while its holder lease is active.

Session memory is process-local. A replacement holder must rebuild its resources,
and an interrupted activity can execute again. Use idempotency and attempt fencing
for external side effects. Committed results replay from history without rebuilding
resources or rerunning callbacks. Changing recorded session options fails replay.
Local activities cannot use session routing.

The runnable session example uses a real process-local cache and prints its resource
generation. Use Server 2.5.1 / Native 2.4.1 for session history and original TTL
preservation. Session support starts with SDK 3.2.0.

### Bounded sticky execution

Enable a durable-history cache explicitly on a Worker:

```rust,no_run
use durable_workflow::{Client, Result, StickyCacheOptions, Worker};
use std::time::Duration;

fn configure(client: Client) -> Result<Worker> {
    Worker::new(client, "rust-workers")
        .build_id("orders-v1")
        .sticky_cache(StickyCacheOptions::new(32)
            .max_history_bytes(8 * 1024 * 1024)
            .ttl(Duration::from_secs(60)))
}
```

Caching is disabled by default. A positive capacity opts in, and zero disables it.
The defaults are 16 MiB of retained encoded history and a 300-second TTL. Set
whole-second TTLs between 1 and 3600 seconds. Registration must confirm the worker,
queue, namespace, build and sticky capability before it can poll with caching.
Use Server 2.5.10 or newer. SDK support starts with 3.4.0.

The cache retains immutable wire histories, never live workflow instances or
session resources. Replays decode a fresh snapshot. Entry and encoded-byte bounds
use LRU eviction, and reads do not extend expiry. Decoding, replay, keys and cursor
metadata use additional memory. Size the cache within your worker's memory budget.

A warm replay validates the inline prefix and fetches the retained tail cursor
under the current task's lease and attempt. Missing, expired, changed or invalid
entries fall back to complete durable history. Worker replacement needs no cache
transfer. Committed side effects replay, and cancellation delivery remains governed
by canonical Server history. Terminal completion and worker shutdown clear entries.

`worker.sticky_cache_metrics()` reports hits, misses, evictions, forced cold
replays, retained entries and encoded history bytes. This reduces history fetching
for warm runs. Measure CPU, memory and completion rate with your own workloads.

An explicit `build_id(...)` pins new runs to that deployment build. A different
build cannot take an existing pinned run. Omit it to retain unversioned routing.
The runnable example below prints its result and cache counters.

### Deploying workflow patches

Use a stable change ID with `ctx.patched(...)` or `ctx.get_version(...)` to
preserve deployment decisions through replay. An old unmarked history selects
the legacy version `-1` if the next durable operation was already recorded.
New executions record one decision per change ID, even when code asks again.

Some older workers recorded a marker for every repeated call. Rust replays
consistent markers at their original positions, retaining the recorded history
and timestamps. Keep those call boundaries, or replace them with
`ctx.deprecate_patch(...)`, while such histories remain active. Replay consumes
one matching historical marker per call and never skips an intervening activity,
timer or side effect. Conflicting recorded versions and unsupported current
ranges remain replay errors.

### Recovering from Server outages

`run` and `run_until` outlive transient Server outages by default, such as a
database failover. A transient failure is a connection refused, reset or timed
out; a 500, 502, 503 or 504 without a typed reason (an upstream or framework
error page, or an untyped JSON error such as `{"message":"Server Error"}`) or
with the generic reason `server_error` (the Server's answer when its database
is unavailable to authenticate a request); a 503 whose reason is
`storage_unavailable` or `backend_unavailable` (for example while native Server
warms up its storage); or any 5xx or 429 that says `retryable: true`. Every
worker loop treats these the same way: workflow, activity and query polls, the
worker heartbeat, registration, and task completion and failure reports. Poll and worker-heartbeat
retries keep going past `WorkerRetryPolicy.max_retries` for these, and a
retried poll keeps its original request ID. Within the budget they use the
policy's delays; beyond it every worker draws from the shared full-jitter
schedule below, so a fleet does not retry in step when the Server comes back.
An outage that has lasted 60 s is logged as a `tracing` error, then again
every 5 minutes while it continues; a success resets it. A transient that still escapes a
poll lane, a task settlement or registration is logged as a `tracing` warning
and retried after a wait drawn uniformly from `[0, min(4 s, 0.25 s * 2^(n-1))]`
for the n-th consecutive failure, the schedule shared by every Durable Workflow
SDK. Shutdown interrupts every wait and settles any poll response already in
flight.

When a 429 or 5xx answer carries `Retry-After` (delta-seconds or an HTTP-date),
every retry the worker schedules after it waits at least that long, capped at
30 s, instead of its shorter backoff. The advice is shared by the worker's
loops and cleared by the next successful answer.

A workflow-task completion or failure that hits a transient failure is resent
unchanged (the same serialized report, so the same task, lease owner and
attempt) within `WorkerRetryPolicy.max_retries`, using the policy's delays and
honoring `Retry-After`. If the Server had already recorded the first copy,
native Server answers the resend with its duplicate receipt
(`"recorded": false, "reason": "already_completed"`), or with the not-recorded
`task_not_leased` receipt for this task and attempt, and the task is settled.
Any other definitive refusal of a resend (for example a lease that expired
meanwhile) is treated like the original transient failure: the worker keeps
running and the Server redelivers the task when its lease ends. Task-offer 409
refusals and lease fencing are unchanged.

An activity completion, failure or `worker_lost` release that hits a
transient failure is resent unchanged with the same backoff while the
activity's lease lasts (a maintained lease keeps being renewed meanwhile). If
the Server had already committed the first copy, native Server 3.17 answers the
resend with `409 {"reason":"stale_attempt","recorded":false}` naming this
task, attempt and owner with every status `completed` (or `attempt_status`
`failed` for a failure); the worker counts that as its own recorded outcome. A
`stale_attempt` in any other state means the attempt was closed by something
else. When the lease runs out first, the worker logs a `tracing` error and the
Server settles the attempt.

A running worker's cluster-info reads (startup discovery and the payload
policy read before a report) retry a connection failure, timeout, 5xx or 429
the same way. Once a payload policy is known, an outage does not hold reports
back: the last-known policy is used and discovery is tried again 10 s later.
If the Server refuses a report as too large because it lowered its inline
limit, the worker rediscovers the policy, encodes the report again and resends
it once. A result that is still too large, or cannot be externalized, fails the
attempt as a non-retryable `ActivityResultTooLarge`; the worker keeps running.

An explicit `retryable: false`, 401, 403, other 4xx and typed protocol
refusals (including a 5xx with a specific `reason` other than those above),
codec and handler failures stop the worker: it emits a `tracing` error event and
returns the error. `.recover_transient_outages(false)` restores bounded retries,
`run_once` remains bounded in either mode, and
`WorkerRetryPolicy.max_retries = 0` disables retries. Keep a process supervisor
for crashes.

Credential refusals differ between SDKs. The Rust and PHP workers stop on a
401 or 403 after logging it as an error, so a supervisor restarts them with new
credentials. The Python SDK's pollers keep retrying 401 and 403, logging an
error on every refusal, so credentials can rotate under a running worker.

### Runnable examples

| Example | Demonstrates |
| --- | --- |
| [`hello_world.rs`]https://github.com/durable-workflow/sdk-rust/blob/main/examples/hello_world.rs | Typed worker, workflow, activities, retries, and completion |
| [`activity_options.rs`]https://github.com/durable-workflow/sdk-rust/blob/main/examples/activity_options.rs | Activity retry and timeout policies |
| [`local_activities.rs`]https://github.com/durable-workflow/sdk-rust/blob/main/examples/local_activities.rs | Explicit local execution, retries, durable timers and remote work |
| [`worker_sessions.rs`]https://github.com/durable-workflow/sdk-rust/blob/main/examples/worker_sessions.rs | Typed activity routing, holder-local resources and graceful session close |
| [`sticky_execution.rs`]https://github.com/durable-workflow/sdk-rust/blob/main/examples/sticky_execution.rs | Opt-in bounded history, signal replay and cache counters |
| [`condition_search_attributes.rs`]https://github.com/durable-workflow/sdk-rust/blob/main/examples/condition_search_attributes.rs | Durable conditions and typed search attributes |
| [`continue_as_new.rs`]https://github.com/durable-workflow/sdk-rust/blob/main/examples/continue_as_new.rs | Bounded histories and continue-as-new |
| [`parallel_saga.rs`]https://github.com/durable-workflow/sdk-rust/blob/main/examples/parallel_saga.rs | Deterministic parallel work and saga compensation |

### Client and worker metrics

The SDK implements the [shared SDK recorder contract](https://github.com/durable-workflow/.github/blob/7a91906ece5cd599175a2e08ebcc9c8bc667a6f6/sdk-metrics/README.md).
The default is a no-op. Supply an `Arc<dyn metrics::MetricsRecorder>` with
`increment(name, count, tags)` and `record(name, seconds, tags)` methods; the
client, its clones and newly constructed workers inherit the recorder.
`Worker::metrics_recorder` overrides worker poll/task observations while client
request observations retain the client's recorder. Recorders must be fast and
handle exporter failures locally. Unwinding recorder panics are isolated from
SDK results; process aborts and blocking exporters cannot be repaired by a hook.

Every observed client request, worker poll and claimed-task dispatch increments
its counter by one and records one nonnegative monotonic duration in seconds.
The paired recorder names are:

| Counter | Duration histogram |
| --- | --- |
| `durable_workflow_client_requests` | `durable_workflow_client_request_duration_seconds` |
| `durable_workflow_worker_polls` | `durable_workflow_worker_poll_duration_seconds` |
| `durable_workflow_worker_tasks` | `durable_workflow_worker_task_duration_seconds` |

Revision 2 also records `durable_workflow_worker_task_schedule_to_start_seconds`
for workflow and activity claims when the Server advertises
`claimed_task_ready_age`. It converts the Server's integer `ready_age_ms` to
seconds and uses only `task_kind` and `task_queue`, without a paired counter or
outcome label. A real zero is retained; missing, malformed or out-of-range
producer values are omitted. This measures Server eligibility-to-claim time,
without estimating missing values from the worker's clock.

Client tags are exactly `method`, `route`, `plane`, `status_code`, `outcome`.
Worker tags are exactly `task_kind`, `task_queue`, `outcome`. Reviewed route
placeholders exclude IDs, query strings, payloads and credentials; unknown paths
use `unknown`. Queue names are application-controlled: use bounded names rather
than a queue per run. The SDK's tests verify the exact vendored revision-2 JSON
from the pinned shared contract above.

One client observation includes its internal transport/storage-admission retries
and response/payload handling. Separate application/worker-managed calls remain
separate client observations. A lazy iterator observes each requested page, not
one operation for the whole iteration. Worker poll observations include managed
retry/backoff and distinguish `task`, `empty`, `backpressure`, `error`. Task
observations describe processing of workflow, activity and query dispatches:
`completed`, `failed` and `expired` do not assert a workflow's terminal state.
These are process observations, not durable counts, billing units or
schedule-to-start latency. Abrupt process loss can prevent a final observation.

Client outcomes include `ok`, `http_error`, `bridge_rejected`, `TransportError`,
`TimeoutError`, `SdkError` and `pending` (a cancelled future). A decimal HTTP
status is retained when observed, otherwise `status_code=none`. Language-specific
exception outcomes need not match Python names. Renaming an adopted name, type,
unit or tag key requires a major release; additions and new tag values are
announced in the changelog.

#### Prometheus export

Enable the optional adapter in your application:

```toml
[dependencies]
durable-workflow = { version = "=4.7.0", features = ["metrics-prometheus"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
```

`metrics::PrometheusMetrics::new()` owns a dedicated registry backed by the
[official Prometheus Rust client](https://github.com/tikv/rust-prometheus/tree/v0.14.0).
Pass an `Arc` of it to `ClientBuilder::metrics_recorder`, and serve its
`encode()` bytes from your application's metrics route with content type
`text/plain; version=0.0.4`. The adapter installs no listener or global registry;
applications choose scrape authentication/network exposure, exporter resources
and shutdown. Counter exports append `_total`; histograms expose standard
bucket/sum/count series without changing the recorder contract. `registry()`
allows application-owned collection and additional metrics.

The [runnable example](examples/metrics_prometheus.rs) previews actual exported
health-request observations:

```bash
DURABLE_WORKFLOW_SERVER_URL=http://localhost:8080 \
DURABLE_WORKFLOW_AUTH_TOKEN=your-token \
cargo run --features metrics-prometheus --example metrics_prometheus
```

For OpenTelemetry, implement `MetricsRecorder` with the application's existing
meter: create count-unit (`1`) counters for `increment` and second-unit (`s`)
histograms for `record`, using the exact names and tags above. Provider,
aggregation, resource labels and exporter lifecycle stay with the application.

### Optional execution telemetry

Enable the `telemetry` Cargo feature and configure your application's
OpenTelemetry provider, exporter, sampling and bounded export timeouts before
constructing the worker. Configure the application's global W3C propagator
before making admission calls or starting workers:

```rust,no_run
# #[cfg(feature = "telemetry")]
# fn main() -> Result<(), Box<dyn std::error::Error>> {
use durable_workflow::{Client, Worker};
use durable_workflow::telemetry::ExecutionTelemetry;
opentelemetry::global::set_text_map_propagator(
    opentelemetry_sdk::propagation::TraceContextPropagator::new(),
);
let client = Client::builder("http://localhost:8080").build()?;
let worker = Worker::new(client, "orders").telemetry(ExecutionTelemetry::new());
# Ok(())
# }
# #[cfg(not(feature = "telemetry"))]
# fn main() {}
```

The default build has no OpenTelemetry dependency. The optional feature needs
the API and official W3C propagators supplied by the OpenTelemetry SDK crate;
the application owns provider/exporter configuration and shutdown.
If the application already uses a composite propagator, retain its other
propagators and include W3C trace context. A missing propagator leaves task
spans independent even when the Server supports carriers. The SDK does not
replace the application's global configuration.
Servers without the exact optional capability use independent task traces.
When available, a valid run origin parents task spans; task-bound dispatch and
validated command/outcome contexts become links. The original poll identity,
generation and existing hydration, query and cooperative fences precede their
use. Missing or insufficient authority omits propagation without changing
business execution. Actual remote/local activity attempts have separate child
spans. Use the configured Server/SDK tuple qualified in
[Workflow #773](https://github.com/durable-workflow/workflow/issues/773).
Replay emits workflow work spans without pretending completed activities ran
again. No span stays open during durable waiting.

Configure admission/command clients with `client.with_telemetry(telemetry)` and
use existing `client.cluster_info().await` discovery during setup. Worker startup
can perform one bounded optional discovery; its failure does not refuse business
registration or add business retries. Only the exact supported
`worker_protocol.server_capabilities.observability_context` object enables
carriers. No mandatory protocol floor or Server version inference is added.
Caller capture precedes HTTP transport. Worker child/continue commands capture
their actual workflow scope before settlement and preserve business arguments
and request keys.

Official W3C propagation validates the agreed byte limits. Baggage defaults empty;
`with_baggage_allowlist` retains explicit keys only on run parents. Links never
carry baggage. Envelopes are bounded to 4096 bytes and at most 32 links. Malformed
metadata is ignored with fixed `discarded`/`filtered` span diagnostics. Use
`with_enabled(false)` to disable spans and propagation explicitly.

Use `telemetry::current_log_context()` in a logging adapter, or wrap an existing
OpenTelemetry logger provider in `telemetry::ExecutionLoggerProvider` before
passing it to your application's logging bridge. It adds bounded namespace,
worker, queue, task and available workflow/attempt IDs; trace/span IDs follow
the current application child span. Request IDs and log messages remain owned
by the application. The SDK installs no global logging bridge or provider.
Tokio contexts attach during each poll and restore on yield, completion, panic
and cancellation. Spawned application tasks must explicitly propagate their
context when that is intended. Export failures do not change business results;
applications must bound exporter I/O and drain their providers during shutdown.
Abrupt process death may lose spans; telemetry is not exactly-once delivery.

## Documentation

- [Rust SDK landing page]https://rust.durable-workflow.com/
- [Generated API reference]https://rust.durable-workflow.com/durable_workflow/
- [Rust SDK guide]https://durable-workflow.com/docs/2.0/polyglot/rust/
- [Self-hosted Server guide]https://durable-workflow.com/docs/2.0/polyglot/server/
- [Cloud early access]https://cloud.durable-workflow.com/early-access

## Nexus service calls

Await a catalog operation from workflow code with Avro arguments:

```rust,ignore
let reply = ctx.call_nexus_service("billing", "invoices", "create", invoice).await?;
let receipt: Receipt = reply.result.deserialize()?;
```

The default synchronous call waits for its committed result. Cold replay resumes
the original call without admitting it again. `NexusServiceOptions` selects a
target namespace, idempotency key, async mode or acceptance-only waiting. Async
and acceptance-only calls return the original admission, even when a terminal
result appears later. Committed failures use `Error::NexusOperationFailed`.
Calls currently run in the root workflow scope.

Enable `Worker::nexus_cooperative_cancellation(true)` for cooperative service
waits. It enables ordinary cooperation and requires the installed Server to
advertise protocol 1.20, both cancellation capabilities and a `workflow_run`
binding. Cancellation reaches the original synchronous completion wait after
owned target cleanup, preserving the original request and cleanup deadline.
Use a cancellation shield for durable cleanup. See
[`examples/nexus_cooperation.rs`](examples/nexus_cooperation.rs) for caller and
target workers. Ordinary cooperative workers keep their existing registration
behavior when Nexus cooperation is disabled.

## Compatibility

The SDK supports cooperative requests and bounded,
replayable cleanup. Enable `Worker::cooperative_cancellation(true)` against a
Server that advertises protocol 1.20 and the required capabilities. This profile
supervises async Activity futures independently of application heartbeats.
Independently cancellable scopes remain disabled. See the
[cancellation guide](https://github.com/durable-workflow/sdk-rust/blob/main/docs/cooperative-cancellation-design.md)
and [v3 migration guide](https://github.com/durable-workflow/sdk-rust/blob/main/docs/migrating-to-v3.md).

The crate publishes its supported Server and worker-protocol ranges in
`[package.metadata.durable-workflow]` in [`Cargo.toml`](https://github.com/durable-workflow/sdk-rust/blob/main/Cargo.toml). Runtime
capability manifests, not matching package version strings, determine protocol
compatibility. Stable releases follow semantic versioning.

`supported-server-release-baselines` maps supported Server majors to minimum
stable releases. A reader validates the whole map before selecting a major and
refuses an unlisted major, a malformed entry or a contradiction with the legacy
`supported-server-versions` 2.x baseline. Without the additive map, existing
same-major baseline behavior remains. The legacy scalar and the separate 2.x
qualification identity are preserved for older readers. Protocol and capability
negotiation remain required for individual features.

`Client::signal_with_start` and `WorkflowContext::signal_external_workflow`
need native Server 3.15.0 or later, the first release that advertises
`capabilities.signal_with_start` and the `signal_external_workflow` command.
Against an older Server they return `Error::SignalWithStartUnavailable` or
`Error::SignalExternalWorkflowUnavailable` before anything is sent.

## Development

Default builds enable `msrv-1-86`, which keeps the builder-macro dependency pin
needed by fresh Rust 1.86 consumers. If you disable default features and still
require Rust 1.86, explicitly enable `msrv-1-86`.

A host on a newer compiler can omit that feature to compose the SDK with the
native Server library and its newer official Avro dependency. Without the pin,
fresh dependency resolution can require a newer compiler. The native composition
check uses Rust 1.88 or later; this opt-out does not change SDK runtime APIs or
protocol negotiation.

```sh
cargo fmt --all --check
cargo test --locked --all-targets --all-features
cargo doc --locked --all-features --no-deps
cargo package --locked
```

The committed lockfile records the dependency graph used by CI and packaging.
Fresh-consumer checks resolve dependencies independently to verify the published
crate also builds for new consumers. Release verification runs tooling pinned to
the workflow commit against a separate immutable source tag. For older tags that
ignored the lockfile, it restores only the missing lock from the checksum-verified
published crate, then requires the complete regenerated archive to match.

Replay and codec defects require a minimal regression fixture. See
[`CONTRIBUTING.md`](https://github.com/durable-workflow/sdk-rust/blob/main/CONTRIBUTING.md) for the corpus rules.

## License

Durable Workflow Rust SDK is released under the [MIT License](https://github.com/durable-workflow/sdk-rust/blob/main/LICENSE).