-
Notifications
You must be signed in to change notification settings - Fork 201
Expand file tree
/
Copy pathtest_workflow_streams.py
More file actions
2739 lines (2295 loc) · 96.3 KB
/
Copy pathtest_workflow_streams.py
File metadata and controls
2739 lines (2295 loc) · 96.3 KB
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
"""E2E integration tests for temporalio.contrib.workflow_streams."""
from __future__ import annotations
import asyncio
import sys
import uuid
from dataclasses import dataclass
from datetime import timedelta
from typing import Any, cast
from unittest.mock import patch
if sys.version_info >= (3, 11):
from asyncio import timeout as _async_timeout # pyright: ignore[reportUnreachable]
else:
from async_timeout import ( # pyright: ignore[reportUnreachable]
timeout as _async_timeout,
)
import google.protobuf.duration_pb2
import nexusrpc
import nexusrpc.handler
import pytest
import temporalio.api.nexus.v1
import temporalio.api.operatorservice.v1
import temporalio.api.workflowservice.v1
from temporalio import activity, nexus, workflow
from temporalio.client import (
Client,
WorkflowExecutionStatus,
WorkflowHandle,
WorkflowUpdateFailedError,
WorkflowUpdateStage,
)
from temporalio.common import RawValue
from temporalio.contrib.workflow_streams import (
PollInput,
PollResult,
PublishEntry,
PublishInput,
TopicHandle,
WorkflowStream,
WorkflowStreamClient,
WorkflowStreamItem,
WorkflowStreamState,
WorkflowTopicHandle,
)
from temporalio.contrib.workflow_streams._types import _encode_payload
from temporalio.converter import DataConverter
from temporalio.exceptions import ApplicationError
from temporalio.nexus import WorkflowRunOperationContext, workflow_run_operation
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import Worker
from tests.helpers import assert_eq_eventually, new_worker
from tests.helpers.nexus import make_nexus_endpoint_name
def _wire_bytes(data: bytes) -> str:
"""Build a PublishEntry.data string from raw bytes.
Mirrors what :class:`WorkflowStreamClient` produces on the encode path:
default payload converter turns the bytes into a ``Payload``, which
is then proto-serialized and base64-encoded for the wire.
"""
payload = DataConverter.default.payload_converter.to_payloads([data])[0]
return _encode_payload(payload)
# ---------------------------------------------------------------------------
# Test workflows (must be module-level, not local classes)
# ---------------------------------------------------------------------------
@workflow.defn
class BasicWorkflowStreamWorkflow:
@workflow.init
def __init__(self) -> None:
self.stream = WorkflowStream()
self._closed = False
@workflow.signal
def close(self) -> None:
self._closed = True
@workflow.run
async def run(self) -> None:
await workflow.wait_condition(lambda: self._closed)
@workflow.defn
class ActivityPublishWorkflow:
@workflow.init
def __init__(self, count: int) -> None:
self.stream = WorkflowStream()
self._closed = False
@workflow.signal
def close(self) -> None:
self._closed = True
@workflow.run
async def run(self, count: int) -> None:
await workflow.execute_activity(
"publish_items",
count,
start_to_close_timeout=timedelta(seconds=30),
heartbeat_timeout=timedelta(seconds=10),
)
self.stream.topic("status", type=bytes).publish(b"activity_done")
await workflow.wait_condition(lambda: self._closed)
@dataclass
class AgentEvent:
kind: str
payload: dict[str, Any]
@workflow.defn
class StructuredPublishWorkflow:
@workflow.init
def __init__(self, count: int) -> None:
self.stream = WorkflowStream()
self._closed = False
@workflow.signal
def close(self) -> None:
self._closed = True
@workflow.run
async def run(self, count: int) -> None:
for i in range(count):
self.stream.topic("events", type=AgentEvent).publish(
AgentEvent(kind="tick", payload={"i": i})
)
await workflow.wait_condition(lambda: self._closed)
@workflow.defn
class TopicHandlePublishWorkflow:
"""Workflow that publishes via the workflow-side topic handle."""
@workflow.init
def __init__(self, count: int) -> None:
self.stream = WorkflowStream()
self.events = self.stream.topic("events", type=AgentEvent)
self._closed = False
@workflow.signal
def close(self) -> None:
self._closed = True
@workflow.run
async def run(self, count: int) -> None:
for i in range(count):
self.events.publish(AgentEvent(kind="tick", payload={"i": i}))
await workflow.wait_condition(lambda: self._closed)
@workflow.defn
class WorkflowSidePublishWorkflow:
@workflow.init
def __init__(self, count: int) -> None:
self.stream = WorkflowStream()
self._closed = False
@workflow.signal
def close(self) -> None:
self._closed = True
@workflow.run
async def run(self, count: int) -> None:
for i in range(count):
self.stream.topic("events", type=bytes).publish(f"item-{i}".encode())
await workflow.wait_condition(lambda: self._closed)
@workflow.defn
class MultiTopicWorkflow:
@workflow.init
def __init__(self, count: int) -> None:
self.stream = WorkflowStream()
self._closed = False
@workflow.signal
def close(self) -> None:
self._closed = True
@workflow.run
async def run(self, count: int) -> None:
await workflow.execute_activity(
"publish_multi_topic",
count,
start_to_close_timeout=timedelta(seconds=30),
heartbeat_timeout=timedelta(seconds=10),
)
await workflow.wait_condition(lambda: self._closed)
@workflow.defn
class InterleavedWorkflow:
@workflow.init
def __init__(self, count: int) -> None:
self.stream = WorkflowStream()
self._closed = False
@workflow.signal
def close(self) -> None:
self._closed = True
@workflow.run
async def run(self, count: int) -> None:
self.stream.topic("status", type=bytes).publish(b"started")
await workflow.execute_activity(
"publish_items",
count,
start_to_close_timeout=timedelta(seconds=30),
heartbeat_timeout=timedelta(seconds=10),
)
self.stream.topic("status", type=bytes).publish(b"done")
await workflow.wait_condition(lambda: self._closed)
@workflow.defn
class PriorityWorkflow:
@workflow.init
def __init__(self) -> None:
self.stream = WorkflowStream()
self._closed = False
@workflow.signal
def close(self) -> None:
self._closed = True
@workflow.run
async def run(self) -> None:
await workflow.execute_activity(
"publish_with_priority",
start_to_close_timeout=timedelta(seconds=30),
heartbeat_timeout=timedelta(seconds=10),
)
await workflow.wait_condition(lambda: self._closed)
@workflow.defn
class FlushOnExitWorkflow:
@workflow.init
def __init__(self, count: int) -> None:
self.stream = WorkflowStream()
self._closed = False
@workflow.signal
def close(self) -> None:
self._closed = True
@workflow.run
async def run(self, count: int) -> None:
await workflow.execute_activity(
"publish_batch_test",
count,
start_to_close_timeout=timedelta(seconds=30),
heartbeat_timeout=timedelta(seconds=10),
)
await workflow.wait_condition(lambda: self._closed)
@workflow.defn
class MaxBatchWorkflow:
@workflow.init
def __init__(self, count: int) -> None:
self.stream = WorkflowStream()
self._closed = False
@workflow.signal
def close(self) -> None:
self._closed = True
@workflow.query
def publisher_sequences(self) -> dict[str, int]:
return {pid: ps.sequence for pid, ps in self.stream._publishers.items()}
@workflow.run
async def run(self, count: int) -> None:
await workflow.execute_activity(
"publish_with_max_batch",
count,
start_to_close_timeout=timedelta(seconds=30),
heartbeat_timeout=timedelta(seconds=10),
)
self.stream.topic("status", type=bytes).publish(b"activity_done")
await workflow.wait_condition(lambda: self._closed)
@workflow.defn
class LateWorkflowStreamWorkflow:
"""Calls WorkflowStream() from @workflow.run, not from @workflow.init.
The constructor inspects the caller's frame and requires the
function name to be ``__init__``; called from ``run``, it must
raise ``RuntimeError``. The workflow returns the error message so
the test can assert on it without forcing a workflow task failure.
"""
@workflow.run
async def run(self) -> str:
try:
WorkflowStream()
except RuntimeError as e:
return str(e)
return "no error raised"
@workflow.defn
class DoubleInitWorkflow:
"""Calls WorkflowStream() twice from @workflow.init.
The first call succeeds; the second must raise RuntimeError because
the workflow stream signal handler is already registered. The workflow
stashes the error message so the test can assert on it without
forcing a workflow task failure.
"""
@workflow.init
def __init__(self) -> None:
self.stream = WorkflowStream()
self._closed = False
self.double_init_error: str | None = None
try:
WorkflowStream()
except RuntimeError as e:
self.double_init_error = str(e)
@workflow.signal
def close(self) -> None:
self._closed = True
@workflow.query
def get_double_init_error(self) -> str | None:
return self.double_init_error
@workflow.run
async def run(self) -> None:
await workflow.wait_condition(lambda: self._closed)
# ---------------------------------------------------------------------------
# Activities
# ---------------------------------------------------------------------------
@activity.defn(name="publish_items")
async def publish_items(count: int) -> None:
client = WorkflowStreamClient.from_within_activity(
batch_interval=timedelta(milliseconds=500)
)
async with client:
for i in range(count):
activity.heartbeat()
client.topic("events", type=bytes).publish(f"item-{i}".encode())
@activity.defn(name="publish_multi_topic")
async def publish_multi_topic(count: int) -> None:
topics = ["a", "b", "c"]
client = WorkflowStreamClient.from_within_activity(
batch_interval=timedelta(milliseconds=500)
)
async with client:
for i in range(count):
activity.heartbeat()
topic = topics[i % len(topics)]
client.topic(topic, type=bytes).publish(f"{topic}-{i}".encode())
@activity.defn(name="publish_with_priority")
async def publish_with_priority() -> None:
# Long batch_interval AND long post-publish hold ensure that only a
# working force_flush wakeup can deliver items before __aexit__ flushes.
# The hold is deliberately much longer than the test's collect timeout
# so a regression (force_flush no-op) surfaces as a missing item rather
# than flaking on slow CI.
client = WorkflowStreamClient.from_within_activity(
batch_interval=timedelta(seconds=60)
)
async with client:
client.topic("events", type=bytes).publish(b"normal-0")
client.topic("events", type=bytes).publish(b"normal-1")
client.topic("events", type=bytes).publish(b"priority", force_flush=True)
for _ in range(100):
activity.heartbeat()
await asyncio.sleep(0.1)
@activity.defn(name="publish_batch_test")
async def publish_batch_test(count: int) -> None:
client = WorkflowStreamClient.from_within_activity(
batch_interval=timedelta(seconds=60)
)
async with client:
for i in range(count):
activity.heartbeat()
client.topic("events", type=bytes).publish(f"item-{i}".encode())
@activity.defn(name="publish_with_max_batch")
async def publish_with_max_batch(count: int) -> None:
client = WorkflowStreamClient.from_within_activity(
batch_interval=timedelta(seconds=60), max_batch_size=3
)
async with client:
for i in range(count):
activity.heartbeat()
client.topic("events", type=bytes).publish(f"item-{i}".encode())
# Yield so the flusher task can run when max_batch_size triggers
# _flush_event. Real workloads (e.g. agents awaiting LLM streams)
# yield constantly; a tight loop with no awaits would never let
# the flusher fire and would collapse back to exit-only flushing.
await asyncio.sleep(0)
# Long batch_interval ensures only max_batch_size triggers flushes.
# Context manager exit flushes any remainder.
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
async def _is_different_run(
old_handle: WorkflowHandle[Any, Any],
new_handle: WorkflowHandle[Any, Any],
) -> bool:
"""Check if new_handle points to a different run than old_handle."""
try:
desc = await new_handle.describe()
return desc.run_id != old_handle.result_run_id
except Exception:
return False
async def collect_items(
client: Client,
handle: WorkflowHandle[Any, Any],
topics: list[str] | None,
from_offset: int,
expected_count: int,
timeout: float = 15.0,
*,
result_type: type | None = bytes,
) -> list[WorkflowStreamItem]:
"""Subscribe and collect exactly expected_count items, with timeout.
Default ``result_type=bytes`` matches the bytes-oriented tests that
compare ``item.data`` against literal byte strings. Pass
``result_type=None`` for the converter's default ``Any`` decoding,
or ``result_type=RawValue`` for a ``RawValue``-wrapped ``Payload``.
"""
stream = WorkflowStreamClient.create(client, handle.id)
items: list[WorkflowStreamItem] = []
try:
async with _async_timeout(timeout):
async for item in stream.subscribe(
topics=topics,
from_offset=from_offset,
poll_cooldown=timedelta(0),
result_type=result_type,
):
items.append(item)
if len(items) >= expected_count:
break
except asyncio.TimeoutError:
pass
return items
# ---------------------------------------------------------------------------
# Tests
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_activity_publish_and_subscribe(client: Client) -> None:
"""Activity publishes items, external client subscribes and receives them."""
count = 10
async with new_worker(
client,
ActivityPublishWorkflow,
activities=[publish_items],
) as worker:
handle = await client.start_workflow(
ActivityPublishWorkflow.run,
count,
id=f"workflow-stream-basic-{uuid.uuid4()}",
task_queue=worker.task_queue,
)
# Collect activity items + the "activity_done" status item
items = await collect_items(client, handle, None, 0, count + 1)
assert len(items) == count + 1
# Check activity items
for i in range(count):
assert items[i].topic == "events"
assert items[i].data == f"item-{i}".encode()
# Check workflow-side status item
assert items[count].topic == "status"
assert items[count].data == b"activity_done"
await handle.signal(ActivityPublishWorkflow.close)
@pytest.mark.asyncio
async def test_structured_type_round_trip(client: Client) -> None:
"""Workflow publishes dataclass values; subscriber decodes via result_type."""
count = 4
async with new_worker(client, StructuredPublishWorkflow) as worker:
handle = await client.start_workflow(
StructuredPublishWorkflow.run,
count,
id=f"workflow-stream-structured-{uuid.uuid4()}",
task_queue=worker.task_queue,
)
items = await collect_items(
client, handle, None, 0, count, result_type=AgentEvent
)
assert len(items) == count
for i, item in enumerate(items):
assert isinstance(item.data, AgentEvent)
assert item.data == AgentEvent(kind="tick", payload={"i": i})
await handle.signal(StructuredPublishWorkflow.close)
@pytest.mark.asyncio
async def test_subscribe_default_decode_and_raw_value(client: Client) -> None:
"""No ``result_type`` decodes via Any; ``result_type=RawValue`` yields a ``Payload``."""
count = 2
async with new_worker(client, StructuredPublishWorkflow) as worker:
handle = await client.start_workflow(
StructuredPublishWorkflow.run,
count,
id=f"workflow-stream-default-decode-{uuid.uuid4()}",
task_queue=worker.task_queue,
)
any_items = await collect_items(
client, handle, None, 0, count, result_type=None
)
assert len(any_items) == count
for i, item in enumerate(any_items):
# Default JSON converter decodes a dataclass to a plain dict.
assert item.data == {"kind": "tick", "payload": {"i": i}}
raw_items = await collect_items(
client, handle, None, 0, count, result_type=RawValue
)
assert len(raw_items) == count
for item in raw_items:
assert isinstance(item.data, RawValue)
assert item.data.payload.data # non-empty serialized JSON bytes
await handle.signal(StructuredPublishWorkflow.close)
@pytest.mark.asyncio
async def test_subscribe_with_payload_result_type_rejected(client: Client) -> None:
"""``subscribe(result_type=Payload)`` raises — there is no Payload decode path.
Mirrors the topic-handle rejection (``stream.topic(name, type=Payload)``)
so the direct ``subscribe`` API can't smuggle in the same ambiguity that
the topic-handle layer already guards against. Users wanting raw payloads
pass ``result_type=RawValue``.
"""
from temporalio.api.common.v1 import Payload
handle = client.get_workflow_handle("nonexistent-workflow-id")
stream = WorkflowStreamClient(handle)
with pytest.raises(RuntimeError, match="result_type=Payload"):
async for _ in stream.subscribe(result_type=Payload):
pass
@pytest.mark.asyncio
async def test_topic_handle_workflow_side_publish_and_subscribe(
client: Client,
) -> None:
"""Workflow publishes via WorkflowStream.topic; client subscribes via TopicHandle."""
count = 3
async with new_worker(client, TopicHandlePublishWorkflow) as worker:
handle = await client.start_workflow(
TopicHandlePublishWorkflow.run,
count,
id=f"workflow-stream-topic-handle-{uuid.uuid4()}",
task_queue=worker.task_queue,
)
stream = WorkflowStreamClient.create(client, handle.id)
events = stream.topic("events", type=AgentEvent)
assert isinstance(events, TopicHandle)
assert events.name == "events"
assert events.type is AgentEvent
items: list[WorkflowStreamItem] = []
async with _async_timeout(15.0):
async for item in events.subscribe(poll_cooldown=timedelta(0)):
items.append(item)
if len(items) >= count:
break
assert [item.data for item in items] == [
AgentEvent(kind="tick", payload={"i": i}) for i in range(count)
]
await handle.signal(TopicHandlePublishWorkflow.close)
@workflow.defn
class TopicHandleUniquenessWorkflow:
"""Probes the WorkflowStream.topic uniqueness check in @workflow.init.
Returns a tuple (idempotent_ok, error_message) so the test can assert
both branches: same-type rebind is silent, different-type rebind raises.
"""
@workflow.init
def __init__(self) -> None:
from temporalio.api.common.v1 import Payload
self.stream = WorkflowStream()
first = self.stream.topic("events", type=AgentEvent)
self._idempotent_ok = (
isinstance(
self.stream.topic("events", type=AgentEvent), WorkflowTopicHandle
)
and first.type is AgentEvent
)
try:
self.stream.topic("events", type=bytes)
except RuntimeError as exc:
self._error = str(exc)
else:
self._error = ""
try:
self.stream.topic("misused", type=Payload)
except RuntimeError as exc:
self._payload_error = str(exc)
else:
self._payload_error = ""
@workflow.run
async def run(self) -> tuple[bool, str, str]:
return (self._idempotent_ok, self._error, self._payload_error)
@pytest.mark.asyncio
async def test_topic_handle_uniqueness_on_workflow_stream(client: Client) -> None:
"""Same-type rebind is idempotent; different-type rebind raises in @workflow.init.
Also covers the workflow-side rejection of ``type=Payload`` —
binding a topic to ``Payload`` itself has no decode path, so
``WorkflowStream.topic`` raises in ``@workflow.init``.
"""
async with new_worker(client, TopicHandleUniquenessWorkflow) as worker:
idempotent_ok, error, payload_error = await client.execute_workflow(
TopicHandleUniquenessWorkflow.run,
id=f"workflow-stream-handle-unique-{uuid.uuid4()}",
task_queue=worker.task_queue,
)
assert idempotent_ok is True
assert "already bound to type" in error
assert "events" in error
assert "type=Payload" in payload_error
@pytest.mark.asyncio
async def test_topic_handle_client_uniqueness(client: Client) -> None:
"""Re-binding a topic name to a different type on a client raises."""
handle = client.get_workflow_handle("nonexistent-workflow-id")
stream = WorkflowStreamClient(handle)
first = stream.topic("events", type=AgentEvent)
assert first.name == "events"
assert first.type is AgentEvent
# Same type is idempotent.
again = stream.topic("events", type=AgentEvent)
assert again.type is AgentEvent
# Different type raises.
with pytest.raises(RuntimeError, match="already bound to type"):
stream.topic("events", type=bytes)
# Different topic with a different type is fine.
other = stream.topic("other", type=bytes)
assert other.type is bytes
# Any escape hatch coexists on a different topic. Omitting ``type``
# is the documented form (defaults to ``typing.Any``); we also
# exercise the explicit ``type=Any`` path with the cast required
# because ``Any`` is a typing special form rather than a class.
raw = stream.topic("forwarded")
assert raw.type is Any
explicit = stream.topic(
"forwarded-explicit", type=cast(type[Any], cast(object, Any))
)
assert explicit.type is Any
# Binding to Payload itself is rejected — subscribers would have
# no decode path. Pre-built Payload values can still be published
# via a normally-typed handle (zero-copy fast path).
from temporalio.api.common.v1 import Payload
with pytest.raises(RuntimeError, match="type=Payload"):
stream.topic("misused", type=Payload)
@pytest.mark.asyncio
async def test_topic_handle_payload_passthrough(client: Client) -> None:
"""Pre-built Payloads pass through topic.publish regardless of bound type."""
count = 2
async with new_worker(client, BasicWorkflowStreamWorkflow) as worker:
handle = await client.start_workflow(
BasicWorkflowStreamWorkflow.run,
id=f"workflow-stream-handle-payload-{uuid.uuid4()}",
task_queue=worker.task_queue,
)
stream = WorkflowStreamClient.create(
client, handle.id, batch_interval=timedelta(milliseconds=50)
)
events = stream.topic("events", type=bytes)
async with stream:
converter = DataConverter.default.payload_converter
for i in range(count):
payload = converter.to_payloads([f"raw-{i}".encode()])[0]
events.publish(payload)
await stream.flush()
items = await collect_items(client, handle, ["events"], 0, count)
assert [item.data for item in items] == [
f"raw-{i}".encode() for i in range(count)
]
await handle.signal(BasicWorkflowStreamWorkflow.close)
@pytest.mark.asyncio
async def test_topic_filtering(client: Client) -> None:
"""Publish to multiple topics, subscribe with filter."""
count = 9 # 3 per topic
async with new_worker(
client,
MultiTopicWorkflow,
activities=[publish_multi_topic],
) as worker:
handle = await client.start_workflow(
MultiTopicWorkflow.run,
count,
id=f"workflow-stream-filter-{uuid.uuid4()}",
task_queue=worker.task_queue,
)
# Subscribe to topic "a" only — should get 3 items
a_items = await collect_items(client, handle, ["a"], 0, 3)
assert len(a_items) == 3
assert all(item.topic == "a" for item in a_items)
# Subscribe to ["a", "c"] — should get 6 items
ac_items = await collect_items(client, handle, ["a", "c"], 0, 6)
assert len(ac_items) == 6
assert all(item.topic in ("a", "c") for item in ac_items)
# Subscribe to all (None) — should get all 9
all_items = await collect_items(client, handle, None, 0, 9)
assert len(all_items) == 9
await handle.signal(MultiTopicWorkflow.close)
@pytest.mark.asyncio
async def test_subscribe_from_offset_and_per_item_offsets(client: Client) -> None:
"""Subscribe from zero and non-zero offsets; each item carries its global offset."""
count = 5
async with new_worker(
client,
WorkflowSidePublishWorkflow,
) as worker:
handle = await client.start_workflow(
WorkflowSidePublishWorkflow.run,
count,
id=f"workflow-stream-offset-{uuid.uuid4()}",
task_queue=worker.task_queue,
)
# Subscribe from offset 0 — all items, offsets 0..count-1
all_items = await collect_items(client, handle, None, 0, count)
assert len(all_items) == count
for i, item in enumerate(all_items):
assert item.offset == i
assert item.data == f"item-{i}".encode()
# Subscribe from offset 3 — items 3, 4 with offsets 3, 4
later_items = await collect_items(client, handle, None, 3, 2)
assert len(later_items) == 2
assert later_items[0].offset == 3
assert later_items[0].data == b"item-3"
assert later_items[1].offset == 4
assert later_items[1].data == b"item-4"
await handle.signal(WorkflowSidePublishWorkflow.close)
@pytest.mark.asyncio
async def test_per_item_offsets_with_topic_filter(client: Client) -> None:
"""Per-item offsets are global (not per-topic) even when filtering."""
count = 9 # 3 per topic (a, b, c round-robin)
async with new_worker(
client,
MultiTopicWorkflow,
activities=[publish_multi_topic],
) as worker:
handle = await client.start_workflow(
MultiTopicWorkflow.run,
count,
id=f"workflow-stream-item-offset-filter-{uuid.uuid4()}",
task_queue=worker.task_queue,
)
# Subscribe to topic "a" only — items are at global offsets 0, 3, 6
a_items = await collect_items(client, handle, ["a"], 0, 3)
assert len(a_items) == 3
assert a_items[0].offset == 0
assert a_items[1].offset == 3
assert a_items[2].offset == 6
# Subscribe to topic "b" — items are at global offsets 1, 4, 7
b_items = await collect_items(client, handle, ["b"], 0, 3)
assert len(b_items) == 3
assert b_items[0].offset == 1
assert b_items[1].offset == 4
assert b_items[2].offset == 7
await handle.signal(MultiTopicWorkflow.close)
@pytest.mark.asyncio
async def test_poll_truncated_offset_returns_application_error(client: Client) -> None:
"""Polling a truncated offset raises ApplicationError (not ValueError)
and does not crash the workflow task."""
async with new_worker(
client,
TruncateWorkflow,
) as worker:
handle = await client.start_workflow(
TruncateWorkflow.run,
5,
id=f"workflow-stream-trunc-error-{uuid.uuid4()}",
task_queue=worker.task_queue,
)
# Truncate up to offset 3 via update — completion is explicit.
await handle.execute_update("truncate", 3)
# Poll from offset 1 (truncated) — should get ApplicationError,
# NOT crash the workflow task. Catching WorkflowUpdateFailedError is
# sufficient to prove the handler raised ApplicationError: Temporal's
# update protocol completes the update with this error only when the
# handler raises ApplicationError. A bare ValueError (or any other
# exception) would fail the workflow task instead, causing
# execute_update to hang — not raise. The follow-up collect_items
# below proves the workflow task wasn't poisoned.
with pytest.raises(WorkflowUpdateFailedError) as exc_info:
await handle.execute_update(
"__temporal_workflow_stream_poll",
PollInput(topics=[], from_offset=1),
result_type=PollResult,
)
cause = exc_info.value.cause
assert isinstance(cause, ApplicationError)
assert cause.type == "TruncatedOffset"
# Workflow should still be usable — poll from valid offset 3
items = await collect_items(client, handle, None, 3, 2)
assert len(items) == 2
assert items[0].offset == 3
await handle.signal("close")
@pytest.mark.asyncio
async def test_truncate_past_end_raises_application_error(client: Client) -> None:
"""truncate() with an offset past the log end raises ApplicationError
(type=TruncateOutOfRange) — the update surfaces as a clean failure
without poisoning the workflow task."""
async with new_worker(
client,
TruncateWorkflow,
) as worker:
handle = await client.start_workflow(
TruncateWorkflow.run,
2,
id=f"workflow-stream-trunc-oor-{uuid.uuid4()}",
task_queue=worker.task_queue,
)
# Only 2 items exist; asking to truncate to offset 5 is out of range.
with pytest.raises(WorkflowUpdateFailedError) as exc_info:
await handle.execute_update("truncate", 5)
cause = exc_info.value.cause
assert isinstance(cause, ApplicationError)
assert cause.type == "TruncateOutOfRange"
# Workflow task wasn't poisoned — a valid poll still completes.
items = await collect_items(client, handle, None, 0, 2)
assert len(items) == 2
await handle.signal("close")
@pytest.mark.asyncio
async def test_subscribe_recovers_from_truncation(client: Client) -> None:
"""subscribe() auto-recovers when offset falls behind truncation."""
async with new_worker(
client,
TruncateWorkflow,
) as worker:
handle = await client.start_workflow(
TruncateWorkflow.run,
5,
id=f"workflow-stream-trunc-recover-{uuid.uuid4()}",
task_queue=worker.task_queue,
)
# Truncate first 3. The update returns after the handler completes.
await handle.execute_update("truncate", 3)
# subscribe from offset 1 (truncated) — should auto-recover
# and deliver items from base_offset (3)
stream = WorkflowStreamClient(handle)
items: list[WorkflowStreamItem] = []
try:
async with _async_timeout(5):
async for item in stream.subscribe(
from_offset=1, poll_cooldown=timedelta(0), result_type=bytes
):
items.append(item)
if len(items) >= 2:
break
except asyncio.TimeoutError:
pass
assert len(items) == 2
assert items[0].offset == 3
await handle.signal("close")
@pytest.mark.asyncio
async def test_truncate_during_waiting_poll_raises_truncated_offset(
client: Client,
) -> None:
"""A truncate that advances ``base_offset`` past a waiting poll's
``from_offset`` must wake the poll and raise ``TruncatedOffset``.
Reproduces the bug where ``_on_poll`` captured ``log_offset`` once
before ``wait_condition`` and then sliced ``self._log[log_offset:]``
against the post-truncate state. With the old predicate
``len(self._log) > log_offset`` the wait would either never fire
(truncation shrinks the log below the captured offset) or fire on a
later publish and silently emit the wrong items at offsets the
subscriber had already moved past.
"""
async with new_worker(client, TruncateRaceWorkflow) as worker:
handle = await client.start_workflow(
TruncateRaceWorkflow.run,
id=f"workflow-stream-trunc-race-{uuid.uuid4()}",
task_queue=worker.task_queue,
)
# Seed: 5 items at offsets 0..4. base_offset stays 0.
await handle.execute_update(TruncateRaceWorkflow.publish, 5)
# Park a poll from offset=10 — past the current end of the log.
# With wait_for_stage=ACCEPTED the handler has begun executing
# and is parked at workflow.wait_condition by the time the
# client gets the handle back.
poll_handle = await handle.start_update(
"__temporal_workflow_stream_poll",
PollInput(topics=[], from_offset=10),
result_type=PollResult,
wait_for_stage=WorkflowUpdateStage.ACCEPTED,
)
# In one workflow activation: publish 7 more items (log grows to
# 12 entries at offsets 0..11) and then truncate to 11. Result:
# base_offset=11, log=[item @11]. The waiting poll's
# from_offset=10 is now strictly less than base_offset, so the
# fixed predicate must wake it and the post-wait recompute must
# raise TruncatedOffset. Both halves of the fix are exercised:
# without the predicate change the wait stays asleep through
# this activation; without the post-wait recompute the slice