@native-sdk/cli 0.5.3 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/build/app.zig +91 -2
  2. package/build.zig +756 -5
  3. package/build.zig.zon +7 -0
  4. package/native-sdk.d.ts +19 -1
  5. package/package.json +9 -9
  6. package/packages/core/package-lock.json +2 -2
  7. package/packages/core/package.json +1 -1
  8. package/packages/core/rt/rt.zig +416 -9
  9. package/packages/core/sdk/core.ts +706 -5
  10. package/packages/core/sdk/events.ts +17 -8
  11. package/packages/core/src/checker.ts +305 -2
  12. package/packages/core/src/diagnostics.ts +12 -0
  13. package/packages/core/src/emitter.ts +3187 -264
  14. package/packages/core/src/typed_ast.ts +51 -4
  15. package/packages/core/src/types.ts +34 -1
  16. package/skill-data/native-ui/SKILL.md +42 -4
  17. package/skill-data/ts-core/SKILL.md +13 -3
  18. package/src/app_runner/root.zig +112 -10
  19. package/src/app_runner/ts_core_main.zig +4 -0
  20. package/src/automation/layout_fingerprint.zig +160 -0
  21. package/src/automation/protocol.zig +82 -33
  22. package/src/automation/root.zig +1 -0
  23. package/src/automation/server.zig +1 -1
  24. package/src/automation/snapshot.zig +68 -9
  25. package/src/automation/watcher.zig +1 -1
  26. package/src/embed/host.zig +5 -0
  27. package/src/embed/tests.zig +119 -1
  28. package/src/embed/ui_host.zig +13 -0
  29. package/src/platform/linux/gtk_host.c +639 -16
  30. package/src/platform/linux/gtk_host.h +25 -0
  31. package/src/platform/linux/root.zig +351 -7
  32. package/src/platform/macos/appkit_host.h +152 -8
  33. package/src/platform/macos/appkit_host.m +1816 -100
  34. package/src/platform/macos/cef_host.mm +372 -11
  35. package/src/platform/macos/root.zig +379 -11
  36. package/src/platform/null_platform.zig +696 -9
  37. package/src/platform/null_platform_tests.zig +35 -0
  38. package/src/platform/root.zig +42 -0
  39. package/src/platform/types.zig +524 -18
  40. package/src/platform/windows/root.zig +432 -9
  41. package/src/platform/windows/webview2_host.cpp +482 -45
  42. package/src/primitives/app_manifest/comptime_scene.zig +5 -0
  43. package/src/primitives/app_manifest/root.zig +1 -0
  44. package/src/primitives/app_manifest/types.zig +32 -0
  45. package/src/primitives/app_manifest/validation.zig +18 -0
  46. package/src/primitives/canvas/a11y_audit.zig +33 -11
  47. package/src/primitives/canvas/a11y_audit_tests.zig +20 -0
  48. package/src/primitives/canvas/drawing.zig +25 -0
  49. package/src/primitives/canvas/equality.zig +8 -0
  50. package/src/primitives/canvas/events.zig +103 -16
  51. package/src/primitives/canvas/frame.zig +125 -1
  52. package/src/primitives/canvas/layout_audit.zig +22 -5
  53. package/src/primitives/canvas/markdown_hostile_tests.zig +8 -4
  54. package/src/primitives/canvas/render_tests.zig +13 -10
  55. package/src/primitives/canvas/root.zig +48 -0
  56. package/src/primitives/canvas/terminal_box.zig +471 -0
  57. package/src/primitives/canvas/terminal_grid.zig +978 -0
  58. package/src/primitives/canvas/terminal_grid_tests.zig +1093 -0
  59. package/src/primitives/canvas/test_support.zig +1 -0
  60. package/src/primitives/canvas/tests.zig +2 -0
  61. package/src/primitives/canvas/text_tests.zig +39 -4
  62. package/src/primitives/canvas/tokens.zig +115 -12
  63. package/src/primitives/canvas/ui.zig +535 -12
  64. package/src/primitives/canvas/ui_markup.zig +253 -36
  65. package/src/primitives/canvas/ui_markup_binary.zig +4 -1
  66. package/src/primitives/canvas/ui_markup_compiled.zig +195 -9
  67. package/src/primitives/canvas/ui_markup_compiled_tests.zig +188 -8
  68. package/src/primitives/canvas/ui_markup_contract.zig +89 -6
  69. package/src/primitives/canvas/ui_markup_contract_tests.zig +65 -1
  70. package/src/primitives/canvas/ui_markup_huge_document_tests.zig +154 -0
  71. package/src/primitives/canvas/ui_markup_huge_model_tests.zig +1 -0
  72. package/src/primitives/canvas/ui_markup_reflect.zig +75 -24
  73. package/src/primitives/canvas/ui_markup_tests.zig +178 -9
  74. package/src/primitives/canvas/ui_markup_view.zig +220 -11
  75. package/src/primitives/canvas/ui_markup_view_tests.zig +553 -28
  76. package/src/primitives/canvas/ui_schema.zig +110 -17
  77. package/src/primitives/canvas/ui_schema_tests.zig +18 -10
  78. package/src/primitives/canvas/ui_tests.zig +141 -9
  79. package/src/primitives/canvas/widget_access.zig +28 -2
  80. package/src/primitives/canvas/widget_anchored_tests.zig +48 -0
  81. package/src/primitives/canvas/widget_invalidation.zig +81 -1
  82. package/src/primitives/canvas/widget_layout.zig +59 -11
  83. package/src/primitives/canvas/widget_layout_tests.zig +125 -4
  84. package/src/primitives/canvas/widget_render.zig +272 -18
  85. package/src/primitives/canvas/widget_render_scroll.zig +108 -27
  86. package/src/primitives/canvas/widget_routing.zig +59 -7
  87. package/src/primitives/canvas/widget_runtime.zig +23 -0
  88. package/src/primitives/canvas/widget_runtime_tests.zig +149 -0
  89. package/src/primitives/canvas/widget_semantics.zig +119 -11
  90. package/src/primitives/canvas/widget_semantics_tests.zig +409 -0
  91. package/src/primitives/canvas/widget_tree.zig +17 -0
  92. package/src/primitives/canvas/widgets.zig +132 -0
  93. package/src/root.zig +23 -0
  94. package/src/runtime/api.zig +76 -5
  95. package/src/runtime/automation_commands.zig +20 -1
  96. package/src/runtime/automation_snapshot.zig +25 -1
  97. package/src/runtime/automation_widget_dispatch.zig +73 -8
  98. package/src/runtime/bridge_payload.zig +8 -0
  99. package/src/runtime/bridge_responses.zig +5 -0
  100. package/src/runtime/builtin_bridge.zig +9 -4
  101. package/src/runtime/canvas_font_tests.zig +439 -2
  102. package/src/runtime/canvas_fonts.zig +61 -6
  103. package/src/runtime/canvas_frame.zig +62 -7
  104. package/src/runtime/canvas_frame_animation_tests.zig +5 -4
  105. package/src/runtime/canvas_frame_helpers.zig +190 -1
  106. package/src/runtime/canvas_frame_invalidation_tests.zig +531 -0
  107. package/src/runtime/canvas_frame_patch_tests.zig +161 -10
  108. package/src/runtime/canvas_frame_retained_tests.zig +5 -2
  109. package/src/runtime/canvas_image_tests.zig +195 -0
  110. package/src/runtime/canvas_images.zig +45 -12
  111. package/src/runtime/canvas_widget_accessibility_tests.zig +1 -1
  112. package/src/runtime/canvas_widget_clipboard_tests.zig +40 -0
  113. package/src/runtime/canvas_widget_context_menu.zig +269 -32
  114. package/src/runtime/canvas_widget_context_menu_tests.zig +640 -14
  115. package/src/runtime/canvas_widget_display.zig +1 -1
  116. package/src/runtime/canvas_widget_event_tests.zig +1823 -0
  117. package/src/runtime/canvas_widget_events.zig +240 -24
  118. package/src/runtime/canvas_widget_runtime.zig +213 -29
  119. package/src/runtime/canvas_widget_scroll_driver_tests.zig +170 -7
  120. package/src/runtime/canvas_widget_scroll_drivers.zig +151 -17
  121. package/src/runtime/canvas_widget_scroll_tests.zig +435 -23
  122. package/src/runtime/canvas_widget_state.zig +6 -0
  123. package/src/runtime/canvas_widget_text_tests.zig +1 -1
  124. package/src/runtime/core.zig +131 -13
  125. package/src/runtime/effects.zig +8136 -180
  126. package/src/runtime/effects_channel_tests.zig +3519 -0
  127. package/src/runtime/effects_fetch_tests.zig +89 -1
  128. package/src/runtime/effects_file_tests.zig +41 -1
  129. package/src/runtime/effects_image_tests.zig +1304 -0
  130. package/src/runtime/effects_pty_tests.zig +1362 -0
  131. package/src/runtime/effects_tests.zig +167 -9
  132. package/src/runtime/effects_video_tests.zig +3609 -0
  133. package/src/runtime/flow.zig +42 -4
  134. package/src/runtime/gpu_surface_events.zig +473 -13
  135. package/src/runtime/media_surface.zig +116 -11
  136. package/src/runtime/media_surface_tests.zig +61 -0
  137. package/src/runtime/pty.zig +1252 -0
  138. package/src/runtime/pty_windows.zig +1780 -0
  139. package/src/runtime/root.zig +36 -0
  140. package/src/runtime/runtime_event_tests.zig +20 -1
  141. package/src/runtime/session_blobs.zig +689 -0
  142. package/src/runtime/session_journal.zig +432 -62
  143. package/src/runtime/session_record.zig +43 -2
  144. package/src/runtime/session_replay.zig +556 -20
  145. package/src/runtime/session_tests.zig +2087 -1
  146. package/src/runtime/shell_layout.zig +7 -0
  147. package/src/runtime/terminal_session.zig +1569 -0
  148. package/src/runtime/terminal_session_tests.zig +450 -0
  149. package/src/runtime/terminal_vt_ghostty.zig +15 -0
  150. package/src/runtime/terminal_vt_stub.zig +13 -0
  151. package/src/runtime/testdata/fonts/NotoSansSC-Receipt.ttf +0 -0
  152. package/src/runtime/testdata/fonts/OFL.txt +93 -0
  153. package/src/runtime/tests.zig +8 -0
  154. package/src/runtime/ts_core_host.zig +1320 -45
  155. package/src/runtime/ts_core_host_tests.zig +1100 -1
  156. package/src/runtime/ts_ui_app.zig +23 -5
  157. package/src/runtime/ui_app.zig +2444 -69
  158. package/src/runtime/ui_app_tests.zig +3171 -744
  159. package/src/runtime/ui_app_virtual_variable_tests.zig +4 -2
  160. package/src/runtime/ui_app_window_tests.zig +736 -0
  161. package/src/runtime/view.zig +190 -2
  162. package/src/runtime/view_widget_scroll.zig +218 -68
  163. package/src/runtime/view_widget_text.zig +11 -2
  164. package/src/runtime/view_widget_tree.zig +111 -3
  165. package/src/runtime/window_command_bridge_tests.zig +117 -0
  166. package/src/runtime/window_storage.zig +77 -2
  167. package/src/runtime/window_view_runtime.zig +34 -2
  168. package/src/runtime/window_views.zig +62 -1
  169. package/src/terminal_session_tests_root.zig +15 -0
  170. package/src/tooling/manifest.zig +75 -0
  171. package/src/tooling/raw_manifest.zig +2 -0
  172. package/src/tooling/templates.zig +244 -8
@@ -0,0 +1,3519 @@
1
+ //! External-source channel coverage: the `fx.openChannel` family —
2
+ //! lifecycle (open/post/deliver/close), the thread-safe posting handle
3
+ //! and its post-close/post-teardown safety, back-pressure drop
4
+ //! accounting, the shared key space with the slot-backed families, and
5
+ //! the record/replay acceptance story: a session recorded WITH a live
6
+ //! posting thread replays fingerprint-identical with no source thread
7
+ //! NEEDED — the journaled events are the whole stream. Producers that
8
+ //! consult `ChannelHandle.live()` before launching never start under
9
+ //! replay (fully offline); producers that launch unconditionally are
10
+ //! stopped at their first post. Both shapes are pinned below.
11
+
12
+ const std = @import("std");
13
+ const geometry = @import("geometry");
14
+ const app_manifest = @import("app_manifest");
15
+ const core = @import("core.zig");
16
+ const ui_app_mod = @import("ui_app.zig");
17
+ const effects_mod = @import("effects.zig");
18
+ const platform_mod = @import("../platform/root.zig");
19
+ const journal = @import("session_journal.zig");
20
+ const session_record = @import("session_record.zig");
21
+ const session_replay = @import("session_replay.zig");
22
+
23
+ const testing = std.testing;
24
+ const PostResult = effects_mod.ChannelHandle.PostResult;
25
+
26
+ // ------------------------------------------------- direct-channel tests
27
+ //
28
+ // The channel family needs no executor, worker, or platform: a direct
29
+ // `Effects(Msg)` instance plus `takeMsg` drives the whole lifecycle.
30
+
31
+ const DirectMsg = union(enum) {
32
+ event: effects_mod.EffectChannelEvent,
33
+ response: effects_mod.EffectResponse,
34
+ exit: effects_mod.EffectExit,
35
+ };
36
+
37
+ const DirectFx = effects_mod.Effects(DirectMsg);
38
+
39
+ fn expectData(fx: *DirectFx, key: u64, bytes: []const u8) !effects_mod.EffectChannelEvent {
40
+ const msg = fx.takeMsg() orelse return error.TestExpectedMsg;
41
+ try testing.expect(msg == .event);
42
+ try testing.expectEqual(key, msg.event.key);
43
+ try testing.expectEqual(effects_mod.EffectChannelEventKind.data, msg.event.kind);
44
+ try testing.expectEqualStrings(bytes, msg.event.bytes);
45
+ return msg.event;
46
+ }
47
+
48
+ test "channel lifecycle: open, post, deliver in order, close, reopen" {
49
+ var fx = DirectFx.init(testing.allocator);
50
+ defer fx.deinit();
51
+ fx.executor = .fake;
52
+
53
+ const handle = fx.openChannel(.{ .key = 7, .on_event = DirectFx.channelMsg(.event) });
54
+ try testing.expect(handle.shared != null);
55
+
56
+ try testing.expectEqual(PostResult.accepted, handle.post("alpha"));
57
+ try testing.expectEqual(PostResult.accepted, handle.post("beta"));
58
+ try testing.expectEqual(PostResult.accepted, handle.post("gamma"));
59
+ try testing.expect(fx.hasPending());
60
+
61
+ _ = try expectData(&fx, 7, "alpha");
62
+ _ = try expectData(&fx, 7, "beta");
63
+ const last = try expectData(&fx, 7, "gamma");
64
+ try testing.expectEqual(@as(u32, 0), last.dropped_pending);
65
+ try testing.expectEqual(@as(u32, 0), last.dropped_total);
66
+
67
+ fx.closeChannel(7);
68
+ // Posts stop landing the moment close runs — before the terminal
69
+ // even delivers.
70
+ try testing.expectEqual(PostResult.closed, handle.post("late"));
71
+ const closed = fx.takeMsg() orelse return error.TestExpectedMsg;
72
+ try testing.expectEqual(effects_mod.EffectChannelEventKind.closed, closed.event.kind);
73
+ try testing.expectEqual(@as(u32, 0), closed.event.dropped_total);
74
+ try testing.expectEqual(@as(?DirectMsg, null), fx.takeMsg());
75
+
76
+ // Delivery of `.closed` retired the key: the same key opens again,
77
+ // and the OLD handle's generation is dead against the reused slot.
78
+ const again = fx.openChannel(.{ .key = 7, .on_event = DirectFx.channelMsg(.event) });
79
+ try testing.expectEqual(PostResult.closed, handle.post("stale generation"));
80
+ try testing.expectEqual(PostResult.accepted, again.post("fresh"));
81
+ _ = try expectData(&fx, 7, "fresh");
82
+ fx.closeChannel(7);
83
+ _ = fx.takeMsg();
84
+ }
85
+
86
+ test "channel posts staged before close flush ahead of the closed terminal" {
87
+ var fx = DirectFx.init(testing.allocator);
88
+ defer fx.deinit();
89
+ fx.executor = .fake;
90
+
91
+ const handle = fx.openChannel(.{ .key = 3, .on_event = DirectFx.channelMsg(.event) });
92
+ try testing.expectEqual(PostResult.accepted, handle.post("one"));
93
+ try testing.expectEqual(PostResult.accepted, handle.post("two"));
94
+ fx.closeChannel(3);
95
+ _ = try expectData(&fx, 3, "one");
96
+ _ = try expectData(&fx, 3, "two");
97
+ const closed = fx.takeMsg() orelse return error.TestExpectedMsg;
98
+ try testing.expectEqual(effects_mod.EffectChannelEventKind.closed, closed.event.kind);
99
+ try testing.expectEqual(@as(?DirectMsg, null), fx.takeMsg());
100
+ }
101
+
102
+ const PosterThread = struct {
103
+ fn run(handle: effects_mod.ChannelHandle, count: usize) void {
104
+ var buffer: [32]u8 = undefined;
105
+ var index: usize = 0;
106
+ while (index < count) : (index += 1) {
107
+ const line = std.fmt.bufPrint(&buffer, "sample {d}", .{index}) catch unreachable;
108
+ _ = handle.post(line);
109
+ }
110
+ }
111
+ };
112
+
113
+ test "channel posts from a spawned thread deliver in post order" {
114
+ var fx = DirectFx.init(testing.allocator);
115
+ defer fx.deinit();
116
+ fx.executor = .fake;
117
+
118
+ const handle = fx.openChannel(.{ .key = 11, .on_event = DirectFx.channelMsg(.event) });
119
+ const thread = try std.Thread.spawn(.{}, PosterThread.run, .{ handle, 10 });
120
+ thread.join();
121
+
122
+ var buffer: [32]u8 = undefined;
123
+ var index: usize = 0;
124
+ while (index < 10) : (index += 1) {
125
+ const expected = try std.fmt.bufPrint(&buffer, "sample {d}", .{index});
126
+ _ = try expectData(&fx, 11, expected);
127
+ }
128
+ fx.closeChannel(11);
129
+ _ = fx.takeMsg();
130
+ }
131
+
132
+ test "a duplicate occupied key rejects the new open with one terminal" {
133
+ var fx = DirectFx.init(testing.allocator);
134
+ defer fx.deinit();
135
+ fx.executor = .fake;
136
+
137
+ const first = fx.openChannel(.{ .key = 5, .on_event = DirectFx.channelMsg(.event) });
138
+ const dup = fx.openChannel(.{ .key = 5, .on_event = DirectFx.channelMsg(.event) });
139
+ // The refused open's handle is dead — never-fails-from-the-caller's
140
+ // view means the terminal is the report, not an error code.
141
+ try testing.expect(dup.shared == null);
142
+ try testing.expectEqual(PostResult.closed, dup.post("nope"));
143
+
144
+ const rejected = fx.takeMsg() orelse return error.TestExpectedMsg;
145
+ try testing.expectEqual(effects_mod.EffectChannelEventKind.rejected, rejected.event.kind);
146
+ try testing.expectEqual(@as(u64, 5), rejected.event.key);
147
+
148
+ // The first occupancy is untouched.
149
+ try testing.expectEqual(PostResult.accepted, first.post("still live"));
150
+ _ = try expectData(&fx, 5, "still live");
151
+ fx.closeChannel(5);
152
+ _ = fx.takeMsg();
153
+ }
154
+
155
+ test "a full channel table rejects the next open" {
156
+ var fx = DirectFx.init(testing.allocator);
157
+ defer fx.deinit();
158
+ fx.executor = .fake;
159
+
160
+ var index: u64 = 0;
161
+ while (index < effects_mod.max_effect_channels) : (index += 1) {
162
+ const handle = fx.openChannel(.{ .key = 100 + index, .on_event = DirectFx.channelMsg(.event) });
163
+ try testing.expect(handle.shared != null);
164
+ }
165
+ const overflow = fx.openChannel(.{ .key = 999, .on_event = DirectFx.channelMsg(.event) });
166
+ try testing.expect(overflow.shared == null);
167
+ const rejected = fx.takeMsg() orelse return error.TestExpectedMsg;
168
+ try testing.expectEqual(effects_mod.EffectChannelEventKind.rejected, rejected.event.kind);
169
+ try testing.expectEqual(@as(u64, 999), rejected.event.key);
170
+ }
171
+
172
+ test "back-pressure: a full staging FIFO refuses posts and the next event carries the counts" {
173
+ var fx = DirectFx.init(testing.allocator);
174
+ defer fx.deinit();
175
+ fx.executor = .fake;
176
+
177
+ const handle = fx.openChannel(.{ .key = 9, .on_event = DirectFx.channelMsg(.event), .max_pending = 2 });
178
+ try testing.expectEqual(PostResult.accepted, handle.post("kept 1"));
179
+ try testing.expectEqual(PostResult.accepted, handle.post("kept 2"));
180
+ // The stage is full: refused posts answer `.dropped_full` and
181
+ // count — the staged entries are NEVER evicted for the newcomer.
182
+ try testing.expectEqual(PostResult.dropped_full, handle.post("dropped 1"));
183
+ try testing.expectEqual(PostResult.dropped_full, handle.post("dropped 2"));
184
+
185
+ const first = try expectData(&fx, 9, "kept 1");
186
+ try testing.expectEqual(@as(u32, 2), first.dropped_pending);
187
+ try testing.expectEqual(@as(u32, 2), first.dropped_total);
188
+ const second = try expectData(&fx, 9, "kept 2");
189
+ // `dropped_pending` reset with the first report; the total is the
190
+ // occupancy's honest cumulative count.
191
+ try testing.expectEqual(@as(u32, 0), second.dropped_pending);
192
+ try testing.expectEqual(@as(u32, 2), second.dropped_total);
193
+
194
+ // Room again: posts land, one more refusal counts, and the NEXT
195
+ // delivered event carries it; the `.closed` terminal reports the
196
+ // final cumulative total.
197
+ try testing.expectEqual(PostResult.accepted, handle.post("kept 3"));
198
+ try testing.expectEqual(PostResult.accepted, handle.post("kept 4"));
199
+ try testing.expectEqual(PostResult.dropped_full, handle.post("dropped 3"));
200
+ fx.closeChannel(9);
201
+ const third = try expectData(&fx, 9, "kept 3");
202
+ try testing.expectEqual(@as(u32, 1), third.dropped_pending);
203
+ try testing.expectEqual(@as(u32, 3), third.dropped_total);
204
+ _ = try expectData(&fx, 9, "kept 4");
205
+ const closed = fx.takeMsg() orelse return error.TestExpectedMsg;
206
+ try testing.expectEqual(effects_mod.EffectChannelEventKind.closed, closed.event.kind);
207
+ try testing.expectEqual(@as(u32, 0), closed.event.dropped_pending);
208
+ try testing.expectEqual(@as(u32, 3), closed.event.dropped_total);
209
+ }
210
+
211
+ test "an oversized post answers dropped_oversized and counts as a drop" {
212
+ var fx = DirectFx.init(testing.allocator);
213
+ defer fx.deinit();
214
+ fx.executor = .fake;
215
+
216
+ const handle = fx.openChannel(.{ .key = 4, .on_event = DirectFx.channelMsg(.event) });
217
+ const oversized = [_]u8{'x'} ** (effects_mod.max_effect_channel_bytes + 1);
218
+ try testing.expectEqual(PostResult.dropped_oversized, handle.post(&oversized));
219
+ const at_bound = [_]u8{'y'} ** effects_mod.max_effect_channel_bytes;
220
+ try testing.expectEqual(PostResult.accepted, handle.post(&at_bound));
221
+
222
+ const event = try expectData(&fx, 4, &at_bound);
223
+ try testing.expectEqual(@as(u32, 1), event.dropped_pending);
224
+ try testing.expectEqual(@as(u32, 1), event.dropped_total);
225
+ fx.closeChannel(4);
226
+ _ = fx.takeMsg();
227
+ }
228
+
229
+ test "teardown closes every channel and post-after-teardown answers closed" {
230
+ var fx = DirectFx.init(testing.allocator);
231
+ fx.executor = .fake;
232
+
233
+ const handle = fx.openChannel(.{ .key = 12, .on_event = DirectFx.channelMsg(.event) });
234
+ try testing.expectEqual(PostResult.accepted, handle.post("staged but never delivered"));
235
+ fx.deinit();
236
+ // The handle resolves through the process-lifetime header, so a
237
+ // source thread that outlives the runtime posts into a closed
238
+ // channel — `.closed`, never a use-after-free.
239
+ try testing.expectEqual(PostResult.closed, handle.post("after teardown"));
240
+ }
241
+
242
+ test "channel keys and slot-family keys share one key space" {
243
+ var fx = DirectFx.init(testing.allocator);
244
+ defer fx.deinit();
245
+ fx.executor = .fake;
246
+
247
+ // An open channel blocks a same-key fetch...
248
+ const handle = fx.openChannel(.{ .key = 21, .on_event = DirectFx.channelMsg(.event) });
249
+ try testing.expect(handle.shared != null);
250
+ fx.fetch(.{ .key = 21, .url = "http://example.test/x", .on_response = DirectFx.responseMsg(.response) });
251
+ const rejected = fx.takeMsg() orelse return error.TestExpectedMsg;
252
+ try testing.expect(rejected == .response);
253
+ try testing.expectEqual(effects_mod.EffectFetchOutcome.rejected, rejected.response.outcome);
254
+ try testing.expectEqual(@as(usize, 0), fx.pendingFetchCount());
255
+
256
+ // ...through the whole `.closing` window: the key frees only when
257
+ // `.closed` delivers.
258
+ fx.closeChannel(21);
259
+ fx.fetch(.{ .key = 21, .url = "http://example.test/x", .on_response = DirectFx.responseMsg(.response) });
260
+ const still_rejected = fx.takeMsg() orelse return error.TestExpectedMsg;
261
+ try testing.expectEqual(effects_mod.EffectFetchOutcome.rejected, still_rejected.response.outcome);
262
+ const closed = fx.takeMsg() orelse return error.TestExpectedMsg;
263
+ try testing.expectEqual(effects_mod.EffectChannelEventKind.closed, closed.event.kind);
264
+ fx.fetch(.{ .key = 21, .url = "http://example.test/x", .on_response = DirectFx.responseMsg(.response) });
265
+ try testing.expectEqual(@as(usize, 1), fx.pendingFetchCount());
266
+
267
+ // And the reverse: a parked same-key effect blocks the channel.
268
+ fx.spawn(.{ .key = 33, .argv = &.{"probe"}, .on_exit = DirectFx.exitMsg(.exit) });
269
+ const blocked = fx.openChannel(.{ .key = 33, .on_event = DirectFx.channelMsg(.event) });
270
+ try testing.expect(blocked.shared == null);
271
+ const channel_rejected = fx.takeMsg() orelse return error.TestExpectedMsg;
272
+ try testing.expectEqual(effects_mod.EffectChannelEventKind.rejected, channel_rejected.event.kind);
273
+ try testing.expectEqual(@as(u64, 33), channel_rejected.event.key);
274
+ }
275
+
276
+ test "live() answers the producer-launch question for every handle shape" {
277
+ var fx = DirectFx.init(testing.allocator);
278
+ defer fx.deinit();
279
+ fx.executor = .fake;
280
+
281
+ // The zero handle (and a refused open's dead handle) can accept
282
+ // nothing.
283
+ const zero: effects_mod.ChannelHandle = .{};
284
+ try testing.expect(!zero.live());
285
+
286
+ const handle = fx.openChannel(.{ .key = 71, .on_event = DirectFx.channelMsg(.event) });
287
+ try testing.expect(handle.live());
288
+ const dup = fx.openChannel(.{ .key = 71, .on_event = DirectFx.channelMsg(.event) });
289
+ try testing.expect(!dup.live());
290
+
291
+ // Advisory, not a gate: `live()` flips false the moment close runs
292
+ // (posts stop landing before the terminal delivers), and the
293
+ // post's own answer remains authoritative.
294
+ fx.closeChannel(71);
295
+ try testing.expect(!handle.live());
296
+ try testing.expectEqual(PostResult.closed, handle.post("late"));
297
+ while (fx.takeMsg()) |_| {}
298
+
299
+ // A reused slot's fresh occupancy: the stale handle stays dead,
300
+ // the fresh one answers for itself.
301
+ const again = fx.openChannel(.{ .key = 71, .on_event = DirectFx.channelMsg(.event) });
302
+ try testing.expect(!handle.live());
303
+ try testing.expect(again.live());
304
+ fx.closeChannel(71);
305
+ while (fx.takeMsg()) |_| {}
306
+ }
307
+
308
+ test "channelHandle resolves the open occupancy and nothing else" {
309
+ var fx = DirectFx.init(testing.allocator);
310
+ defer fx.deinit();
311
+ fx.executor = .fake;
312
+
313
+ try testing.expect(fx.channelHandle(6) == null);
314
+ _ = fx.openChannel(.{ .key = 6, .on_event = DirectFx.channelMsg(.event) });
315
+ const resolved = fx.channelHandle(6) orelse return error.TestExpectedHandle;
316
+ try testing.expectEqual(PostResult.accepted, resolved.post("via accessor"));
317
+ fx.closeChannel(6);
318
+ // `.closing` accepts no posts, so the accessor stops resolving.
319
+ try testing.expect(fx.channelHandle(6) == null);
320
+ _ = try expectData(&fx, 6, "via accessor");
321
+ _ = fx.takeMsg();
322
+ }
323
+
324
+ test "under replay openChannel parks the occupancy and hands back an inert handle" {
325
+ var fx = DirectFx.init(testing.allocator);
326
+ defer fx.deinit();
327
+ fx.executor = .fake;
328
+ fx.armReplay();
329
+
330
+ // The parked occupancy registers exactly as a live open...
331
+ const handle = fx.openChannel(.{ .key = 17, .on_event = DirectFx.channelMsg(.event) });
332
+ try testing.expect(fx.channelHandle(17) != null);
333
+ // ...but the handle is INERT: `live()` answers false — the
334
+ // producer-launch check that keeps replay fully offline — and
335
+ // every post answers `.closed` immediately (nothing staged, no
336
+ // drop counted, nothing to journal), so a producer launched
337
+ // unconditionally exits on its first post.
338
+ try testing.expect(!handle.live());
339
+ try testing.expectEqual(PostResult.closed, handle.post("never lands"));
340
+ try testing.expect(!fx.hasPending());
341
+ try testing.expectEqual(@as(?DirectMsg, null), fx.takeMsg());
342
+
343
+ // closeChannel on the parked occupancy: no live flush, no
344
+ // self-delivered terminal — the slot parks `.closing` until the
345
+ // journaled `.closed` record feeds.
346
+ fx.closeChannel(17);
347
+ try testing.expectEqual(@as(?DirectMsg, null), fx.takeMsg());
348
+
349
+ // The fed events are the ONLY stream: the recorded data and the
350
+ // recorded terminal deliver verbatim (drop counts included), and
351
+ // the fed `.closed` retires the parked occupancy at delivery.
352
+ try fx.feedChannelEvent(17, .data, "recorded sample", 0, 2);
353
+ try fx.feedChannelEvent(17, .closed, "", 0, 2);
354
+ const data = try expectData(&fx, 17, "recorded sample");
355
+ try testing.expectEqual(@as(u32, 2), data.dropped_total);
356
+ const closed = fx.takeMsg() orelse return error.TestExpectedMsg;
357
+ try testing.expectEqual(effects_mod.EffectChannelEventKind.closed, closed.event.kind);
358
+ try testing.expectEqual(@as(u32, 2), closed.event.dropped_total);
359
+ try testing.expect(fx.channelHandle(17) == null);
360
+ }
361
+
362
+ test "a second rejection record against one park is journal damage, not a second terminal" {
363
+ var fx = DirectFx.init(testing.allocator);
364
+ defer fx.deinit();
365
+ fx.executor = .fake;
366
+ fx.armReplay();
367
+
368
+ _ = fx.openChannel(.{ .key = 29, .on_event = DirectFx.channelMsg(.event) });
369
+ // The first fed `.rejected` resolves the park's pending-order
370
+ // reservation — one open, one terminal.
371
+ try fx.feedChannelEvent(29, .rejected, "", 0, 0);
372
+ // A SECOND rejection record targeting the same park (a damaged or
373
+ // hand-edited journal — no recorder writes two terminals for one
374
+ // open) must not reuse the vacated reservation and append a
375
+ // duplicate terminal to the one-entry-per-open pending ring.
376
+ try testing.expectError(
377
+ error.ReplayDamagedRecord,
378
+ fx.feedChannelEvent(29, .rejected, "", 0, 0),
379
+ );
380
+ // Exactly one terminal delivers, and it retires the key.
381
+ const rejected = fx.takeMsg() orelse return error.TestExpectedMsg;
382
+ try testing.expectEqual(effects_mod.EffectChannelEventKind.rejected, rejected.event.kind);
383
+ try testing.expectEqual(@as(u64, 29), rejected.event.key);
384
+ try testing.expectEqual(@as(?DirectMsg, null), fx.takeMsg());
385
+ try testing.expect(fx.channelHandle(29) == null);
386
+ }
387
+
388
+ test "a data record after the open's rejection terminal is journal damage" {
389
+ // The silent-discard shape: the fed rejection will retire the slot
390
+ // at DELIVERY, so a `.data` fed before that delivery would enqueue,
391
+ // outlive the retire, and then be dropped by the delivery
392
+ // generation gate — an invalid stream that unverified replay would
393
+ // pass. Refused at the feed instead: nothing feeds past a terminal.
394
+ var fx = DirectFx.init(testing.allocator);
395
+ defer fx.deinit();
396
+ fx.executor = .fake;
397
+ fx.armReplay();
398
+
399
+ _ = fx.openChannel(.{ .key = 31, .on_event = DirectFx.channelMsg(.event) });
400
+ try fx.feedChannelEvent(31, .rejected, "", 0, 0);
401
+ try testing.expectError(
402
+ error.ReplayDamagedRecord,
403
+ fx.feedChannelEvent(31, .data, "ghost", 0, 0),
404
+ );
405
+ // Exactly the one terminal delivers, and it retires the key.
406
+ const rejected = fx.takeMsg() orelse return error.TestExpectedMsg;
407
+ try testing.expectEqual(effects_mod.EffectChannelEventKind.rejected, rejected.event.kind);
408
+ try testing.expectEqual(@as(?DirectMsg, null), fx.takeMsg());
409
+ try testing.expect(fx.channelHandle(31) == null);
410
+ }
411
+
412
+ test "a data record after the fed closed terminal is journal damage" {
413
+ // The accepted-live stream's twin of the rejection case above: the
414
+ // `.closed` terminal fed, so nothing may target the open again.
415
+ var fx = DirectFx.init(testing.allocator);
416
+ defer fx.deinit();
417
+ fx.executor = .fake;
418
+ fx.armReplay();
419
+
420
+ _ = fx.openChannel(.{ .key = 32, .on_event = DirectFx.channelMsg(.event) });
421
+ try fx.feedChannelEvent(32, .data, "recorded", 0, 0);
422
+ try fx.feedChannelEvent(32, .closed, "", 0, 0);
423
+ try testing.expectError(
424
+ error.ReplayDamagedRecord,
425
+ fx.feedChannelEvent(32, .data, "ghost", 0, 0),
426
+ );
427
+ // The recorded stream still delivers verbatim and retires the key.
428
+ _ = try expectData(&fx, 32, "recorded");
429
+ const closed = fx.takeMsg() orelse return error.TestExpectedMsg;
430
+ try testing.expectEqual(effects_mod.EffectChannelEventKind.closed, closed.event.kind);
431
+ try testing.expectEqual(@as(?DirectMsg, null), fx.takeMsg());
432
+ try testing.expect(fx.channelHandle(32) == null);
433
+ }
434
+
435
+ test "a closed terminal refused by queue back-pressure stays retryable after a drain" {
436
+ // The replay pump's back-pressure contract: a feed that answers
437
+ // `EffectQueueFull` is drained around and fed AGAIN (see
438
+ // `replaySession`). The park's terminal transition must therefore
439
+ // apply only once the event actually enqueues — a `.closed` that
440
+ // marked the park terminated before a refused enqueue would turn
441
+ // the pump's legal retry into a ReplayDamagedRecord refusal of a
442
+ // valid journal.
443
+ var fx = DirectFx.init(testing.allocator);
444
+ defer fx.deinit();
445
+ fx.executor = .fake;
446
+ fx.armReplay();
447
+
448
+ _ = fx.openChannel(.{ .key = 34, .on_event = DirectFx.channelMsg(.event) });
449
+ // Fill the completion queue with recorded data events until it
450
+ // back-pressures.
451
+ var fed: usize = 0;
452
+ while (true) : (fed += 1) {
453
+ if (fed > 10_000) return error.TestExpectedBackPressure;
454
+ fx.feedChannelEvent(34, .data, "burst", 0, 0) catch |err| switch (err) {
455
+ error.EffectQueueFull => break,
456
+ else => return err,
457
+ };
458
+ }
459
+ // The terminal also answers back-pressure...
460
+ try testing.expectError(error.EffectQueueFull, fx.feedChannelEvent(34, .closed, "", 0, 0));
461
+ // ...the pump drains...
462
+ var delivered: usize = 0;
463
+ while (fx.takeMsg()) |msg| {
464
+ try testing.expectEqual(effects_mod.EffectChannelEventKind.data, msg.event.kind);
465
+ delivered += 1;
466
+ }
467
+ try testing.expectEqual(fed, delivered);
468
+ // ...and the retried terminal lands cleanly, delivering exactly
469
+ // once and retiring the key.
470
+ try fx.feedChannelEvent(34, .closed, "", 0, 0);
471
+ const closed = fx.takeMsg() orelse return error.TestExpectedMsg;
472
+ try testing.expectEqual(effects_mod.EffectChannelEventKind.closed, closed.event.kind);
473
+ try testing.expectEqual(@as(?DirectMsg, null), fx.takeMsg());
474
+ try testing.expect(fx.channelHandle(34) == null);
475
+ }
476
+
477
+ test "a rejection record after the stream proved the open accepted is journal damage" {
478
+ // A refused open delivers nothing before its refusal, so a
479
+ // `.rejected` fed after a `.data` vacated the park is a terminal
480
+ // the recorded open can never have produced — and the refusal must
481
+ // not corrupt the park: the stream's real terminal still lands.
482
+ var fx = DirectFx.init(testing.allocator);
483
+ defer fx.deinit();
484
+ fx.executor = .fake;
485
+ fx.armReplay();
486
+
487
+ _ = fx.openChannel(.{ .key = 33, .on_event = DirectFx.channelMsg(.event) });
488
+ try fx.feedChannelEvent(33, .data, "recorded", 0, 0);
489
+ try testing.expectError(
490
+ error.ReplayDamagedRecord,
491
+ fx.feedChannelEvent(33, .rejected, "", 0, 0),
492
+ );
493
+ try fx.feedChannelEvent(33, .closed, "", 0, 0);
494
+ _ = try expectData(&fx, 33, "recorded");
495
+ const closed = fx.takeMsg() orelse return error.TestExpectedMsg;
496
+ try testing.expectEqual(effects_mod.EffectChannelEventKind.closed, closed.event.kind);
497
+ try testing.expectEqual(@as(?DirectMsg, null), fx.takeMsg());
498
+ try testing.expect(fx.channelHandle(33) == null);
499
+ }
500
+
501
+ test "under replay a duplicate open still rejects symmetrically against the parked occupancy" {
502
+ var fx = DirectFx.init(testing.allocator);
503
+ defer fx.deinit();
504
+ fx.executor = .fake;
505
+ fx.armReplay();
506
+
507
+ _ = fx.openChannel(.{ .key = 23, .on_event = DirectFx.channelMsg(.event) });
508
+ // The duplicate open is regenerating validation: the replayed
509
+ // dispatch refuses against the parked occupancy exactly as the
510
+ // recording refused against the live one, and delivers its own
511
+ // `.rejected` terminal loop-side (the journaled copy is skipped by
512
+ // the replay pump, not fed).
513
+ const dup = fx.openChannel(.{ .key = 23, .on_event = DirectFx.channelMsg(.event) });
514
+ try testing.expect(dup.shared == null);
515
+ try testing.expectEqual(PostResult.closed, dup.post("nope"));
516
+ const rejected = fx.takeMsg() orelse return error.TestExpectedMsg;
517
+ try testing.expectEqual(effects_mod.EffectChannelEventKind.rejected, rejected.event.kind);
518
+ try testing.expectEqual(@as(u64, 23), rejected.event.key);
519
+ // The parked first occupancy is untouched by the refusal.
520
+ try testing.expect(fx.channelHandle(23) != null);
521
+ }
522
+
523
+ // ------------------------------------------- lock-order invariant gate
524
+
525
+ /// A test-injected host wake hook standing where a real platform's
526
+ /// cross-thread nudge runs (macOS: main-queue dispatch, GTK:
527
+ /// `g_idle_add`, Win32: `PostMessage`). It PROBES the poster's lock
528
+ /// state: the staging mutex must never be held while the host hook
529
+ /// runs — the lock-order invariant documented at `ChannelShared.mutex`.
530
+ /// A hook observing the mutex held is the deadlock precursor this gate
531
+ /// exists to catch: drain, close, and teardown contend on that mutex,
532
+ /// so a wake path that holds it across the host call stalls the loop
533
+ /// behind a slow hook and deadlocks outright if the hook ever
534
+ /// synchronizes against a loop thread blocked on the same mutex.
535
+ const WakeProbe = struct {
536
+ var shared_under_probe: ?*effects_mod.ChannelShared = null;
537
+ var staging_mutex_free_during_wake: ?bool = null;
538
+ var wake_calls: usize = 0;
539
+
540
+ fn reset() void {
541
+ shared_under_probe = null;
542
+ staging_mutex_free_during_wake = null;
543
+ wake_calls = 0;
544
+ }
545
+
546
+ fn wake(context: ?*anyopaque) anyerror!void {
547
+ _ = context;
548
+ wake_calls += 1;
549
+ const shared = shared_under_probe orelse return;
550
+ const free = shared.mutex.inner.tryLock();
551
+ if (free) shared.mutex.inner.unlock();
552
+ staging_mutex_free_during_wake = free;
553
+ }
554
+ };
555
+
556
+ test "the staging mutex is never held across the host wake hook" {
557
+ var fx = DirectFx.init(testing.allocator);
558
+ defer fx.deinit();
559
+ fx.executor = .fake;
560
+ WakeProbe.reset();
561
+ defer WakeProbe.reset();
562
+
563
+ const services: platform_mod.PlatformServices = .{ .wake_fn = WakeProbe.wake };
564
+ fx.bindServices(&services);
565
+
566
+ const handle = fx.openChannel(.{ .key = 51, .on_event = DirectFx.channelMsg(.event) });
567
+ WakeProbe.shared_under_probe = handle.shared;
568
+
569
+ try testing.expectEqual(PostResult.accepted, handle.post("probe"));
570
+ try testing.expect(WakeProbe.wake_calls >= 1);
571
+ try testing.expectEqual(@as(?bool, true), WakeProbe.staging_mutex_free_during_wake);
572
+
573
+ WakeProbe.shared_under_probe = null;
574
+ fx.closeChannel(51);
575
+ _ = try expectData(&fx, 51, "probe");
576
+ _ = fx.takeMsg();
577
+ }
578
+
579
+ // ------------------------------------------------- wake coalescer gates
580
+
581
+ /// A counting host wake hook for the direct-channel coalescer tests:
582
+ /// stands where the null platform's atomic wake counter stands, close
583
+ /// enough to the posting seam to observe every individual host call.
584
+ const WakeCounter = struct {
585
+ var calls: usize = 0;
586
+
587
+ fn reset() void {
588
+ calls = 0;
589
+ }
590
+
591
+ fn wake(context: ?*anyopaque) anyerror!void {
592
+ _ = context;
593
+ calls += 1;
594
+ }
595
+ };
596
+
597
+ test "a burst of accepted posts latches exactly one host wake" {
598
+ var fx = DirectFx.init(testing.allocator);
599
+ defer fx.deinit();
600
+ fx.executor = .fake;
601
+ WakeCounter.reset();
602
+ const services: platform_mod.PlatformServices = .{ .wake_fn = WakeCounter.wake };
603
+ fx.bindServices(&services);
604
+
605
+ const handle = fx.openChannel(.{ .key = 52, .on_event = DirectFx.channelMsg(.event) });
606
+
607
+ // Fill the whole default stage: one wake, not max_effect_channel_pending.
608
+ var index: usize = 0;
609
+ while (index < effects_mod.max_effect_channel_pending) : (index += 1) {
610
+ try testing.expectEqual(PostResult.accepted, handle.post("burst"));
611
+ }
612
+ try testing.expectEqual(@as(usize, 1), WakeCounter.calls);
613
+
614
+ // The drain pass unlatches at its boundary and delivers the whole
615
+ // eligible backlog — one wake answered every staged entry.
616
+ var boundary = fx.drainBoundary();
617
+ var delivered: usize = 0;
618
+ while (fx.takeMsgWithin(&boundary)) |msg| {
619
+ try testing.expect(msg == .event);
620
+ delivered += 1;
621
+ }
622
+ try testing.expectEqual(effects_mod.max_effect_channel_pending, delivered);
623
+
624
+ // Refill after the drain: the unlatched coalescer wakes exactly
625
+ // once again — the fill/drain/refill cycle costs one wake per
626
+ // drain, never a standing backlog of host-queue entries.
627
+ try testing.expectEqual(PostResult.accepted, handle.post("refill"));
628
+ try testing.expectEqual(PostResult.accepted, handle.post("refill"));
629
+ try testing.expectEqual(@as(usize, 2), WakeCounter.calls);
630
+
631
+ fx.closeChannel(52);
632
+ while (fx.takeMsg()) |_| {}
633
+ }
634
+
635
+ test "a post racing the drain lands after the coalescer clear and still wakes" {
636
+ var fx = DirectFx.init(testing.allocator);
637
+ defer fx.deinit();
638
+ fx.executor = .fake;
639
+ WakeCounter.reset();
640
+ const services: platform_mod.PlatformServices = .{ .wake_fn = WakeCounter.wake };
641
+ fx.bindServices(&services);
642
+
643
+ const handle = fx.openChannel(.{ .key = 53, .on_event = DirectFx.channelMsg(.event) });
644
+ try testing.expectEqual(PostResult.accepted, handle.post("before the pass"));
645
+ try testing.expectEqual(@as(usize, 1), WakeCounter.calls);
646
+
647
+ // The pass boundary clears the latch BEFORE snapshotting the post
648
+ // order (`drainBoundary`). A post landing after the boundary — the
649
+ // closest deterministic stand-in for one racing the clear/snapshot
650
+ // window, which has no injectable seam between its two lines —
651
+ // must observe the cleared latch and land a FRESH wake, because
652
+ // this pass's snapshot excludes it. Were the clear ordered after
653
+ // the snapshot instead, a racing post would coalesce into a wake
654
+ // this very pass consumes and stall until unrelated traffic.
655
+ var boundary = fx.drainBoundary();
656
+ try testing.expectEqual(PostResult.accepted, handle.post("during the pass"));
657
+ try testing.expectEqual(@as(usize, 2), WakeCounter.calls);
658
+
659
+ // The pass delivers only the pre-boundary post...
660
+ const first = fx.takeMsgWithin(&boundary) orelse return error.TestExpectedMsg;
661
+ try testing.expectEqualStrings("before the pass", first.event.bytes);
662
+ try testing.expectEqual(@as(?DirectMsg, null), fx.takeMsgWithin(&boundary));
663
+
664
+ // ...and the racing post's fresh wake has a pass of its own.
665
+ var next = fx.drainBoundary();
666
+ const second = fx.takeMsgWithin(&next) orelse return error.TestExpectedMsg;
667
+ try testing.expectEqualStrings("during the pass", second.event.bytes);
668
+
669
+ fx.closeChannel(53);
670
+ while (fx.takeMsg()) |_| {}
671
+ }
672
+
673
+ test "a bare-takeMsg drain to empty releases the coalescer: the next accepted post wakes" {
674
+ var fx = DirectFx.init(testing.allocator);
675
+ defer fx.deinit();
676
+ fx.executor = .fake;
677
+ WakeCounter.reset();
678
+ const services: platform_mod.PlatformServices = .{ .wake_fn = WakeCounter.wake };
679
+ fx.bindServices(&services);
680
+
681
+ const handle = fx.openChannel(.{ .key = 65, .on_event = DirectFx.channelMsg(.event) });
682
+ try testing.expectEqual(PostResult.accepted, handle.post("first"));
683
+ try testing.expectEqual(@as(usize, 1), WakeCounter.calls);
684
+
685
+ // The public bare-takeMsg drain — no `drainBoundary` anywhere: the
686
+ // caller loops to empty, exactly as documented. The sweep that
687
+ // observes the staged queue empty must release the latch, because
688
+ // no pass boundary ever will on this path.
689
+ while (fx.takeMsg()) |_| {}
690
+
691
+ // The stranded-event regression: pre-clear, this accepted post saw
692
+ // the stale latch and never woke — the event sat staged until
693
+ // unrelated traffic. The observation seam is the host wake count
694
+ // (`WakeCounter` stands where the null platform's pendingWakeCount
695
+ // stands): a NEW wake must be issued, and the event must deliver.
696
+ try testing.expectEqual(PostResult.accepted, handle.post("second"));
697
+ try testing.expectEqual(@as(usize, 2), WakeCounter.calls);
698
+ _ = try expectData(&fx, 65, "second");
699
+
700
+ fx.closeChannel(65);
701
+ while (fx.takeMsg()) |_| {}
702
+ }
703
+
704
+ const StrandProducer = struct {
705
+ const total: usize = 100;
706
+
707
+ fn run(handle: effects_mod.ChannelHandle, stop: *std.atomic.Value(bool)) void {
708
+ var accepted: usize = 0;
709
+ while (accepted < total and !stop.load(.acquire)) {
710
+ switch (handle.post("strand probe")) {
711
+ .accepted => accepted += 1,
712
+ // Transient back-pressure: the documented producer
713
+ // pattern keeps going; the consumer's drain relieves it.
714
+ .dropped_full => std.Thread.yield() catch {},
715
+ else => return,
716
+ }
717
+ }
718
+ }
719
+ };
720
+
721
+ test "an event-driven bare-takeMsg consumer never strands an accepted post" {
722
+ // The race the empty-observation clear must win, run for real: a
723
+ // producer thread posts through the coalescer while an
724
+ // EVENT-DRIVEN consumer drains via bare `takeMsg` — it only
725
+ // drains when the wake count moves, exactly like an embedder
726
+ // servicing wake nudges, so a stranded event (an accepted post
727
+ // whose stale-latch check suppressed the wake AFTER the consumer
728
+ // drained to empty) parks the consumer forever. The clear/post
729
+ // race window (between the sweep's latch clear and its re-check)
730
+ // has no injectable seam, so this pins the invariant
731
+ // probabilistically-but-real, the bind/post handshake test's
732
+ // precedent: completion within the bound IS the assertion.
733
+ var fx = DirectFx.init(testing.allocator);
734
+ defer fx.deinit();
735
+ fx.executor = .fake;
736
+ RaceWake.calls.store(0, .seq_cst);
737
+ const services: platform_mod.PlatformServices = .{ .wake_fn = RaceWake.wake };
738
+ fx.bindServices(&services);
739
+
740
+ const handle = fx.openChannel(.{ .key = 66, .on_event = DirectFx.channelMsg(.event) });
741
+ var stop = std.atomic.Value(bool).init(false);
742
+ const producer = try std.Thread.spawn(.{}, StrandProducer.run, .{ handle, &stop });
743
+ defer producer.join();
744
+ defer stop.store(true, .release);
745
+
746
+ var received: usize = 0;
747
+ var wakes_seen: usize = 0;
748
+ var waited_ms: usize = 0;
749
+ while (received < StrandProducer.total) {
750
+ const wakes = RaceWake.calls.load(.seq_cst);
751
+ if (wakes > wakes_seen) {
752
+ wakes_seen = wakes;
753
+ while (fx.takeMsg()) |msg| {
754
+ try testing.expect(msg == .event);
755
+ received += 1;
756
+ }
757
+ continue;
758
+ }
759
+ waited_ms += 1;
760
+ if (waited_ms > 30_000) return error.TestStrandedEvent;
761
+ try std.Io.sleep(std.testing.io, std.Io.Duration.fromMilliseconds(1), .awake);
762
+ }
763
+
764
+ fx.closeChannel(66);
765
+ while (fx.takeMsg()) |_| {}
766
+ }
767
+
768
+ test "a post accepted before services bind is delivered by the bind sweep with no further post" {
769
+ var fx = DirectFx.init(testing.allocator);
770
+ defer fx.deinit();
771
+ fx.executor = .fake;
772
+ WakeCounter.reset();
773
+
774
+ // Open-before-bind is supported: the channel is live and posts are
775
+ // ACCEPTED — but no host services exist to wake, and nothing is
776
+ // latched (a latch with no wake behind it would suppress the real
777
+ // wake later).
778
+ const handle = fx.openChannel(.{ .key = 55, .on_event = DirectFx.channelMsg(.event) });
779
+ try testing.expectEqual(PostResult.accepted, handle.post("early sample"));
780
+ try testing.expectEqual(@as(usize, 0), WakeCounter.calls);
781
+
782
+ // Binding sweeps: the pre-bind staged post gets its one catch-up
783
+ // host wake at bind time, with NO further post. (Pre-sweep, a
784
+ // one-shot producer stranded here forever: `.accepted` with no
785
+ // wake, and nothing else ever nudging the host.)
786
+ const services: platform_mod.PlatformServices = .{ .wake_fn = WakeCounter.wake };
787
+ fx.bindServices(&services);
788
+ try testing.expectEqual(@as(usize, 1), WakeCounter.calls);
789
+
790
+ // The wake's drain pass delivers the pre-bind post.
791
+ var boundary = fx.drainBoundary();
792
+ const msg = fx.takeMsgWithin(&boundary) orelse return error.TestExpectedMsg;
793
+ try testing.expectEqualStrings("early sample", msg.event.bytes);
794
+ try testing.expectEqual(@as(?DirectMsg, null), fx.takeMsgWithin(&boundary));
795
+
796
+ // And the post-bind path is the ordinary latched wake.
797
+ try testing.expectEqual(PostResult.accepted, handle.post("late sample"));
798
+ try testing.expectEqual(@as(usize, 2), WakeCounter.calls);
799
+ fx.closeChannel(55);
800
+ while (fx.takeMsg()) |_| {}
801
+ }
802
+
803
+ test "an idle bind sweeps nothing" {
804
+ var fx = DirectFx.init(testing.allocator);
805
+ defer fx.deinit();
806
+ fx.executor = .fake;
807
+ WakeCounter.reset();
808
+
809
+ // A channel is open but nothing is staged: binding must NOT wake —
810
+ // the sweep answers staged work, not open occupancies, so an idle
811
+ // app pays no spurious host-queue entry at startup.
812
+ _ = fx.openChannel(.{ .key = 56, .on_event = DirectFx.channelMsg(.event) });
813
+ const services: platform_mod.PlatformServices = .{ .wake_fn = WakeCounter.wake };
814
+ fx.bindServices(&services);
815
+ try testing.expectEqual(@as(usize, 0), WakeCounter.calls);
816
+ fx.closeChannel(56);
817
+ while (fx.takeMsg()) |_| {}
818
+ }
819
+
820
+ /// An atomic wake counter plus a start gate for the concurrent
821
+ /// bind/post handshake test below: the wake hook runs on whichever
822
+ /// thread posted, so the counter must be an atomic, not `WakeCounter`'s
823
+ /// loop-thread-only plain var.
824
+ const RaceWake = struct {
825
+ var calls: std.atomic.Value(usize) = std.atomic.Value(usize).init(0);
826
+
827
+ fn wake(context: ?*anyopaque) anyerror!void {
828
+ _ = context;
829
+ _ = calls.fetchAdd(1, .seq_cst);
830
+ }
831
+ };
832
+
833
+ const RacePoster = struct {
834
+ fn run(handle: effects_mod.ChannelHandle, start: *std.atomic.Value(bool)) void {
835
+ while (!start.load(.acquire)) std.atomic.spinLoopHint();
836
+ _ = handle.post("racing sample");
837
+ }
838
+ };
839
+
840
+ test "a post racing bindServices is never stranded: one side always wakes" {
841
+ // The bind/post handshake is a store-buffer (Dekker) pairing over
842
+ // two atomics: the binder stores `wake_services` then loads the
843
+ // pending count (`hasPending`), while a poster increments the
844
+ // pending count then loads `wake_services`. Unless all four
845
+ // operations are seq_cst, both sides can read the stale value —
846
+ // the poster sees no services (wakes nobody), the binder sees no
847
+ // pending work (sweeps nothing) — and an ACCEPTED post strands
848
+ // until unrelated traffic. This test is probabilistic-but-real
849
+ // for that race class: it aligns one post against one bind per
850
+ // iteration and asserts the handshake's invariant — at least one
851
+ // side always acts, so a wake is observed and the post drains.
852
+ // A bounded iteration count keeps the suite fast; a regression
853
+ // here may pass on hardware/toolchains where the reorder happens
854
+ // not to bite, but the seq_cst repair is what the memory model
855
+ // itself guarantees.
856
+ var iteration: usize = 0;
857
+ while (iteration < 300) : (iteration += 1) {
858
+ var fx = DirectFx.init(testing.allocator);
859
+ defer fx.deinit();
860
+ fx.executor = .fake;
861
+ RaceWake.calls.store(0, .seq_cst);
862
+
863
+ const handle = fx.openChannel(.{ .key = 61, .on_event = DirectFx.channelMsg(.event) });
864
+ const services: platform_mod.PlatformServices = .{ .wake_fn = RaceWake.wake };
865
+
866
+ var start = std.atomic.Value(bool).init(false);
867
+ const poster = try std.Thread.spawn(.{}, RacePoster.run, .{ handle, &start });
868
+ start.store(true, .release);
869
+ fx.bindServices(&services);
870
+ poster.join();
871
+
872
+ // The post was accepted (open channel, empty stage), so it
873
+ // must never strand: either the poster observed the published
874
+ // services and latched its own wake, or the binder observed
875
+ // the staged post and swept — one host wake either way.
876
+ try testing.expect(RaceWake.calls.load(.seq_cst) >= 1);
877
+ // And the staged work is drainable at that wake.
878
+ _ = try expectData(&fx, 61, "racing sample");
879
+ fx.closeChannel(61);
880
+ while (fx.takeMsg()) |_| {}
881
+ }
882
+ }
883
+
884
+ /// A wake hook that posts back into the channel that woke it — the
885
+ /// reentrant shape a well-behaved hook avoids (enqueue-only), turned
886
+ /// into a regression gate: pre-split this deadlocked on the staging
887
+ /// mutex, and the coalescer's pre-latched flag is what lets the inner
888
+ /// post coalesce lock-free and return — without it, the inner post
889
+ /// would find the (now free, see `ChannelWake`) wake mutex and
890
+ /// re-enter the hook unboundedly.
891
+ const ReentrantPoster = struct {
892
+ var handle: ?effects_mod.ChannelHandle = null;
893
+ var inner_result: ?PostResult = null;
894
+
895
+ fn reset() void {
896
+ handle = null;
897
+ inner_result = null;
898
+ }
899
+
900
+ fn wake(context: ?*anyopaque) anyerror!void {
901
+ _ = context;
902
+ const h = handle orelse return;
903
+ if (inner_result != null) return;
904
+ inner_result = h.post("reentrant");
905
+ }
906
+ };
907
+
908
+ test "a wake hook that posts back into the same channel coalesces instead of deadlocking" {
909
+ var fx = DirectFx.init(testing.allocator);
910
+ defer fx.deinit();
911
+ fx.executor = .fake;
912
+ ReentrantPoster.reset();
913
+ defer ReentrantPoster.reset();
914
+ const services: platform_mod.PlatformServices = .{ .wake_fn = ReentrantPoster.wake };
915
+ fx.bindServices(&services);
916
+
917
+ const handle = fx.openChannel(.{ .key = 54, .on_event = DirectFx.channelMsg(.event) });
918
+ ReentrantPoster.handle = handle;
919
+
920
+ // The outer post latches the wake, then runs the hook; the hook's
921
+ // inner post stages (the staging mutex is free — the lock-order
922
+ // invariant) and coalesces on the latched flag without touching
923
+ // the wake mutex the outer post still holds.
924
+ try testing.expectEqual(PostResult.accepted, handle.post("outer"));
925
+ try testing.expectEqual(@as(?PostResult, .accepted), ReentrantPoster.inner_result);
926
+
927
+ // Both entries ride the one latched wake, in post order.
928
+ ReentrantPoster.handle = null;
929
+ _ = try expectData(&fx, 54, "outer");
930
+ _ = try expectData(&fx, 54, "reentrant");
931
+ fx.closeChannel(54);
932
+ while (fx.takeMsg()) |_| {}
933
+ }
934
+
935
+ /// VIOLATOR-CONTAINMENT PIN, not a supported-usage example. A wake
936
+ /// hook that takes the exact locks the LOOP THREAD takes at every pass
937
+ /// boundary: `drainBoundary` acquires each channel's wake mutex to
938
+ /// clear the coalescer. A hook that synchronizes with the loop this
939
+ /// way VIOLATES the wake contract (`PlatformServices.wake_fn` is
940
+ /// bounded and enqueue-only), but the contract is unenforceable, so
941
+ /// the runtime must survive its own half: the host call runs with the
942
+ /// wake mutex FREE, and a violator hangs only in its own stack — never
943
+ /// in the runtime's lock graph. When the call ran under the mutex,
944
+ /// this hook deadlocked (`drainBoundary` spinning on the wake mutex
945
+ /// the post still held); with the in-flight fence it completes. That
946
+ /// containment is the behavior pinned here.
947
+ const BoundaryTakingWake = struct {
948
+ var fx_under_test: ?*DirectFx = null;
949
+ var shared_under_probe: ?*effects_mod.ChannelShared = null;
950
+ var wake_mutex_free_during_wake: ?bool = null;
951
+ var boundary_taken: bool = false;
952
+
953
+ fn reset() void {
954
+ fx_under_test = null;
955
+ shared_under_probe = null;
956
+ wake_mutex_free_during_wake = null;
957
+ boundary_taken = false;
958
+ }
959
+
960
+ fn wake(context: ?*anyopaque) anyerror!void {
961
+ _ = context;
962
+ // Pin the invariant directly: the wake mutex is free while the
963
+ // hook runs (the disarm fence is the in-flight count, never
964
+ // lock tenure).
965
+ if (shared_under_probe) |shared| {
966
+ const free = shared.wake.mutex.inner.tryLock();
967
+ if (free) shared.wake.mutex.inner.unlock();
968
+ wake_mutex_free_during_wake = free;
969
+ }
970
+ // And prove it end to end: take the loop's own pass boundary —
971
+ // the same wake-mutex acquisition drainBoundary performs —
972
+ // from inside the host call.
973
+ const fx = fx_under_test orelse return;
974
+ if (boundary_taken) return;
975
+ boundary_taken = true;
976
+ _ = fx.drainBoundary();
977
+ }
978
+ };
979
+
980
+ test "violator containment: a wake hook that takes the drain's pass boundary cannot deadlock the runtime's lock graph" {
981
+ var fx = DirectFx.init(testing.allocator);
982
+ defer fx.deinit();
983
+ fx.executor = .fake;
984
+ BoundaryTakingWake.reset();
985
+ defer BoundaryTakingWake.reset();
986
+ const services: platform_mod.PlatformServices = .{ .wake_fn = BoundaryTakingWake.wake };
987
+ fx.bindServices(&services);
988
+
989
+ const handle = fx.openChannel(.{ .key = 57, .on_event = DirectFx.channelMsg(.event) });
990
+ BoundaryTakingWake.fx_under_test = &fx;
991
+ BoundaryTakingWake.shared_under_probe = handle.shared;
992
+
993
+ // Deadlocked here pre-fix: the post held the wake mutex through
994
+ // the hook while the hook's drainBoundary spun on the same mutex.
995
+ try testing.expectEqual(PostResult.accepted, handle.post("boundary probe"));
996
+ try testing.expect(BoundaryTakingWake.boundary_taken);
997
+ try testing.expectEqual(@as(?bool, true), BoundaryTakingWake.wake_mutex_free_during_wake);
998
+
999
+ // The hook's boundary cleared the coalescer, so the staged entry
1000
+ // still delivers and a later post latches a fresh wake of its own.
1001
+ BoundaryTakingWake.fx_under_test = null;
1002
+ BoundaryTakingWake.shared_under_probe = null;
1003
+ _ = try expectData(&fx, 57, "boundary probe");
1004
+ fx.closeChannel(57);
1005
+ while (fx.takeMsg()) |_| {}
1006
+ }
1007
+
1008
+ /// VIOLATOR-CONTAINMENT PIN, not a supported-usage example. A wake
1009
+ /// hook that SYNCHRONOUSLY MARSHALS to the loop thread — the
1010
+ /// dispatch-sync shape (macOS `dispatch_sync` onto the main queue,
1011
+ /// Win32 `SendMessage`): the hook returns only after the loop thread
1012
+ /// has serviced the marshaled dispatch. This VIOLATES the wake
1013
+ /// contract (`PlatformServices.wake_fn` is bounded and enqueue-only —
1014
+ /// the first-party hosts all enqueue), but the contract is
1015
+ /// unenforceable, and this is the exact shape that turned the close
1016
+ /// path's blocking in-flight wait into a deadlock of the runtime's own
1017
+ /// making: the marshaled dispatch delivers the channel message, the
1018
+ /// message's handler calls `closeChannel`, and a close that waits for
1019
+ /// `in_flight == 0` waits on a hook that waits on the loop. The
1020
+ /// runtime's half of the containment — pinned here — is that the close
1021
+ /// path REVOKES the binding (non-blocking) and lets the in-flight call
1022
+ /// finish against the process-lifetime header on its own time; only
1023
+ /// teardown quiesces, bounded (see `quiesceChannelWake`). The violator
1024
+ /// hangs nothing but its own posting thread.
1025
+ const SyncMarshalWake = struct {
1026
+ var loop_thread: std.Thread.Id = 0;
1027
+ var marshal_requested: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);
1028
+ var dispatch_done: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);
1029
+
1030
+ fn reset() void {
1031
+ loop_thread = 0;
1032
+ marshal_requested.store(false, .seq_cst);
1033
+ dispatch_done.store(false, .seq_cst);
1034
+ }
1035
+
1036
+ fn wake(context: ?*anyopaque) anyerror!void {
1037
+ _ = context;
1038
+ // A wake issued ON the loop thread dispatches inline — the
1039
+ // real synchronous-marshal primitives behave the same way
1040
+ // (dispatch_sync from the target queue would deadlock, so a
1041
+ // real hook checks; `SendMessage` to the calling thread's own
1042
+ // window runs the procedure directly). Only a producer-thread
1043
+ // wake marshals and blocks.
1044
+ if (std.Thread.getCurrentId() == loop_thread) return;
1045
+ marshal_requested.store(true, .seq_cst);
1046
+ // The synchronous marshal: block until the loop thread reports
1047
+ // the dispatched handler ran to completion.
1048
+ while (!dispatch_done.load(.seq_cst)) std.atomic.spinLoopHint();
1049
+ }
1050
+ };
1051
+
1052
+ const SyncMarshalPoster = struct {
1053
+ fn run(handle: effects_mod.ChannelHandle, result: *PostResult) void {
1054
+ result.* = handle.post("marshal me");
1055
+ }
1056
+ };
1057
+
1058
+ test "violator containment: a synchronous-marshal wake whose dispatched handler closes the channel completes instead of deadlocking" {
1059
+ var fx = DirectFx.init(testing.allocator);
1060
+ defer fx.deinit();
1061
+ fx.executor = .fake;
1062
+ SyncMarshalWake.reset();
1063
+ defer SyncMarshalWake.reset();
1064
+ SyncMarshalWake.loop_thread = std.Thread.getCurrentId();
1065
+ const services: platform_mod.PlatformServices = .{ .wake_fn = SyncMarshalWake.wake };
1066
+ fx.bindServices(&services);
1067
+
1068
+ const handle = fx.openChannel(.{ .key = 58, .on_event = DirectFx.channelMsg(.event) });
1069
+ var post_result: PostResult = .closed;
1070
+ const producer = try std.Thread.spawn(.{}, SyncMarshalPoster.run, .{ handle, &post_result });
1071
+ // An error return must still release the marshal and collect the
1072
+ // producer, or the blocked thread would hang the suite behind the
1073
+ // failure.
1074
+ var joined = false;
1075
+ errdefer SyncMarshalWake.dispatch_done.store(true, .seq_cst);
1076
+ defer if (!joined) producer.join();
1077
+
1078
+ // Wait (bounded — fail loud, never hang the suite) for the
1079
+ // producer to reach the inside of `wake_fn`: from here on it is
1080
+ // blocked until the loop services its marshal, with the wake's
1081
+ // in-flight count held at one.
1082
+ var waited_ms: usize = 0;
1083
+ while (!SyncMarshalWake.marshal_requested.load(.seq_cst)) : (waited_ms += 1) {
1084
+ if (waited_ms > 10_000) return error.TestExpectedMarshal;
1085
+ try std.Io.sleep(std.testing.io, std.Io.Duration.fromMilliseconds(1), .awake);
1086
+ }
1087
+
1088
+ // Service the marshaled dispatch on the loop thread: deliver the
1089
+ // channel message, and — as the app's update — close the channel.
1090
+ // Pre-split this deadlocked HERE: `closeChannel`'s disarm spun on
1091
+ // `in_flight == 0` while the producer spun inside `wake_fn`
1092
+ // waiting for this very dispatch to complete.
1093
+ _ = try expectData(&fx, 58, "marshal me");
1094
+ fx.closeChannel(58);
1095
+ try testing.expectEqual(PostResult.closed, handle.post("after close"));
1096
+ SyncMarshalWake.dispatch_done.store(true, .seq_cst);
1097
+ producer.join();
1098
+ joined = true;
1099
+ try testing.expectEqual(PostResult.accepted, post_result);
1100
+
1101
+ // The close delivers its `.closed` terminal exactly once.
1102
+ const closed = fx.takeMsg() orelse return error.TestExpectedMsg;
1103
+ try testing.expectEqual(effects_mod.EffectChannelEventKind.closed, closed.event.kind);
1104
+ try testing.expectEqual(@as(?DirectMsg, null), fx.takeMsg());
1105
+ }
1106
+
1107
+ /// A wake hook held OPEN mid-call while the loop closes, drains, and
1108
+ /// REOPENS the channel — the stale in-flight call the revoke split
1109
+ /// leaves behind on purpose (a hook that blocks like this violates the
1110
+ /// enqueue-only wake contract; this pin is the containment's
1111
+ /// generation-safety half). The gated call FAILS once released, so
1112
+ /// its post-call failure unlatch runs against a dead generation: the
1113
+ /// gate in `requestHostWake` must keep it from clearing the fresh
1114
+ /// occupancy's latched wake, and its decrement must land safely in the
1115
+ /// process-lifetime header.
1116
+ const StaleWakeCall = struct {
1117
+ var loop_thread: std.Thread.Id = 0;
1118
+ var gate_armed: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);
1119
+ var blocked: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);
1120
+ var release: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);
1121
+
1122
+ fn reset() void {
1123
+ loop_thread = 0;
1124
+ gate_armed.store(false, .seq_cst);
1125
+ blocked.store(false, .seq_cst);
1126
+ release.store(false, .seq_cst);
1127
+ }
1128
+
1129
+ fn wake(context: ?*anyopaque) anyerror!void {
1130
+ _ = context;
1131
+ if (std.Thread.getCurrentId() == loop_thread) return;
1132
+ if (!gate_armed.swap(false, .seq_cst)) return;
1133
+ blocked.store(true, .seq_cst);
1134
+ while (!release.load(.seq_cst)) std.atomic.spinLoopHint();
1135
+ return error.WakeRefused;
1136
+ }
1137
+ };
1138
+
1139
+ test "a stale in-flight wake call outliving close and reopen cannot unlatch the fresh occupancy" {
1140
+ var fx = DirectFx.init(testing.allocator);
1141
+ defer fx.deinit();
1142
+ fx.executor = .fake;
1143
+ StaleWakeCall.reset();
1144
+ defer StaleWakeCall.reset();
1145
+ StaleWakeCall.loop_thread = std.Thread.getCurrentId();
1146
+ const services: platform_mod.PlatformServices = .{ .wake_fn = StaleWakeCall.wake };
1147
+ fx.bindServices(&services);
1148
+
1149
+ const stale = fx.openChannel(.{ .key = 62, .on_event = DirectFx.channelMsg(.event) });
1150
+ StaleWakeCall.gate_armed.store(true, .seq_cst);
1151
+ var post_result: PostResult = .closed;
1152
+ const producer = try std.Thread.spawn(.{}, SyncMarshalPoster.run, .{ stale, &post_result });
1153
+ var joined = false;
1154
+ errdefer StaleWakeCall.release.store(true, .seq_cst);
1155
+ defer if (!joined) producer.join();
1156
+
1157
+ var waited_ms: usize = 0;
1158
+ while (!StaleWakeCall.blocked.load(.seq_cst)) : (waited_ms += 1) {
1159
+ if (waited_ms > 10_000) return error.TestExpectedBlockedWake;
1160
+ try std.Io.sleep(std.testing.io, std.Io.Duration.fromMilliseconds(1), .awake);
1161
+ }
1162
+
1163
+ // Close and fully retire the first occupancy WHILE the stale call
1164
+ // is still inside the hook (revoke is non-blocking), then reopen
1165
+ // the same key: a fresh generation on the same process-lifetime
1166
+ // header.
1167
+ fx.closeChannel(62);
1168
+ _ = try expectData(&fx, 62, "marshal me");
1169
+ const closed = fx.takeMsg() orelse return error.TestExpectedMsg;
1170
+ try testing.expectEqual(effects_mod.EffectChannelEventKind.closed, closed.event.kind);
1171
+ const fresh = fx.openChannel(.{ .key = 62, .on_event = DirectFx.channelMsg(.event) });
1172
+ try testing.expect(fresh.shared != null);
1173
+
1174
+ // The fresh occupancy latches its own wake (the loop-thread call
1175
+ // dispatches inline and SUCCEEDS, so the latch stays set).
1176
+ try testing.expectEqual(PostResult.accepted, fresh.post("fresh"));
1177
+ try testing.expect(fresh.shared.?.wake.pending.load(.seq_cst));
1178
+
1179
+ // Release the stale call: it fails, and its failure unlatch runs
1180
+ // with the dead generation — the gate must refuse it. The
1181
+ // decrement lands in the process-lifetime header either way.
1182
+ StaleWakeCall.release.store(true, .seq_cst);
1183
+ producer.join();
1184
+ joined = true;
1185
+ try testing.expectEqual(PostResult.accepted, post_result);
1186
+ try testing.expect(fresh.shared.?.wake.pending.load(.seq_cst));
1187
+
1188
+ // The fresh occupancy's staged post is untouched.
1189
+ _ = try expectData(&fx, 62, "fresh");
1190
+ fx.closeChannel(62);
1191
+ while (fx.takeMsg()) |_| {}
1192
+ }
1193
+
1194
+ /// A wake hook that dawdles inside the call so teardown's quiesce has
1195
+ /// something real to wait out: enters, sleeps, marks itself returned.
1196
+ const SlowTeardownWake = struct {
1197
+ var loop_thread: std.Thread.Id = 0;
1198
+ var entered: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);
1199
+ var returned: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);
1200
+
1201
+ fn reset() void {
1202
+ loop_thread = 0;
1203
+ entered.store(false, .seq_cst);
1204
+ returned.store(false, .seq_cst);
1205
+ }
1206
+
1207
+ fn wake(context: ?*anyopaque) anyerror!void {
1208
+ _ = context;
1209
+ if (std.Thread.getCurrentId() == loop_thread) return;
1210
+ entered.store(true, .seq_cst);
1211
+ try std.Io.sleep(std.testing.io, std.Io.Duration.fromMilliseconds(100), .awake);
1212
+ returned.store(true, .seq_cst);
1213
+ }
1214
+ };
1215
+
1216
+ test "teardown quiesces an in-flight wake call before the services binding dies" {
1217
+ var fx = DirectFx.init(testing.allocator);
1218
+ fx.executor = .fake;
1219
+ SlowTeardownWake.reset();
1220
+ defer SlowTeardownWake.reset();
1221
+ SlowTeardownWake.loop_thread = std.Thread.getCurrentId();
1222
+ const services: platform_mod.PlatformServices = .{ .wake_fn = SlowTeardownWake.wake };
1223
+ fx.bindServices(&services);
1224
+
1225
+ const handle = fx.openChannel(.{ .key = 63, .on_event = DirectFx.channelMsg(.event) });
1226
+ var post_result: PostResult = .closed;
1227
+ const producer = try std.Thread.spawn(.{}, SyncMarshalPoster.run, .{ handle, &post_result });
1228
+ defer producer.join();
1229
+
1230
+ var waited_ms: usize = 0;
1231
+ while (!SlowTeardownWake.entered.load(.seq_cst)) : (waited_ms += 1) {
1232
+ if (waited_ms > 10_000) return error.TestExpectedWakeEntry;
1233
+ try std.Io.sleep(std.testing.io, std.Io.Duration.fromMilliseconds(1), .awake);
1234
+ }
1235
+
1236
+ // Teardown while the producer is inside `wake_fn`: deinit severs
1237
+ // the services binding, so its channel sweep must WAIT for the
1238
+ // in-flight call — a revoke-only teardown could tear the platform
1239
+ // down under a hook still executing inside it. The quiesce
1240
+ // returning cleanly (no abandon counted) proves the wait covered
1241
+ // the whole call.
1242
+ fx.deinit();
1243
+ try testing.expect(SlowTeardownWake.returned.load(.seq_cst));
1244
+ try testing.expectEqual(@as(u32, 0), fx.abandoned_channel_wakes);
1245
+ }
1246
+
1247
+ /// A wake hook stuck PAST teardown's deadline — the shape quiesce
1248
+ /// cannot wait out (a synchronous marshal against the stopping loop
1249
+ /// never returns; a wake-contract violation, which is the only way the
1250
+ /// deadline is ever met), pinned with a test-released gate instead.
1251
+ const StuckTeardownWake = struct {
1252
+ var loop_thread: std.Thread.Id = 0;
1253
+ var entered: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);
1254
+ var release: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);
1255
+
1256
+ fn reset() void {
1257
+ loop_thread = 0;
1258
+ entered.store(false, .seq_cst);
1259
+ release.store(false, .seq_cst);
1260
+ }
1261
+
1262
+ fn wake(context: ?*anyopaque) anyerror!void {
1263
+ _ = context;
1264
+ if (std.Thread.getCurrentId() == loop_thread) return;
1265
+ entered.store(true, .seq_cst);
1266
+ while (!release.load(.seq_cst)) std.atomic.spinLoopHint();
1267
+ }
1268
+ };
1269
+
1270
+ test "teardown abandons a wake call still stuck at the deadline and the stale call stays safe" {
1271
+ var fx = DirectFx.init(testing.allocator);
1272
+ fx.executor = .fake;
1273
+ // A tiny injected budget so the abandon safety net is reached
1274
+ // deterministically (the real default is generous; see
1275
+ // `default_channel_wake_join_deadline_ms`).
1276
+ fx.channel_wake_join_deadline_ms = 50;
1277
+ StuckTeardownWake.reset();
1278
+ defer StuckTeardownWake.reset();
1279
+ StuckTeardownWake.loop_thread = std.Thread.getCurrentId();
1280
+ // A real (null) platform behind the services table, with its
1281
+ // conforming wake REPLACED by the stuck hook: the abandon-report
1282
+ // seam (`note_channel_wake_abandoned_fn`) stays the platform's own,
1283
+ // so the test observes the platform half of the abandon — the
1284
+ // destroy gate — through the null platform's reference model.
1285
+ const null_platform = try testing.allocator.create(platform_mod.NullPlatform);
1286
+ defer testing.allocator.destroy(null_platform);
1287
+ null_platform.* = platform_mod.NullPlatform.init(.{});
1288
+ var host_platform = null_platform.platform();
1289
+ host_platform.services.wake_fn = StuckTeardownWake.wake;
1290
+ fx.bindServices(&host_platform.services);
1291
+
1292
+ const handle = fx.openChannel(.{ .key = 64, .on_event = DirectFx.channelMsg(.event) });
1293
+ var post_result: PostResult = .closed;
1294
+ const producer = try std.Thread.spawn(.{}, SyncMarshalPoster.run, .{ handle, &post_result });
1295
+ var joined = false;
1296
+ errdefer StuckTeardownWake.release.store(true, .seq_cst);
1297
+ defer if (!joined) producer.join();
1298
+
1299
+ var waited_ms: usize = 0;
1300
+ while (!StuckTeardownWake.entered.load(.seq_cst)) : (waited_ms += 1) {
1301
+ if (waited_ms > 10_000) return error.TestExpectedWakeEntry;
1302
+ try std.Io.sleep(std.testing.io, std.Io.Duration.fromMilliseconds(1), .awake);
1303
+ }
1304
+
1305
+ // Teardown cannot wait this one out — deinit must return within
1306
+ // its bounded budget, warn, and count the abandon rather than
1307
+ // hang the app's exit forever behind a hook nobody will release.
1308
+ fx.deinit();
1309
+ try testing.expectEqual(@as(u32, 1), fx.abandoned_channel_wakes);
1310
+
1311
+ // The abandon was reported to the platform, synchronously, while
1312
+ // it was alive: the latch is set...
1313
+ try testing.expect(null_platform.channel_wake_abandoned.load(.seq_cst));
1314
+ // ...and the platform-destroy path is SUPPRESSED — deinit consults
1315
+ // the latch, skips destruction, and leaks the host, process-lived,
1316
+ // so the stale call still inside `wake_fn` can never execute into
1317
+ // freed host state (the real hosts' destroy gate, observed through
1318
+ // the null platform's reference model).
1319
+ null_platform.deinit();
1320
+ try testing.expect(!null_platform.destroyed);
1321
+
1322
+ // The abandoned call unblocks LATER and finishes against the
1323
+ // process-lifetime header — a safe decrement, never a
1324
+ // use-after-free — and the post it served still answers honestly.
1325
+ StuckTeardownWake.release.store(true, .seq_cst);
1326
+ producer.join();
1327
+ joined = true;
1328
+ try testing.expectEqual(PostResult.accepted, post_result);
1329
+ try testing.expectEqual(PostResult.closed, handle.post("after teardown"));
1330
+ }
1331
+
1332
+ test "a conforming enqueue-only wake at teardown quiesces fast and platform destruction proceeds" {
1333
+ // The two-sided contract's healthy half, pinned as the abandon
1334
+ // test's non-regression twin: with the platform's OWN wake (the
1335
+ // null platform's atomic counter — bounded, enqueue-only, the
1336
+ // contract at `PlatformServices.wake_fn`), teardown's quiesce
1337
+ // covers every in-flight call without ever nearing the deadline,
1338
+ // nothing is abandoned, and the platform destroys normally.
1339
+ var fx = DirectFx.init(testing.allocator);
1340
+ fx.executor = .fake;
1341
+ const null_platform = try testing.allocator.create(platform_mod.NullPlatform);
1342
+ defer testing.allocator.destroy(null_platform);
1343
+ null_platform.* = platform_mod.NullPlatform.init(.{});
1344
+ const host_platform = null_platform.platform();
1345
+ fx.bindServices(&host_platform.services);
1346
+
1347
+ const handle = fx.openChannel(.{ .key = 65, .on_event = DirectFx.channelMsg(.event) });
1348
+ try testing.expectEqual(PostResult.accepted, handle.post("healthy"));
1349
+ // The conforming wake already returned: it enqueued (the null
1350
+ // platform counts) and nothing lingers inside the hook.
1351
+ try testing.expect(null_platform.wake_count.load(.acquire) >= 1);
1352
+
1353
+ fx.deinit();
1354
+ try testing.expectEqual(@as(u32, 0), fx.abandoned_channel_wakes);
1355
+
1356
+ // No abandon, no latch, no leak: destruction proceeds.
1357
+ try testing.expect(!null_platform.channel_wake_abandoned.load(.seq_cst));
1358
+ null_platform.deinit();
1359
+ try testing.expect(null_platform.destroyed);
1360
+ try testing.expectEqual(PostResult.closed, handle.post("after teardown"));
1361
+ }
1362
+
1363
+ /// A wake hook stuck past the deadline whose FIRST context dereference
1364
+ /// happens only after it is released — which the test arranges to be
1365
+ /// strictly after teardown completed, the platform destroy path ran,
1366
+ /// and the stack frame that owned the bound services value unwound.
1367
+ /// The abandon doctrine's whole claim ("may execute at any later
1368
+ /// time") is that this dereference reads valid memory; the two earlier
1369
+ /// abandon tests could not see it because their hooks ignore context
1370
+ /// and rejoin while every owner is still alive.
1371
+ const AfterTeardownDerefWake = struct {
1372
+ var loop_thread: std.Thread.Id = 0;
1373
+ var entered: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);
1374
+ var release: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);
1375
+ /// What the resumed hook read through its context AFTER teardown:
1376
+ /// the leaked platform's latched abandon flag. Valid (leaked)
1377
+ /// memory reads true; a freed or reused wrapper could read
1378
+ /// anything, so the assertion is on the value, not just on not
1379
+ /// crashing.
1380
+ var observed_latch: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);
1381
+
1382
+ fn reset() void {
1383
+ loop_thread = 0;
1384
+ entered.store(false, .seq_cst);
1385
+ release.store(false, .seq_cst);
1386
+ observed_latch.store(false, .seq_cst);
1387
+ }
1388
+
1389
+ fn wake(context: ?*anyopaque) anyerror!void {
1390
+ if (std.Thread.getCurrentId() == loop_thread) return;
1391
+ entered.store(true, .seq_cst);
1392
+ while (!release.load(.seq_cst)) std.atomic.spinLoopHint();
1393
+ // Resumed after teardown: the one dereference the abandon-leak
1394
+ // doctrine exists to keep valid.
1395
+ const stale_platform: *platform_mod.NullPlatform = @ptrCast(@alignCast(context.?));
1396
+ observed_latch.store(stale_platform.channel_wake_abandoned.load(.seq_cst), .seq_cst);
1397
+ }
1398
+ };
1399
+
1400
+ /// The dying-owner scope for the after-teardown test: the `Platform`
1401
+ /// value whose services table `bindServices` receives lives in THIS
1402
+ /// frame — standing in for the heap Runtime the real runners bind
1403
+ /// against, destroyed right after effects teardown — and the frame
1404
+ /// poisons it (0xAA) before returning, so any pointer into it held
1405
+ /// past this function reads the pattern, never a valid table. Returns
1406
+ /// with teardown complete, the abandon counted, and the stale call
1407
+ /// still parked inside the stuck hook.
1408
+ fn abandonAgainstDyingOwner(
1409
+ fx: *DirectFx,
1410
+ null_platform: *platform_mod.NullPlatform,
1411
+ post_result: *PostResult,
1412
+ handle_out: *effects_mod.ChannelHandle,
1413
+ snapshot_out: **const platform_mod.PlatformServices,
1414
+ ) !std.Thread {
1415
+ var host_platform = null_platform.platform();
1416
+ host_platform.services.wake_fn = AfterTeardownDerefWake.wake;
1417
+ fx.bindServices(&host_platform.services);
1418
+
1419
+ const handle = fx.openChannel(.{ .key = 66, .on_event = DirectFx.channelMsg(.event) });
1420
+ handle_out.* = handle;
1421
+ // The decoupling under test: what the bind generation PUBLISHED to
1422
+ // posting threads (lazily, at this first open) is the snapshot,
1423
+ // never this frame's value.
1424
+ const snapshot = fx.wake_services.load(.seq_cst) orelse return error.TestExpectedSnapshot;
1425
+ try testing.expect(snapshot != &host_platform.services);
1426
+ snapshot_out.* = snapshot;
1427
+ const producer = try std.Thread.spawn(.{}, SyncMarshalPoster.run, .{ handle, post_result });
1428
+ errdefer AfterTeardownDerefWake.release.store(true, .seq_cst);
1429
+ var waited_ms: usize = 0;
1430
+ while (!AfterTeardownDerefWake.entered.load(.seq_cst)) : (waited_ms += 1) {
1431
+ if (waited_ms > 10_000) return error.TestExpectedWakeEntry;
1432
+ try std.Io.sleep(std.testing.io, std.Io.Duration.fromMilliseconds(1), .awake);
1433
+ }
1434
+
1435
+ // Bounded quiesce meets the deadline against the parked hook:
1436
+ // ABANDON, latch, warn — teardown completes while the call is
1437
+ // still inside `wake_fn`.
1438
+ fx.deinit();
1439
+ try testing.expectEqual(@as(u32, 1), fx.abandoned_channel_wakes);
1440
+ // The frame is about to die; poison the services value it owned so
1441
+ // a stale pointer into it reads a deterministic pattern instead of
1442
+ // whatever the dead frame happens to leave behind.
1443
+ @memset(std.mem.asBytes(&host_platform), 0xAA);
1444
+ return producer;
1445
+ }
1446
+
1447
+ test "an abandoned wake call dereferences its context and services snapshot only after teardown and the owning scopes died" {
1448
+ var fx = DirectFx.init(testing.allocator);
1449
+ fx.executor = .fake;
1450
+ fx.channel_wake_join_deadline_ms = 50;
1451
+ AfterTeardownDerefWake.reset();
1452
+ defer AfterTeardownDerefWake.reset();
1453
+ AfterTeardownDerefWake.loop_thread = std.Thread.getCurrentId();
1454
+ // The wrapper through the runners' own lifetime seam: heap-allocated
1455
+ // by `createWithOptions`, retired by `destroy`, the latch-gated free.
1456
+ const null_platform = try platform_mod.NullPlatform.createWithOptions(.{}, .system, .{});
1457
+ var post_result: PostResult = .closed;
1458
+ var handle: effects_mod.ChannelHandle = undefined;
1459
+ var snapshot: *const platform_mod.PlatformServices = undefined;
1460
+ const producer = try abandonAgainstDyingOwner(&fx, null_platform, &post_result, &handle, &snapshot);
1461
+ var joined = false;
1462
+ errdefer AfterTeardownDerefWake.release.store(true, .seq_cst);
1463
+ defer if (!joined) producer.join();
1464
+
1465
+ // Teardown is complete and the frame that owned the bound services
1466
+ // value unwound, poisoned. The runner-shaped destroy runs next:
1467
+ // the abandon latched, so deinit skips destruction AND the storage
1468
+ // free is skipped — wrapper and host leaked, process-lived. The
1469
+ // reads below stay valid BECAUSE of that leak.
1470
+ try testing.expect(null_platform.channel_wake_abandoned.load(.seq_cst));
1471
+ null_platform.destroy();
1472
+ try testing.expect(!null_platform.destroyed);
1473
+
1474
+ // What a poster suspended between capturing the published services
1475
+ // pointer and dereferencing it inside `services.wake()` reads NOW,
1476
+ // after the owner died: the immortal snapshot with the bound table
1477
+ // intact — never the poisoned frame value.
1478
+ try testing.expect(snapshot.wake_fn == AfterTeardownDerefWake.wake);
1479
+ try testing.expect(snapshot.context == @as(?*anyopaque, null_platform));
1480
+
1481
+ // Release the parked call: it resumes and dereferences its CONTEXT
1482
+ // for the first time — strictly after teardown, destroy, and the
1483
+ // owner frame's death — and must read the leaked platform's latched
1484
+ // flag from valid memory. Its post still answers honestly, and the
1485
+ // handle stays a safe `.closed` forever.
1486
+ AfterTeardownDerefWake.release.store(true, .seq_cst);
1487
+ producer.join();
1488
+ joined = true;
1489
+ try testing.expect(AfterTeardownDerefWake.observed_latch.load(.seq_cst));
1490
+ try testing.expectEqual(PostResult.accepted, post_result);
1491
+ try testing.expectEqual(PostResult.closed, handle.post("after the owners died"));
1492
+ }
1493
+
1494
+ /// Records every allocation and free routed through the
1495
+ /// channel-storage seam, by count and by pointer — the snapshot
1496
+ /// lifetime tests' observability: laziness (no allocation while no
1497
+ /// channel opens), the clean-teardown free, and the abandon path's
1498
+ /// deliberate leak. Forwards everything to the page allocator
1499
+ /// (`process_allocator`'s backing), so retire/teardown frees stay
1500
+ /// valid.
1501
+ const TrackingChannelStorageAllocator = struct {
1502
+ backing: std.mem.Allocator = std.heap.page_allocator,
1503
+ alloc_count: usize = 0,
1504
+ freed_ptrs: [16]usize = @splat(0),
1505
+ freed_len: usize = 0,
1506
+
1507
+ const vtable: std.mem.Allocator.VTable = .{
1508
+ .alloc = alloc,
1509
+ .resize = resize,
1510
+ .remap = remap,
1511
+ .free = free,
1512
+ };
1513
+
1514
+ fn allocator(self: *TrackingChannelStorageAllocator) std.mem.Allocator {
1515
+ return .{ .ptr = self, .vtable = &vtable };
1516
+ }
1517
+
1518
+ fn didFree(self: *const TrackingChannelStorageAllocator, ptr: *const anyopaque) bool {
1519
+ for (self.freed_ptrs[0..self.freed_len]) |freed| {
1520
+ if (freed == @intFromPtr(ptr)) return true;
1521
+ }
1522
+ return false;
1523
+ }
1524
+
1525
+ fn alloc(ptr: *anyopaque, len: usize, alignment: std.mem.Alignment, ret_addr: usize) ?[*]u8 {
1526
+ const self: *TrackingChannelStorageAllocator = @ptrCast(@alignCast(ptr));
1527
+ self.alloc_count += 1;
1528
+ return self.backing.vtable.alloc(self.backing.ptr, len, alignment, ret_addr);
1529
+ }
1530
+
1531
+ fn resize(ptr: *anyopaque, memory: []u8, alignment: std.mem.Alignment, new_len: usize, ret_addr: usize) bool {
1532
+ const self: *TrackingChannelStorageAllocator = @ptrCast(@alignCast(ptr));
1533
+ return self.backing.vtable.resize(self.backing.ptr, memory, alignment, new_len, ret_addr);
1534
+ }
1535
+
1536
+ fn remap(ptr: *anyopaque, memory: []u8, alignment: std.mem.Alignment, new_len: usize, ret_addr: usize) ?[*]u8 {
1537
+ const self: *TrackingChannelStorageAllocator = @ptrCast(@alignCast(ptr));
1538
+ return self.backing.vtable.remap(self.backing.ptr, memory, alignment, new_len, ret_addr);
1539
+ }
1540
+
1541
+ fn free(ptr: *anyopaque, memory: []u8, alignment: std.mem.Alignment, ret_addr: usize) void {
1542
+ const self: *TrackingChannelStorageAllocator = @ptrCast(@alignCast(ptr));
1543
+ if (self.freed_len < self.freed_ptrs.len) {
1544
+ self.freed_ptrs[self.freed_len] = @intFromPtr(memory.ptr);
1545
+ self.freed_len += 1;
1546
+ }
1547
+ self.backing.vtable.free(self.backing.ptr, memory, alignment, ret_addr);
1548
+ }
1549
+ };
1550
+
1551
+ test "bindServices with no channels allocates nothing: the services snapshot is lazy" {
1552
+ var tracker: TrackingChannelStorageAllocator = .{};
1553
+ var services: platform_mod.PlatformServices = .{};
1554
+ // Repeated app lifetimes that never open a channel — the test-suite
1555
+ // and embed-host cycling shape: bind + teardown, several rounds.
1556
+ // The process-lived snapshot must never materialize, so repeated
1557
+ // app creation accumulates nothing.
1558
+ var round: usize = 0;
1559
+ while (round < 4) : (round += 1) {
1560
+ var fx = DirectFx.init(testing.allocator);
1561
+ fx.executor = .fake;
1562
+ fx.channel_storage_allocator = tracker.allocator();
1563
+ fx.bindServices(&services);
1564
+ // The bind recorded the loop-thread services pointer but
1565
+ // published no snapshot: no channel wake exists to consume one.
1566
+ try testing.expect(fx.services != null);
1567
+ try testing.expectEqual(@as(?*const platform_mod.PlatformServices, null), fx.wake_services.load(.seq_cst));
1568
+ fx.deinit();
1569
+ }
1570
+ try testing.expectEqual(@as(usize, 0), tracker.alloc_count);
1571
+ }
1572
+
1573
+ test "a channel that opens and tears down cleanly frees the services snapshot" {
1574
+ // The immortality exemption is gone from the healthy path: the
1575
+ // snapshot materializes at the first live open (lazily — the bind
1576
+ // alone published nothing) and a clean teardown, having quiesced
1577
+ // every wake header with zero abandons, proves no poster can still
1578
+ // reach it and frees it.
1579
+ var tracker: TrackingChannelStorageAllocator = .{};
1580
+ var fx = DirectFx.init(testing.allocator);
1581
+ fx.executor = .fake;
1582
+ fx.channel_storage_allocator = tracker.allocator();
1583
+ const null_platform = try testing.allocator.create(platform_mod.NullPlatform);
1584
+ defer testing.allocator.destroy(null_platform);
1585
+ null_platform.* = platform_mod.NullPlatform.init(.{});
1586
+ const host_platform = null_platform.platform();
1587
+
1588
+ fx.bindServices(&host_platform.services);
1589
+ try testing.expectEqual(@as(?*const platform_mod.PlatformServices, null), fx.wake_services.load(.seq_cst));
1590
+ const handle = fx.openChannel(.{ .key = 69, .on_event = DirectFx.channelMsg(.event) });
1591
+ const snapshot = fx.wake_snapshot orelse return error.TestExpectedSnapshot;
1592
+ try testing.expectEqual(@as(?*const platform_mod.PlatformServices, snapshot), fx.wake_services.load(.seq_cst));
1593
+ // The snapshot is live plumbing, not bookkeeping: a producer post
1594
+ // wakes the host through it.
1595
+ try testing.expectEqual(PostResult.accepted, handle.post("healthy"));
1596
+ try testing.expect(null_platform.wake_count.load(.acquire) >= 1);
1597
+ _ = try expectData(&fx, 69, "healthy");
1598
+
1599
+ fx.deinit();
1600
+ try testing.expectEqual(@as(u32, 0), fx.abandoned_channel_wakes);
1601
+ try testing.expect(fx.wake_snapshot == null);
1602
+ try testing.expect(tracker.didFree(snapshot));
1603
+ }
1604
+
1605
+ /// The rebind coverage's two hooks: the FIRST generation's hook parks
1606
+ /// until released — so its teardown ABANDONS the in-flight call, which
1607
+ /// is now the ONE shape that makes a generation's snapshot immortal —
1608
+ /// and the second is a plain conforming counter.
1609
+ const RebindWakes = struct {
1610
+ var loop_thread: std.Thread.Id = 0;
1611
+ var entered: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);
1612
+ var release: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);
1613
+ var second_count: std.atomic.Value(usize) = std.atomic.Value(usize).init(0);
1614
+
1615
+ fn reset() void {
1616
+ loop_thread = 0;
1617
+ entered.store(false, .seq_cst);
1618
+ release.store(false, .seq_cst);
1619
+ second_count.store(0, .seq_cst);
1620
+ }
1621
+
1622
+ fn first(context: ?*anyopaque) anyerror!void {
1623
+ _ = context;
1624
+ if (std.Thread.getCurrentId() == loop_thread) return;
1625
+ entered.store(true, .seq_cst);
1626
+ while (!release.load(.seq_cst)) std.atomic.spinLoopHint();
1627
+ }
1628
+
1629
+ fn second(context: ?*anyopaque) anyerror!void {
1630
+ _ = context;
1631
+ _ = second_count.fetchAdd(1, .seq_cst);
1632
+ }
1633
+ };
1634
+
1635
+ /// First bind generation in a frame that dies, ending in an ABANDON:
1636
+ /// bind, open, park a producer's wake call inside the stuck hook, tear
1637
+ /// down past the deadline (the abandon is what keeps this generation's
1638
+ /// snapshot immortal), then poison the frame-owned services value
1639
+ /// before returning the snapshot pointer the stale call still holds.
1640
+ fn bindFirstGeneration(fx: *DirectFx, post_result: *PostResult) !struct {
1641
+ snapshot: *const platform_mod.PlatformServices,
1642
+ producer: std.Thread,
1643
+ } {
1644
+ var services: platform_mod.PlatformServices = .{ .wake_fn = RebindWakes.first };
1645
+ fx.bindServices(&services);
1646
+ const handle = fx.openChannel(.{ .key = 67, .on_event = DirectFx.channelMsg(.event) });
1647
+ const snapshot = fx.wake_services.load(.seq_cst) orelse return error.TestExpectedSnapshot;
1648
+ try testing.expect(snapshot != &services);
1649
+
1650
+ const producer = try std.Thread.spawn(.{}, SyncMarshalPoster.run, .{ handle, post_result });
1651
+ errdefer RebindWakes.release.store(true, .seq_cst);
1652
+ var waited_ms: usize = 0;
1653
+ while (!RebindWakes.entered.load(.seq_cst)) : (waited_ms += 1) {
1654
+ if (waited_ms > 10_000) return error.TestExpectedWakeEntry;
1655
+ try std.Io.sleep(std.testing.io, std.Io.Duration.fromMilliseconds(1), .awake);
1656
+ }
1657
+
1658
+ fx.deinit();
1659
+ try testing.expectEqual(@as(u32, 1), fx.abandoned_channel_wakes);
1660
+ @memset(std.mem.asBytes(&services), 0xAA);
1661
+ return .{ .snapshot = snapshot, .producer = producer };
1662
+ }
1663
+
1664
+ test "a rebind publishes a fresh snapshot and an abandoned generation's snapshot stays intact for stale calls" {
1665
+ // The one supported rebind shape: `bindServices` after `deinit`
1666
+ // cleared the first binding (mid-life binds are first-bind-sticks
1667
+ // no-ops). Immutable-per-bind is the whole race story — the rebind
1668
+ // never writes the old snapshot, it atomically swaps in a fresh
1669
+ // allocation, so there is no tear window: a stale call that
1670
+ // captured the old pointer before the swap keeps reading the OLD
1671
+ // table intact, for as long as it can exist — which, past the
1672
+ // abandon that generation ended in, is forever — while new posts
1673
+ // route through the new one. Both snapshots stay valid side by
1674
+ // side while the second generation's channels are live, and the
1675
+ // final CLEAN teardown frees exactly the generation it quiesced.
1676
+ var tracker: TrackingChannelStorageAllocator = .{};
1677
+ var fx = DirectFx.init(testing.allocator);
1678
+ fx.executor = .fake;
1679
+ fx.channel_wake_join_deadline_ms = 50;
1680
+ RebindWakes.reset();
1681
+ defer RebindWakes.reset();
1682
+ RebindWakes.loop_thread = std.Thread.getCurrentId();
1683
+ fx.channel_storage_allocator = tracker.allocator();
1684
+
1685
+ var post_result: PostResult = .closed;
1686
+ const first = try bindFirstGeneration(&fx, &post_result);
1687
+ var joined = false;
1688
+ errdefer RebindWakes.release.store(true, .seq_cst);
1689
+ defer if (!joined) first.producer.join();
1690
+ // The abandoned generation's snapshot was NOT freed at its own
1691
+ // teardown: the stale call parked inside the first hook still
1692
+ // holds it.
1693
+ try testing.expect(!tracker.didFree(first.snapshot));
1694
+
1695
+ // REBIND: a second generation against the same Effects value, its
1696
+ // services owned by this (still living) frame. The bind itself
1697
+ // publishes nothing (no channel is open); the snapshot
1698
+ // materializes at the generation's first live open.
1699
+ var second_services: platform_mod.PlatformServices = .{ .wake_fn = RebindWakes.second };
1700
+ fx.bindServices(&second_services);
1701
+ try testing.expectEqual(@as(?*const platform_mod.PlatformServices, null), fx.wake_services.load(.seq_cst));
1702
+ const handle = fx.openChannel(.{ .key = 68, .on_event = DirectFx.channelMsg(.event) });
1703
+ const second_snapshot = fx.wake_services.load(.seq_cst) orelse return error.TestExpectedSnapshot;
1704
+ try testing.expect(second_snapshot != first.snapshot);
1705
+ try testing.expect(second_snapshot != &second_services);
1706
+
1707
+ // BOTH snapshots valid side by side: the swap wrote nothing into
1708
+ // the first generation — the stale call's pointer reads the FIRST
1709
+ // table intact (its own hook, not the poison pattern its dead
1710
+ // owner left and not the second generation's hook) — while the
1711
+ // live channel's posts route through the second.
1712
+ try testing.expect(first.snapshot.wake_fn == RebindWakes.first);
1713
+ try testing.expect(second_snapshot.wake_fn == RebindWakes.second);
1714
+ try testing.expectEqual(PostResult.accepted, handle.post("second generation"));
1715
+ try testing.expect(RebindWakes.second_count.load(.seq_cst) >= 1);
1716
+ _ = try expectData(&fx, 68, "second generation");
1717
+
1718
+ // Release the parked call: it finishes against the process-lived
1719
+ // pieces of its own generation, and its post answers honestly.
1720
+ RebindWakes.release.store(true, .seq_cst);
1721
+ first.producer.join();
1722
+ joined = true;
1723
+ try testing.expectEqual(PostResult.accepted, post_result);
1724
+
1725
+ // The final teardown is CLEAN (no new abandon), so it frees
1726
+ // exactly the generation it quiesced: the second snapshot — never
1727
+ // the abandoned first, whose immortality outlives every later
1728
+ // lifetime of this Effects.
1729
+ fx.deinit();
1730
+ try testing.expectEqual(@as(u32, 1), fx.abandoned_channel_wakes);
1731
+ try testing.expect(tracker.didFree(second_snapshot));
1732
+ try testing.expect(!tracker.didFree(first.snapshot));
1733
+ try testing.expect(first.snapshot.wake_fn == RebindWakes.first);
1734
+ }
1735
+
1736
+ // ---------------------------------------------- record/replay acceptance
1737
+
1738
+ const channel_canvas_label = "channel-session-canvas";
1739
+
1740
+ const ChannelSessionModel = struct {
1741
+ data_events: u32 = 0,
1742
+ closed_events: u32 = 0,
1743
+ rejected_events: u32 = 0,
1744
+ dropped_pending_last: u32 = 0,
1745
+ dropped_total_last: u32 = 0,
1746
+ /// Rolling order-sensitive digest of every delivered payload — a
1747
+ /// replay that reorders or alters one byte diverges here (and in
1748
+ /// the fingerprints that pin it).
1749
+ payload_digest: u64 = 0,
1750
+ /// Rolling order-sensitive digest of every REJECTED key — the
1751
+ /// mixed-authority test's order pin: engine-staged and
1752
+ /// caller-staged (`stageLoopMsg`) rejections must deliver in
1753
+ /// staging order, and a replay that reorders them diverges here.
1754
+ rejected_key_digest: u64 = 0,
1755
+ last_line: [48]u8 = @splat(' '),
1756
+ last_line_len: usize = 0,
1757
+
1758
+ fn record(model: *ChannelSessionModel, event: effects_mod.EffectChannelEvent) void {
1759
+ switch (event.kind) {
1760
+ .data => model.data_events += 1,
1761
+ .closed => model.closed_events += 1,
1762
+ .rejected => {
1763
+ model.rejected_events += 1;
1764
+ model.rejected_key_digest = std.hash.Wyhash.hash(model.rejected_key_digest, std.mem.asBytes(&event.key));
1765
+ },
1766
+ }
1767
+ model.dropped_pending_last = event.dropped_pending;
1768
+ model.dropped_total_last = event.dropped_total;
1769
+ model.payload_digest = std.hash.Wyhash.hash(model.payload_digest, event.bytes);
1770
+ const len = @min(event.bytes.len, model.last_line.len);
1771
+ @memcpy(model.last_line[0..len], event.bytes[0..len]);
1772
+ model.last_line_len = len;
1773
+ }
1774
+
1775
+ fn lastLine(model: *const ChannelSessionModel) []const u8 {
1776
+ return model.last_line[0..model.last_line_len];
1777
+ }
1778
+ };
1779
+
1780
+ const ChannelSessionMsg = union(enum) {
1781
+ open,
1782
+ open_dup,
1783
+ /// One dispatch mixing both rejection authorities: a caller-staged
1784
+ /// rejection (`stageLoopMsg`, the TS bridge's synchronous-refusal
1785
+ /// seam), an engine-staged rejection (a duplicate open the engine
1786
+ /// refuses loop-side), and a second caller-staged one — three
1787
+ /// refusals whose delivery must hold staging order across layers.
1788
+ open_mixed,
1789
+ close,
1790
+ event: effects_mod.EffectChannelEvent,
1791
+ };
1792
+
1793
+ const ChannelSessionApp = ui_app_mod.UiApp(ChannelSessionModel, ChannelSessionMsg);
1794
+
1795
+ const session_channel_key: u64 = 41;
1796
+
1797
+ /// The handle the recording side hands its posting thread. Replay
1798
+ /// re-runs the same `openChannel` dispatch (the handle just goes
1799
+ /// unused — no source thread exists there).
1800
+ var session_handle: ?effects_mod.ChannelHandle = null;
1801
+
1802
+ fn channelSessionUpdate(model: *ChannelSessionModel, msg: ChannelSessionMsg, fx: *ChannelSessionApp.Effects) void {
1803
+ switch (msg) {
1804
+ .open => session_handle = fx.openChannel(.{
1805
+ .key = session_channel_key,
1806
+ .on_event = ChannelSessionApp.Effects.channelMsg(.event),
1807
+ .max_pending = 2,
1808
+ }),
1809
+ // The duplicate open: refused loop-side on BOTH sides — the
1810
+ // journaled `.rejected` regenerates at replay.
1811
+ .open_dup => _ = fx.openChannel(.{
1812
+ .key = session_channel_key,
1813
+ .on_event = ChannelSessionApp.Effects.channelMsg(.event),
1814
+ }),
1815
+ // Both rejection authorities in one dispatch, interleaved:
1816
+ // caller-staged (77), engine-staged (the dup of 41),
1817
+ // caller-staged (88). All three stamp the shared pending seq
1818
+ // at refusal time, so delivery — and the model's rejected-key
1819
+ // digest — pins 77, 41, 88 on record and replay alike. The
1820
+ // caller-staged Msgs are never journaled (`stageLoopMsg`'s
1821
+ // regenerating contract); the engine's dup rejection journals
1822
+ // marked regenerable and is skipped at replay.
1823
+ .open_mixed => {
1824
+ fx.stageLoopMsg(.{ .event = .{ .key = 77, .kind = .rejected } });
1825
+ _ = fx.openChannel(.{
1826
+ .key = session_channel_key,
1827
+ .on_event = ChannelSessionApp.Effects.channelMsg(.event),
1828
+ });
1829
+ fx.stageLoopMsg(.{ .event = .{ .key = 88, .kind = .rejected } });
1830
+ },
1831
+ .close => fx.closeChannel(session_channel_key),
1832
+ .event => |event| model.record(event),
1833
+ }
1834
+ }
1835
+
1836
+ fn channelSessionView(ui: *ChannelSessionApp.Ui, model: *const ChannelSessionModel) ChannelSessionApp.Ui.Node {
1837
+ // The semantic tree carries every channel-derived model fact, so
1838
+ // the fingerprint checkpoints PIN the event stream — kinds, order,
1839
+ // payload bytes, and drop accounting alike.
1840
+ return ui.column(.{ .gap = 4, .padding = 8 }, .{
1841
+ ui.text(.{}, ui.fmt("{d} data, {d} closed, {d} rejected", .{ model.data_events, model.closed_events, model.rejected_events })),
1842
+ ui.text(.{}, ui.fmt("drops {d}/{d}", .{ model.dropped_pending_last, model.dropped_total_last })),
1843
+ ui.text(.{}, ui.fmt("digest {x} last {s}", .{ model.payload_digest, model.lastLine() })),
1844
+ });
1845
+ }
1846
+
1847
+ fn channelSessionCommand(name: []const u8) ?ChannelSessionMsg {
1848
+ if (std.mem.eql(u8, name, "channel.open")) return .open;
1849
+ if (std.mem.eql(u8, name, "channel.open-dup")) return .open_dup;
1850
+ if (std.mem.eql(u8, name, "channel.open-mixed")) return .open_mixed;
1851
+ if (std.mem.eql(u8, name, "channel.close")) return .close;
1852
+ return null;
1853
+ }
1854
+
1855
+ const channel_session_views = [_]app_manifest.ShellView{
1856
+ .{ .label = channel_canvas_label, .kind = .gpu_surface, .fill = true, .gpu_backend = .metal },
1857
+ };
1858
+ const channel_session_windows = [_]app_manifest.ShellWindow{.{
1859
+ .label = "main",
1860
+ .title = "Channel Session",
1861
+ .width = 400,
1862
+ .height = 300,
1863
+ .views = &channel_session_views,
1864
+ }};
1865
+ const channel_session_scene: app_manifest.ShellConfig = .{ .windows = &channel_session_windows };
1866
+
1867
+ fn channelSessionOptions() ChannelSessionApp.Options {
1868
+ return .{
1869
+ .name = "channel-session-demo",
1870
+ .scene = channel_session_scene,
1871
+ .canvas_label = channel_canvas_label,
1872
+ .update_fx = channelSessionUpdate,
1873
+ .view = channelSessionView,
1874
+ .on_command = channelSessionCommand,
1875
+ };
1876
+ }
1877
+
1878
+ const JournalBuffer = struct {
1879
+ bytes: [256 * 1024]u8 = undefined,
1880
+ len: usize = 0,
1881
+
1882
+ fn sink(self: *JournalBuffer) session_record.RecorderSink {
1883
+ return .{ .context = self, .write_fn = write };
1884
+ }
1885
+
1886
+ fn write(context: *anyopaque, bytes: []const u8) anyerror!void {
1887
+ const self: *JournalBuffer = @ptrCast(@alignCast(context));
1888
+ if (self.len + bytes.len > self.bytes.len) return error.NoSpaceLeft;
1889
+ @memcpy(self.bytes[self.len .. self.len + bytes.len], bytes);
1890
+ self.len += bytes.len;
1891
+ }
1892
+
1893
+ fn journalBytes(self: *const JournalBuffer) []const u8 {
1894
+ return self.bytes[0..self.len];
1895
+ }
1896
+ };
1897
+
1898
+ const RecordedChannelSession = struct {
1899
+ model: ChannelSessionModel,
1900
+ fingerprint: u64,
1901
+ };
1902
+
1903
+ /// One posting burst from a REAL source thread: three lines, joined
1904
+ /// before the drain so the recorded drop accounting (max_pending = 2:
1905
+ /// two staged, one honestly refused) is deterministic.
1906
+ const SessionPoster = struct {
1907
+ fn run(handle: effects_mod.ChannelHandle) void {
1908
+ _ = handle.post("reading 1: 42 units");
1909
+ _ = handle.post("reading 2: 43 units");
1910
+ _ = handle.post("reading 3: 44 units");
1911
+ }
1912
+ };
1913
+
1914
+ /// Record the channel reference session: open, a real posting thread's
1915
+ /// burst (with one honest drop), a duplicate open's regenerating
1916
+ /// rejection, and the close terminal — checkpoints after every wake.
1917
+ fn recordChannelSession(gpa: std.mem.Allocator, buffer: *JournalBuffer) !RecordedChannelSession {
1918
+ const recorder = try std.heap.page_allocator.create(session_record.SessionRecorder);
1919
+ defer std.heap.page_allocator.destroy(recorder);
1920
+ recorder.* = session_record.SessionRecorder.init(buffer.sink());
1921
+ recorder.begin(.{ .platform_name = "test", .app_name = "channel-session-demo", .window_width = 400, .window_height = 300 });
1922
+
1923
+ const harness = try core.TestHarness().create(gpa, .{ .size = geometry.SizeF.init(400, 300) });
1924
+ defer harness.destroy(gpa);
1925
+ harness.null_platform.gpu_surfaces = true;
1926
+ harness.runtime.options.session_recorder = recorder;
1927
+
1928
+ const app_state = try gpa.create(ChannelSessionApp);
1929
+ defer gpa.destroy(app_state);
1930
+ app_state.* = ChannelSessionApp.init(std.heap.page_allocator, .{}, channelSessionOptions());
1931
+ defer app_state.deinit();
1932
+ app_state.effects.executor = .fake;
1933
+ const app = app_state.app();
1934
+ session_handle = null;
1935
+
1936
+ try harness.start(app);
1937
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
1938
+ .label = channel_canvas_label,
1939
+ .size = geometry.SizeF.init(400, 300),
1940
+ .scale_factor = 2,
1941
+ .frame_index = 1,
1942
+ .timestamp_ns = 1_000_000,
1943
+ } });
1944
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
1945
+
1946
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = "channel.open", .window_id = 1 } });
1947
+ const handle = session_handle orelse return error.TestExpectedHandle;
1948
+
1949
+ // The live source: a real thread, joined before any drain so the
1950
+ // burst's drop is deterministic (two staged, the third refused by
1951
+ // the max_pending bound).
1952
+ const poster = try std.Thread.spawn(.{}, SessionPoster.run, .{handle});
1953
+ poster.join();
1954
+ try harness.runtime.dispatchPlatformEvent(app, .wake);
1955
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
1956
+ try testing.expectEqual(@as(u32, 2), app_state.model.data_events);
1957
+ try testing.expectEqual(@as(u32, 1), app_state.model.dropped_total_last);
1958
+
1959
+ // The duplicate open: one regenerating `.rejected` terminal.
1960
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = "channel.open-dup", .window_id = 1 } });
1961
+ try harness.runtime.dispatchPlatformEvent(app, .wake);
1962
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
1963
+ try testing.expectEqual(@as(u32, 1), app_state.model.rejected_events);
1964
+
1965
+ // One more accepted post after the drain relieved the stage.
1966
+ try testing.expectEqual(PostResult.accepted, handle.post("reading 4: 45 units"));
1967
+ try harness.runtime.dispatchPlatformEvent(app, .wake);
1968
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
1969
+
1970
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = "channel.close", .window_id = 1 } });
1971
+ try harness.runtime.dispatchPlatformEvent(app, .wake);
1972
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
1973
+ try testing.expectEqual(@as(u32, 1), app_state.model.closed_events);
1974
+ try testing.expectEqual(PostResult.closed, handle.post("after close"));
1975
+
1976
+ recorder.finish();
1977
+ try testing.expect(!recorder.failed);
1978
+ return .{
1979
+ .model = app_state.model,
1980
+ .fingerprint = harness.runtime.sessionStateFingerprint(),
1981
+ };
1982
+ }
1983
+
1984
+ test "a recorded channel session replays fingerprint-identical offline with no source thread" {
1985
+ const gpa = testing.allocator;
1986
+ const buffer = try std.heap.page_allocator.create(JournalBuffer);
1987
+ defer std.heap.page_allocator.destroy(buffer);
1988
+ buffer.len = 0;
1989
+
1990
+ const recorded = try recordChannelSession(gpa, buffer);
1991
+ try testing.expectEqual(@as(u32, 3), recorded.model.data_events);
1992
+ try testing.expectEqual(@as(u32, 1), recorded.model.closed_events);
1993
+ try testing.expectEqual(@as(u32, 1), recorded.model.rejected_events);
1994
+ try testing.expectEqual(@as(u32, 1), recorded.model.dropped_total_last);
1995
+
1996
+ // Replay into a fresh app: the journal is the WHOLE world — no
1997
+ // thread posts, no handle is touched, and every fed event arrives
1998
+ // verbatim at its recorded position.
1999
+ const harness = try core.TestHarness().create(gpa, .{ .size = geometry.SizeF.init(400, 300) });
2000
+ defer harness.destroy(gpa);
2001
+ harness.null_platform.gpu_surfaces = true;
2002
+ const app_state = try gpa.create(ChannelSessionApp);
2003
+ defer gpa.destroy(app_state);
2004
+ app_state.* = ChannelSessionApp.init(std.heap.page_allocator, .{}, channelSessionOptions());
2005
+ defer app_state.deinit();
2006
+ session_handle = null;
2007
+
2008
+ const report = try session_replay.replaySession(&harness.runtime, app_state.app(), buffer.journalBytes(), .{
2009
+ .verify = true,
2010
+ .require_same_platform = false,
2011
+ });
2012
+ try testing.expect(report.ok());
2013
+ try testing.expect(report.checkpoints_verified > 0);
2014
+ // Three data events and the closed terminal FEED (executor truth);
2015
+ // the duplicate open's rejection regenerates from the replayed
2016
+ // dispatch and its record is skipped.
2017
+ try testing.expectEqual(@as(u64, 4), report.effects_fed);
2018
+ try testing.expectEqual(@as(u64, 1), report.effects_skipped);
2019
+ try testing.expectEqualDeep(recorded.model, app_state.model);
2020
+ try testing.expectEqual(recorded.fingerprint, harness.runtime.sessionStateFingerprint());
2021
+ // Replay opened (and close-parked) the channel through the same
2022
+ // dispatches; the fed `.closed` retired it — nothing is left open.
2023
+ try testing.expect(app_state.effects.channelHandle(session_channel_key) == null);
2024
+ }
2025
+
2026
+ /// Record the mixed-authority rejection session: one live channel, one
2027
+ /// accepted post, then one dispatch that interleaves caller-staged
2028
+ /// rejections (`stageLoopMsg`) around an engine-staged one, and the
2029
+ /// close terminal.
2030
+ fn recordMixedRejectionSession(gpa: std.mem.Allocator, buffer: *JournalBuffer) !RecordedChannelSession {
2031
+ const recorder = try std.heap.page_allocator.create(session_record.SessionRecorder);
2032
+ defer std.heap.page_allocator.destroy(recorder);
2033
+ recorder.* = session_record.SessionRecorder.init(buffer.sink());
2034
+ recorder.begin(.{ .platform_name = "test", .app_name = "channel-session-demo", .window_width = 400, .window_height = 300 });
2035
+
2036
+ const harness = try core.TestHarness().create(gpa, .{ .size = geometry.SizeF.init(400, 300) });
2037
+ defer harness.destroy(gpa);
2038
+ harness.null_platform.gpu_surfaces = true;
2039
+ harness.runtime.options.session_recorder = recorder;
2040
+
2041
+ const app_state = try gpa.create(ChannelSessionApp);
2042
+ defer gpa.destroy(app_state);
2043
+ app_state.* = ChannelSessionApp.init(std.heap.page_allocator, .{}, channelSessionOptions());
2044
+ defer app_state.deinit();
2045
+ app_state.effects.executor = .fake;
2046
+ const app = app_state.app();
2047
+ session_handle = null;
2048
+
2049
+ try harness.start(app);
2050
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
2051
+ .label = channel_canvas_label,
2052
+ .size = geometry.SizeF.init(400, 300),
2053
+ .scale_factor = 2,
2054
+ .frame_index = 1,
2055
+ .timestamp_ns = 1_000_000,
2056
+ } });
2057
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
2058
+
2059
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = "channel.open", .window_id = 1 } });
2060
+ const handle = session_handle orelse return error.TestExpectedHandle;
2061
+ try testing.expectEqual(PostResult.accepted, handle.post("reading 1: 42 units"));
2062
+ try harness.runtime.dispatchPlatformEvent(app, .wake);
2063
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
2064
+ try testing.expectEqual(@as(u32, 1), app_state.model.data_events);
2065
+
2066
+ // The mixed dispatch: three rejections, two authorities, one
2067
+ // staging order (77 caller, 41 engine, 88 caller).
2068
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = "channel.open-mixed", .window_id = 1 } });
2069
+ try harness.runtime.dispatchPlatformEvent(app, .wake);
2070
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
2071
+ try testing.expectEqual(@as(u32, 3), app_state.model.rejected_events);
2072
+
2073
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = "channel.close", .window_id = 1 } });
2074
+ try harness.runtime.dispatchPlatformEvent(app, .wake);
2075
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
2076
+ try testing.expectEqual(@as(u32, 1), app_state.model.closed_events);
2077
+
2078
+ recorder.finish();
2079
+ try testing.expect(!recorder.failed);
2080
+ return .{
2081
+ .model = app_state.model,
2082
+ .fingerprint = harness.runtime.sessionStateFingerprint(),
2083
+ };
2084
+ }
2085
+
2086
+ test "mixed caller- and engine-staged rejections deliver in staging order and replay identically with neither journaled as executor truth" {
2087
+ const gpa = testing.allocator;
2088
+ const buffer = try std.heap.page_allocator.create(JournalBuffer);
2089
+ defer std.heap.page_allocator.destroy(buffer);
2090
+ buffer.len = 0;
2091
+
2092
+ const recorded = try recordMixedRejectionSession(gpa, buffer);
2093
+ // The order pin: rejected keys hashed in delivery order must be
2094
+ // exactly the staging order 77 (caller), 41 (engine), 88 (caller).
2095
+ var expected_digest: u64 = 0;
2096
+ for ([_]u64{ 77, session_channel_key, 88 }) |key| {
2097
+ expected_digest = std.hash.Wyhash.hash(expected_digest, std.mem.asBytes(&key));
2098
+ }
2099
+ try testing.expectEqual(expected_digest, recorded.model.rejected_key_digest);
2100
+
2101
+ // Replay into a fresh app: the journal is the whole world.
2102
+ const harness = try core.TestHarness().create(gpa, .{ .size = geometry.SizeF.init(400, 300) });
2103
+ defer harness.destroy(gpa);
2104
+ harness.null_platform.gpu_surfaces = true;
2105
+ const app_state = try gpa.create(ChannelSessionApp);
2106
+ defer gpa.destroy(app_state);
2107
+ app_state.* = ChannelSessionApp.init(std.heap.page_allocator, .{}, channelSessionOptions());
2108
+ defer app_state.deinit();
2109
+ session_handle = null;
2110
+
2111
+ const report = try session_replay.replaySession(&harness.runtime, app_state.app(), buffer.journalBytes(), .{
2112
+ .verify = true,
2113
+ .require_same_platform = false,
2114
+ });
2115
+ try testing.expect(report.ok());
2116
+ try testing.expect(report.checkpoints_verified > 0);
2117
+ // The journal carries NEITHER rejection authority as executor
2118
+ // truth: the one data event and the closed terminal FEED; the
2119
+ // engine's dup rejection journals marked regenerable and is
2120
+ // SKIPPED (the replayed open re-derives it); the two caller-staged
2121
+ // rejections were never journaled at all — nothing to feed,
2122
+ // nothing to skip, regenerated by the replayed dispatch itself.
2123
+ try testing.expectEqual(@as(u64, 2), report.effects_fed);
2124
+ try testing.expectEqual(@as(u64, 1), report.effects_skipped);
2125
+ // The identical model INCLUDES the rejected-key digest: the
2126
+ // replayed Msg order matches the recorded order across both
2127
+ // authorities.
2128
+ try testing.expectEqualDeep(recorded.model, app_state.model);
2129
+ try testing.expectEqual(recorded.fingerprint, harness.runtime.sessionStateFingerprint());
2130
+ try testing.expect(app_state.effects.channelHandle(session_channel_key) == null);
2131
+ }
2132
+
2133
+ // ------------------- replay acceptance: the open-and-spawn pattern
2134
+ //
2135
+ // The channel-monitor example's documented shape: ONE update handler
2136
+ // both opens the channel and spawns the worker thread that posts into
2137
+ // it. A replayed session re-executes that update, and BOTH producer
2138
+ // disciplines must replay the identical stream from one recording:
2139
+ // the example's `handle.live()` gate skips the spawn entirely (the
2140
+ // parked handle answers false — replay fully offline), and an
2141
+ // unconditional launch really starts but exits on its FIRST post
2142
+ // against the inert handle. The fed journal events are the only event
2143
+ // stream either way; a live re-run source would interleave with them
2144
+ // and diverge the fingerprint.
2145
+
2146
+ const monitor_channel_key: u64 = 61;
2147
+
2148
+ var monitor_thread: ?std.Thread = null;
2149
+ var monitor_posts_made: u32 = 0;
2150
+ var monitor_first_post_closed: bool = false;
2151
+ var monitor_spawns: u32 = 0;
2152
+ /// The producer discipline under test: true mirrors the example's
2153
+ /// `live()` gate; false is the unconditional launcher the inert
2154
+ /// handle must stop at its first post.
2155
+ var monitor_consults_live = true;
2156
+
2157
+ /// The worker the update handler spawns — the example's sampling loop,
2158
+ /// bounded at three samples so record-side staging is deterministic.
2159
+ /// A closed answer ends the loop immediately (the well-behaved
2160
+ /// producer contract).
2161
+ const MonitorWorker = struct {
2162
+ fn run(handle: effects_mod.ChannelHandle) void {
2163
+ var buffer: [32]u8 = undefined;
2164
+ var index: u32 = 0;
2165
+ while (index < 3) : (index += 1) {
2166
+ const line = std.fmt.bufPrint(&buffer, "sample {d}", .{index}) catch unreachable;
2167
+ const result = handle.post(line);
2168
+ monitor_posts_made += 1;
2169
+ switch (result) {
2170
+ // Drops are transient: skip the sample, keep sampling.
2171
+ .accepted, .dropped_full, .dropped_oversized => {},
2172
+ // The occupancy is over: exit the loop for good.
2173
+ .closed => {
2174
+ monitor_first_post_closed = (index == 0);
2175
+ return;
2176
+ },
2177
+ }
2178
+ }
2179
+ }
2180
+ };
2181
+
2182
+ fn monitorUpdate(model: *ChannelSessionModel, msg: ChannelSessionMsg, fx: *ChannelSessionApp.Effects) void {
2183
+ switch (msg) {
2184
+ // The open-and-spawn pattern under test: BOTH sides re-run this
2185
+ // dispatch. The join inside the handler is the test's
2186
+ // determinism pin (the example joins later, at close) — it
2187
+ // pins exactly when the worker's posts have all been answered,
2188
+ // on the recording and the replay alike.
2189
+ .open => {
2190
+ const handle = fx.openChannel(.{
2191
+ .key = monitor_channel_key,
2192
+ .on_event = ChannelSessionApp.Effects.channelMsg(.event),
2193
+ });
2194
+ // The example's launch discipline (when consulted): spawn
2195
+ // only for a live handle. The model never reads `live()`,
2196
+ // so the Msg stream — and the model — stay identical
2197
+ // across both disciplines and both sides of the journal.
2198
+ if (!monitor_consults_live or handle.live()) {
2199
+ monitor_spawns += 1;
2200
+ monitor_thread = std.Thread.spawn(.{}, MonitorWorker.run, .{handle}) catch null;
2201
+ if (monitor_thread) |thread| {
2202
+ thread.join();
2203
+ monitor_thread = null;
2204
+ }
2205
+ }
2206
+ },
2207
+ .open_dup => _ = fx.openChannel(.{
2208
+ .key = monitor_channel_key,
2209
+ .on_event = ChannelSessionApp.Effects.channelMsg(.event),
2210
+ }),
2211
+ // The session-app msg set is shared; the monitor session never
2212
+ // dispatches the mixed-authority probe.
2213
+ .open_mixed => {},
2214
+ .close => fx.closeChannel(monitor_channel_key),
2215
+ .event => |event| model.record(event),
2216
+ }
2217
+ }
2218
+
2219
+ fn monitorCommand(name: []const u8) ?ChannelSessionMsg {
2220
+ if (std.mem.eql(u8, name, "monitor.open")) return .open;
2221
+ if (std.mem.eql(u8, name, "monitor.close")) return .close;
2222
+ return null;
2223
+ }
2224
+
2225
+ fn monitorOptions() ChannelSessionApp.Options {
2226
+ return .{
2227
+ .name = "channel-monitor-session",
2228
+ .scene = channel_session_scene,
2229
+ .canvas_label = channel_canvas_label,
2230
+ .update_fx = monitorUpdate,
2231
+ .view = channelSessionView,
2232
+ .on_command = monitorCommand,
2233
+ };
2234
+ }
2235
+
2236
+ fn recordMonitorSession(gpa: std.mem.Allocator, buffer: *JournalBuffer) !RecordedChannelSession {
2237
+ const recorder = try std.heap.page_allocator.create(session_record.SessionRecorder);
2238
+ defer std.heap.page_allocator.destroy(recorder);
2239
+ recorder.* = session_record.SessionRecorder.init(buffer.sink());
2240
+ recorder.begin(.{ .platform_name = "test", .app_name = "channel-monitor-session", .window_width = 400, .window_height = 300 });
2241
+
2242
+ const harness = try core.TestHarness().create(gpa, .{ .size = geometry.SizeF.init(400, 300) });
2243
+ defer harness.destroy(gpa);
2244
+ harness.null_platform.gpu_surfaces = true;
2245
+ harness.runtime.options.session_recorder = recorder;
2246
+
2247
+ const app_state = try gpa.create(ChannelSessionApp);
2248
+ defer gpa.destroy(app_state);
2249
+ app_state.* = ChannelSessionApp.init(std.heap.page_allocator, .{}, monitorOptions());
2250
+ defer app_state.deinit();
2251
+ app_state.effects.executor = .fake;
2252
+ const app = app_state.app();
2253
+
2254
+ try harness.start(app);
2255
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
2256
+ .label = channel_canvas_label,
2257
+ .size = geometry.SizeF.init(400, 300),
2258
+ .scale_factor = 2,
2259
+ .frame_index = 1,
2260
+ .timestamp_ns = 1_000_000,
2261
+ } });
2262
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
2263
+
2264
+ // Open-and-spawn: the worker posts its three samples and exits
2265
+ // (joined inside the dispatch), then the drain delivers them.
2266
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = "monitor.open", .window_id = 1 } });
2267
+ try harness.runtime.dispatchPlatformEvent(app, .wake);
2268
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
2269
+ try testing.expectEqual(@as(u32, 3), app_state.model.data_events);
2270
+
2271
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = "monitor.close", .window_id = 1 } });
2272
+ try harness.runtime.dispatchPlatformEvent(app, .wake);
2273
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
2274
+ try testing.expectEqual(@as(u32, 1), app_state.model.closed_events);
2275
+
2276
+ recorder.finish();
2277
+ try testing.expect(!recorder.failed);
2278
+ return .{
2279
+ .model = app_state.model,
2280
+ .fingerprint = harness.runtime.sessionStateFingerprint(),
2281
+ };
2282
+ }
2283
+
2284
+ fn resetMonitorGlobals() void {
2285
+ monitor_thread = null;
2286
+ monitor_posts_made = 0;
2287
+ monitor_first_post_closed = false;
2288
+ monitor_spawns = 0;
2289
+ }
2290
+
2291
+ test "replaying an open-and-spawn session with the live() gate never creates the sampler thread" {
2292
+ const gpa = testing.allocator;
2293
+ const buffer = try std.heap.page_allocator.create(JournalBuffer);
2294
+ defer std.heap.page_allocator.destroy(buffer);
2295
+ buffer.len = 0;
2296
+
2297
+ resetMonitorGlobals();
2298
+ monitor_consults_live = true;
2299
+ defer monitor_consults_live = true;
2300
+ const recorded = try recordMonitorSession(gpa, buffer);
2301
+ try testing.expectEqual(@as(u32, 3), recorded.model.data_events);
2302
+ try testing.expectEqual(@as(u32, 1), recorded.model.closed_events);
2303
+ // The recording side is live: `live()` answered true, the worker
2304
+ // spawned and posted its three samples.
2305
+ try testing.expectEqual(@as(u32, 1), monitor_spawns);
2306
+ try testing.expectEqual(@as(u32, 3), monitor_posts_made);
2307
+
2308
+ // Replay re-executes the SAME open-and-spawn update, but the
2309
+ // example's `live()` gate sees the parked handle answer false: the
2310
+ // sampler thread is NEVER created — no spawn, no pre-post work,
2311
+ // replay fully offline — and the fed events replay the recorded
2312
+ // stream byte-identical.
2313
+ resetMonitorGlobals();
2314
+ const harness = try core.TestHarness().create(gpa, .{ .size = geometry.SizeF.init(400, 300) });
2315
+ defer harness.destroy(gpa);
2316
+ harness.null_platform.gpu_surfaces = true;
2317
+ const app_state = try gpa.create(ChannelSessionApp);
2318
+ defer gpa.destroy(app_state);
2319
+ app_state.* = ChannelSessionApp.init(std.heap.page_allocator, .{}, monitorOptions());
2320
+ defer app_state.deinit();
2321
+
2322
+ const report = try session_replay.replaySession(&harness.runtime, app_state.app(), buffer.journalBytes(), .{
2323
+ .verify = true,
2324
+ .require_same_platform = false,
2325
+ });
2326
+ try testing.expectEqual(@as(u32, 0), monitor_spawns);
2327
+ try testing.expectEqual(@as(u32, 0), monitor_posts_made);
2328
+ try testing.expect(monitor_thread == null);
2329
+ try testing.expect(report.ok());
2330
+ try testing.expect(report.checkpoints_verified > 0);
2331
+ // Three fed data events plus the fed closed terminal — and NOTHING
2332
+ // else: the never-launched worker contributed no events and no
2333
+ // journal records.
2334
+ try testing.expectEqual(@as(u64, 4), report.effects_fed);
2335
+ try testing.expectEqual(@as(u64, 0), report.effects_skipped);
2336
+ try testing.expectEqualDeep(recorded.model, app_state.model);
2337
+ try testing.expectEqual(recorded.fingerprint, harness.runtime.sessionStateFingerprint());
2338
+ // The fed closed terminal retired the parked occupancy.
2339
+ try testing.expect(app_state.effects.channelHandle(monitor_channel_key) == null);
2340
+ }
2341
+
2342
+ test "replaying the same session with an unconditional launcher stops the re-run worker at its first post" {
2343
+ const gpa = testing.allocator;
2344
+ const buffer = try std.heap.page_allocator.create(JournalBuffer);
2345
+ defer std.heap.page_allocator.destroy(buffer);
2346
+ buffer.len = 0;
2347
+
2348
+ resetMonitorGlobals();
2349
+ monitor_consults_live = true;
2350
+ defer monitor_consults_live = true;
2351
+ const recorded = try recordMonitorSession(gpa, buffer);
2352
+ try testing.expectEqual(@as(u32, 3), monitor_posts_made);
2353
+
2354
+ // The safety net behind the honesty teaching: a producer that
2355
+ // launches WITHOUT consulting `live()` really starts under replay
2356
+ // — app code is app code — but the parked channel's inert handle
2357
+ // answers closed on its first post, the worker exits (joined
2358
+ // before the report below), nothing is staged or journaled, and
2359
+ // the SAME journal replays the identical stream.
2360
+ resetMonitorGlobals();
2361
+ monitor_consults_live = false;
2362
+ const harness = try core.TestHarness().create(gpa, .{ .size = geometry.SizeF.init(400, 300) });
2363
+ defer harness.destroy(gpa);
2364
+ harness.null_platform.gpu_surfaces = true;
2365
+ const app_state = try gpa.create(ChannelSessionApp);
2366
+ defer gpa.destroy(app_state);
2367
+ app_state.* = ChannelSessionApp.init(std.heap.page_allocator, .{}, monitorOptions());
2368
+ defer app_state.deinit();
2369
+
2370
+ const report = try session_replay.replaySession(&harness.runtime, app_state.app(), buffer.journalBytes(), .{
2371
+ .verify = true,
2372
+ .require_same_platform = false,
2373
+ });
2374
+ try testing.expect(monitor_thread == null);
2375
+ // The worker spawned and exited on its FIRST post: the inert
2376
+ // handle answered closed immediately.
2377
+ try testing.expectEqual(@as(u32, 1), monitor_spawns);
2378
+ try testing.expectEqual(@as(u32, 1), monitor_posts_made);
2379
+ try testing.expect(monitor_first_post_closed);
2380
+ try testing.expect(report.ok());
2381
+ try testing.expect(report.checkpoints_verified > 0);
2382
+ try testing.expectEqual(@as(u64, 4), report.effects_fed);
2383
+ try testing.expectEqual(@as(u64, 0), report.effects_skipped);
2384
+ try testing.expectEqualDeep(recorded.model, app_state.model);
2385
+ try testing.expectEqual(recorded.fingerprint, harness.runtime.sessionStateFingerprint());
2386
+ }
2387
+
2388
+ // --------------------------------------------- wake back-pressure gate
2389
+
2390
+ test "rejected posts never wake the host: the pending-wake count stays flat under a refusal storm" {
2391
+ const gpa = testing.allocator;
2392
+ const harness = try core.TestHarness().create(gpa, .{ .size = geometry.SizeF.init(400, 300) });
2393
+ defer harness.destroy(gpa);
2394
+ harness.null_platform.gpu_surfaces = true;
2395
+
2396
+ const app_state = try gpa.create(ChannelSessionApp);
2397
+ defer gpa.destroy(app_state);
2398
+ app_state.* = ChannelSessionApp.init(std.heap.page_allocator, .{}, channelSessionOptions());
2399
+ defer app_state.deinit();
2400
+ app_state.effects.executor = .fake;
2401
+ const app = app_state.app();
2402
+ session_handle = null;
2403
+
2404
+ try harness.start(app);
2405
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
2406
+ .label = channel_canvas_label,
2407
+ .size = geometry.SizeF.init(400, 300),
2408
+ .scale_factor = 2,
2409
+ .frame_index = 1,
2410
+ .timestamp_ns = 1_000_000,
2411
+ } });
2412
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
2413
+
2414
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = "channel.open", .window_id = 1 } });
2415
+ const handle = session_handle orelse return error.TestExpectedHandle;
2416
+
2417
+ // Accepted posts wake, COALESCED: the first accepted post latches
2418
+ // exactly one host wake and the rest of the burst rides it — one
2419
+ // wake drains the whole eligible backlog, so a fill/drain/refill
2420
+ // producer can never park a backlog of redundant host-queue
2421
+ // entries behind the one drain that answers them all.
2422
+ const before_accepted = harness.null_platform.pendingWakeCount();
2423
+ try testing.expectEqual(PostResult.accepted, handle.post("kept 1"));
2424
+ try testing.expectEqual(before_accepted + 1, harness.null_platform.pendingWakeCount());
2425
+ try testing.expectEqual(PostResult.accepted, handle.post("kept 2"));
2426
+ try testing.expectEqual(before_accepted + 1, harness.null_platform.pendingWakeCount());
2427
+
2428
+ // The stage is full (max_pending = 2). A refused post stages
2429
+ // nothing, so it must NOT wake: the staged entries' own accepted
2430
+ // posts already woke the loop, and the drop counters ride the next
2431
+ // delivered event with no extra nudge. A producer that keeps going
2432
+ // after `.dropped_full` — the documented pattern — must never grow
2433
+ // the host loop's queue.
2434
+ const before_refused = harness.null_platform.pendingWakeCount();
2435
+ var index: usize = 0;
2436
+ while (index < 64) : (index += 1) {
2437
+ try testing.expectEqual(PostResult.dropped_full, handle.post("refused"));
2438
+ }
2439
+ const oversized = [_]u8{'x'} ** (effects_mod.max_effect_channel_bytes + 1);
2440
+ try testing.expectEqual(PostResult.dropped_oversized, handle.post(&oversized));
2441
+ try testing.expectEqual(before_refused, harness.null_platform.pendingWakeCount());
2442
+
2443
+ // Drain: the staged entries deliver and the first delivered event
2444
+ // carries every counted drop.
2445
+ while (harness.null_platform.takeWake()) |event| {
2446
+ try harness.runtime.dispatchPlatformEvent(app, event);
2447
+ }
2448
+ try testing.expectEqual(@as(u32, 2), app_state.model.data_events);
2449
+ try testing.expectEqual(@as(u32, 65), app_state.model.dropped_total_last);
2450
+
2451
+ // Delivery latency: the drain unlatched the coalescer, so an
2452
+ // accepted post after the idle period wakes immediately — one
2453
+ // wake per drain, never fewer (the stall the latch must not
2454
+ // introduce) and never a backlog.
2455
+ const before_relieved = harness.null_platform.pendingWakeCount();
2456
+ try testing.expectEqual(PostResult.accepted, handle.post("kept 3"));
2457
+ try testing.expectEqual(before_relieved + 1, harness.null_platform.pendingWakeCount());
2458
+
2459
+ // A post against a closed channel is a pure no-op: nothing staged,
2460
+ // nothing counted, no wake.
2461
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = "channel.close", .window_id = 1 } });
2462
+ const before_closed = harness.null_platform.pendingWakeCount();
2463
+ try testing.expectEqual(PostResult.closed, handle.post("after close"));
2464
+ try testing.expectEqual(before_closed, harness.null_platform.pendingWakeCount());
2465
+ }
2466
+
2467
+ // -------------------- generation width: permanent-closed is absolute
2468
+
2469
+ test "channel generations are u64 from the channel-owned counter" {
2470
+ // Type pins: the posting handle and the process-lifetime header
2471
+ // carry the channel family's u64 generation — never the shared u32
2472
+ // effect counter, whose wrap would bound the permanent-`.closed`
2473
+ // guarantee at 2^32 occupancies.
2474
+ try testing.expectEqual(u64, @FieldType(effects_mod.ChannelHandle, "generation"));
2475
+ try testing.expectEqual(u64, @FieldType(effects_mod.ChannelShared, "generation"));
2476
+
2477
+ var fx = DirectFx.init(testing.allocator);
2478
+ defer fx.deinit();
2479
+ fx.executor = .fake;
2480
+
2481
+ // The counter is channel-owned and monotonic: seed it past
2482
+ // anything a u32 can hold and the next occupancy continues from
2483
+ // there — the shared effect counter never touches it.
2484
+ fx.channel_generation = @as(u64, std.math.maxInt(u32)) + 41;
2485
+ const handle = fx.openChannel(.{ .key = 61, .on_event = DirectFx.channelMsg(.event) });
2486
+ try testing.expectEqual(@as(u64, std.math.maxInt(u32)) + 42, handle.generation);
2487
+ try testing.expectEqual(PostResult.accepted, handle.post("wide"));
2488
+ _ = try expectData(&fx, 61, "wide");
2489
+ fx.closeChannel(61);
2490
+ _ = fx.takeMsg();
2491
+ }
2492
+
2493
+ test "a stale handle stays closed across a u32 wrap's worth of occupancy turnovers" {
2494
+ var fx = DirectFx.init(testing.allocator);
2495
+ defer fx.deinit();
2496
+ fx.executor = .fake;
2497
+
2498
+ // First occupancy: the stale handle a long-lived producer thread
2499
+ // might still hold centuries of churn later.
2500
+ const stale = fx.openChannel(.{ .key = 62, .on_event = DirectFx.channelMsg(.event) });
2501
+ fx.closeChannel(62);
2502
+ const closed = fx.takeMsg() orelse return error.TestExpectedMsg;
2503
+ try testing.expectEqual(effects_mod.EffectChannelEventKind.closed, closed.event.kind);
2504
+
2505
+ // Simulate 2^32 turnovers of the old u32 counter's worth: seed the
2506
+ // channel counter so the reused slot's next generation TRUNCATES
2507
+ // to the stale handle's value in u32 arithmetic — exactly the wrap
2508
+ // that would have resurrected the stale handle against the reused
2509
+ // slot's header.
2510
+ fx.channel_generation = stale.generation + (@as(u64, 1) << 32) - 1;
2511
+ const fresh = fx.openChannel(.{ .key = 62, .on_event = DirectFx.channelMsg(.event) });
2512
+ try testing.expectEqual(stale.generation + (@as(u64, 1) << 32), fresh.generation);
2513
+ // The u32 collision is real...
2514
+ try testing.expectEqual(@as(u32, @truncate(stale.generation)), @as(u32, @truncate(fresh.generation)));
2515
+ // ...and harmless at u64: the stale handle still answers `.closed`
2516
+ // — nothing staged, nothing counted — while the fresh occupancy
2517
+ // posts normally into its own stream.
2518
+ try testing.expectEqual(PostResult.closed, stale.post("resurrected?"));
2519
+ try testing.expectEqual(PostResult.accepted, fresh.post("fresh stream"));
2520
+ const delivered = try expectData(&fx, 62, "fresh stream");
2521
+ try testing.expectEqual(@as(u32, 0), delivered.dropped_total);
2522
+ fx.closeChannel(62);
2523
+ _ = fx.takeMsg();
2524
+ }
2525
+
2526
+ // ------------------------------------------------- replay damage gates
2527
+
2528
+ /// Frame a minimal journal around one hand-built channel effect record:
2529
+ /// header, one `app_start` event (so the effect has a preceding
2530
+ /// dispatch), the record, and a matching end record.
2531
+ fn buildChannelDamageJournal(buffer: []u8, record: effects_mod.EffectResultRecord) ![]const u8 {
2532
+ var len: usize = 0;
2533
+ len += journal.writePreamble(buffer).len;
2534
+ var payload: [2 * effects_mod.max_effect_channel_bytes]u8 = undefined;
2535
+ var frame: [2 * effects_mod.max_effect_channel_bytes + 64]u8 = undefined;
2536
+
2537
+ const header_payload = try journal.encodeHeader(.{ .platform_name = "test", .app_name = "damage" }, &payload);
2538
+ var framed = try journal.frameRecord(.header, header_payload, &frame);
2539
+ @memcpy(buffer[len .. len + framed.len], framed);
2540
+ len += framed.len;
2541
+
2542
+ const event_payload = try journal.encodeEvent(.app_start, &payload);
2543
+ framed = try journal.frameRecord(.event, event_payload, &frame);
2544
+ @memcpy(buffer[len .. len + framed.len], framed);
2545
+ len += framed.len;
2546
+
2547
+ const effect_payload = try journal.encodeEffect(record, &payload);
2548
+ framed = try journal.frameRecord(.effect, effect_payload, &frame);
2549
+ @memcpy(buffer[len .. len + framed.len], framed);
2550
+ len += framed.len;
2551
+
2552
+ const end_payload = try journal.encodeEnd(.{ .event_count = 1, .effect_count = 1, .checkpoint_count = 0, .screenshot_count = 0 }, &payload);
2553
+ framed = try journal.frameRecord(.end, end_payload, &frame);
2554
+ @memcpy(buffer[len .. len + framed.len], framed);
2555
+ len += framed.len;
2556
+ return buffer[0..len];
2557
+ }
2558
+
2559
+ fn replayChannelDamageRecord(record: effects_mod.EffectResultRecord) !session_replay.ReplayReport {
2560
+ const gpa = testing.allocator;
2561
+ const buffer = try std.heap.page_allocator.alloc(u8, 64 * 1024);
2562
+ defer std.heap.page_allocator.free(buffer);
2563
+ const journal_bytes = try buildChannelDamageJournal(buffer, record);
2564
+
2565
+ const harness = try core.TestHarness().create(gpa, .{ .size = geometry.SizeF.init(400, 300) });
2566
+ defer harness.destroy(gpa);
2567
+ harness.null_platform.gpu_surfaces = true;
2568
+ const app_state = try gpa.create(ChannelSessionApp);
2569
+ defer gpa.destroy(app_state);
2570
+ app_state.* = ChannelSessionApp.init(std.heap.page_allocator, .{}, channelSessionOptions());
2571
+ defer app_state.deinit();
2572
+ session_handle = null;
2573
+
2574
+ return session_replay.replaySession(&harness.runtime, app_state.app(), journal_bytes, .{
2575
+ .verify = false,
2576
+ .require_same_platform = false,
2577
+ });
2578
+ }
2579
+
2580
+ test "a channel record with bytes over the post bound refuses replay as damage" {
2581
+ // A recorded post can never exceed max_effect_channel_bytes — the
2582
+ // handle refuses the bound before staging — so the gate must fire
2583
+ // before the fed bytes could reach a fixed-size feed buffer.
2584
+ const oversized = [_]u8{'z'} ** (effects_mod.max_effect_channel_bytes + 1);
2585
+ const result = replayChannelDamageRecord(.{
2586
+ .kind = .channel,
2587
+ .key = session_channel_key,
2588
+ .payload = &oversized,
2589
+ .channel_kind = .data,
2590
+ });
2591
+ try testing.expectError(error.ReplayDamagedRecord, result);
2592
+ }
2593
+
2594
+ test "a channel terminal claiming payload bytes refuses replay as damage" {
2595
+ // `.closed` and `.rejected` are payload-free by construction; a
2596
+ // record that decodes fine but claims otherwise is hand-edited.
2597
+ const result = replayChannelDamageRecord(.{
2598
+ .kind = .channel,
2599
+ .key = session_channel_key,
2600
+ .payload = "not a data event",
2601
+ .channel_kind = .closed,
2602
+ });
2603
+ try testing.expectError(error.ReplayDamagedRecord, result);
2604
+ }
2605
+
2606
+ test "a channel .data record stamped with rejected provenance refuses replay as damage" {
2607
+ // The recorder stamps `.rejected` provenance only on regenerating
2608
+ // admission refusals, whose event kind is always `.rejected`. A
2609
+ // `.data` record wearing that stamp would be silently skipped by
2610
+ // the regeneration filter — with verification disabled, replay
2611
+ // would succeed with a different Msg stream — so the mismatch is
2612
+ // damage, refused before the skip decision.
2613
+ const result = replayChannelDamageRecord(.{
2614
+ .kind = .channel,
2615
+ .key = session_channel_key,
2616
+ .payload = "reading 1: 42 units",
2617
+ .channel_kind = .data,
2618
+ .exit_reason = .rejected,
2619
+ });
2620
+ try testing.expectError(error.ReplayDamagedRecord, result);
2621
+ }
2622
+
2623
+ test "a channel .closed record stamped with rejected provenance refuses replay as damage" {
2624
+ // The `.data` mismatch's terminal twin: a skipped `.closed` would
2625
+ // leave the replayed channel parked forever with its key occupied.
2626
+ const result = replayChannelDamageRecord(.{
2627
+ .kind = .channel,
2628
+ .key = session_channel_key,
2629
+ .channel_kind = .closed,
2630
+ .exit_reason = .rejected,
2631
+ });
2632
+ try testing.expectError(error.ReplayDamagedRecord, result);
2633
+ }
2634
+
2635
+ test "a channel record with provenance outside the recorder's range refuses replay as damage" {
2636
+ // Channel records journal from exactly two sites, and neither can
2637
+ // write any exit reason but `.exited` or `.rejected`; a decoded
2638
+ // `.cancelled` (a valid enum member for SPAWN records) on a
2639
+ // channel record is hand-editing.
2640
+ const result = replayChannelDamageRecord(.{
2641
+ .kind = .channel,
2642
+ .key = session_channel_key,
2643
+ .payload = "reading 1: 42 units",
2644
+ .channel_kind = .data,
2645
+ .exit_reason = .cancelled,
2646
+ });
2647
+ try testing.expectError(error.ReplayDamagedRecord, result);
2648
+ }
2649
+
2650
+ test "an executor-truth channel rejection record still feeds and retires the parked open" {
2651
+ // The reverse direction's positive pin: `.rejected` kind with
2652
+ // `.exited` provenance is exactly what the recorder writes for an
2653
+ // open that could not stage its channel (executor truth) — it must
2654
+ // FEED, never refuse and never skip. The damage journal's one
2655
+ // `app_start` event opens nothing, so the fed record simply finds
2656
+ // no park — the gate letting it THROUGH to the feed (EffectNotFound
2657
+ // surfacing as the divergence report, not ReplayDamagedRecord) is
2658
+ // the pin.
2659
+ const result = replayChannelDamageRecord(.{
2660
+ .kind = .channel,
2661
+ .key = session_channel_key,
2662
+ .channel_kind = .rejected,
2663
+ .exit_reason = .exited,
2664
+ });
2665
+ try testing.expectError(error.ReplayEffectDivergence, result);
2666
+ }
2667
+
2668
+ // ------------------- table capacity: the start-failure reservation
2669
+
2670
+ /// Fails exactly the next channel-storage allocation and delegates
2671
+ /// everything else to the page allocator — `process_allocator`'s
2672
+ /// backing, which keeps retire/teardown's `process_allocator` frees
2673
+ /// valid for every allocation that succeeds. The seam
2674
+ /// (`channel_storage_allocator`) is consulted only by `openChannel`'s
2675
+ /// posting-header, staging-FIFO, and services-snapshot creates, so
2676
+ /// failing the next call through it is exactly one open's (or one
2677
+ /// publication's) start failure — the surgical one-shot the image
2678
+ /// tests get from their buffer-size-matched wrapper
2679
+ /// (`ImageBufferFailingAllocator` in the session tests).
2680
+ const ChannelStorageFailingAllocator = struct {
2681
+ backing: std.mem.Allocator = std.heap.page_allocator,
2682
+ armed: bool = false,
2683
+
2684
+ const vtable: std.mem.Allocator.VTable = .{
2685
+ .alloc = alloc,
2686
+ .resize = resize,
2687
+ .remap = remap,
2688
+ .free = free,
2689
+ };
2690
+
2691
+ fn allocator(self: *ChannelStorageFailingAllocator) std.mem.Allocator {
2692
+ return .{ .ptr = self, .vtable = &vtable };
2693
+ }
2694
+
2695
+ fn alloc(ptr: *anyopaque, len: usize, alignment: std.mem.Alignment, ret_addr: usize) ?[*]u8 {
2696
+ const self: *ChannelStorageFailingAllocator = @ptrCast(@alignCast(ptr));
2697
+ if (self.armed) {
2698
+ self.armed = false;
2699
+ return null;
2700
+ }
2701
+ return self.backing.vtable.alloc(self.backing.ptr, len, alignment, ret_addr);
2702
+ }
2703
+
2704
+ fn resize(ptr: *anyopaque, memory: []u8, alignment: std.mem.Alignment, new_len: usize, ret_addr: usize) bool {
2705
+ const self: *ChannelStorageFailingAllocator = @ptrCast(@alignCast(ptr));
2706
+ return self.backing.vtable.resize(self.backing.ptr, memory, alignment, new_len, ret_addr);
2707
+ }
2708
+
2709
+ fn remap(ptr: *anyopaque, memory: []u8, alignment: std.mem.Alignment, new_len: usize, ret_addr: usize) ?[*]u8 {
2710
+ const self: *ChannelStorageFailingAllocator = @ptrCast(@alignCast(ptr));
2711
+ return self.backing.vtable.remap(self.backing.ptr, memory, alignment, new_len, ret_addr);
2712
+ }
2713
+
2714
+ fn free(ptr: *anyopaque, memory: []u8, alignment: std.mem.Alignment, ret_addr: usize) void {
2715
+ const self: *ChannelStorageFailingAllocator = @ptrCast(@alignCast(ptr));
2716
+ self.backing.vtable.free(self.backing.ptr, memory, alignment, ret_addr);
2717
+ }
2718
+ };
2719
+
2720
+ fn expectRejected(fx: *DirectFx, key: u64) !void {
2721
+ const msg = fx.takeMsg() orelse return error.TestExpectedMsg;
2722
+ try testing.expect(msg == .event);
2723
+ try testing.expectEqual(key, msg.event.key);
2724
+ try testing.expectEqual(effects_mod.EffectChannelEventKind.rejected, msg.event.kind);
2725
+ }
2726
+
2727
+ test "an alloc-failed open reserves table capacity until its rejection drains" {
2728
+ var fx = DirectFx.init(testing.allocator);
2729
+ defer fx.deinit();
2730
+ fx.executor = .fake;
2731
+ var failing: ChannelStorageFailingAllocator = .{};
2732
+ fx.channel_storage_allocator = failing.allocator();
2733
+
2734
+ // Six live occupancies (6 of the 8 slots).
2735
+ var index: u64 = 0;
2736
+ while (index < 6) : (index += 1) {
2737
+ const handle = fx.openChannel(.{ .key = 200 + index, .on_event = DirectFx.channelMsg(.event) });
2738
+ try testing.expect(handle.shared != null);
2739
+ }
2740
+
2741
+ // The alloc-failed open claims no slot, but its staged
2742
+ // executor-truth `.rejected` reserves one slot of capacity —
2743
+ // replay parks this open in a REAL slot until the terminal feeds.
2744
+ failing.armed = true;
2745
+ const failed = fx.openChannel(.{ .key = 300, .on_event = DirectFx.channelMsg(.event) });
2746
+ try testing.expect(failed.shared == null);
2747
+ try testing.expect(!failing.armed);
2748
+
2749
+ // 6 slots + 1 reservation = 7: a different key still fits...
2750
+ const seventh = fx.openChannel(.{ .key = 301, .on_event = DirectFx.channelMsg(.event) });
2751
+ try testing.expect(seventh.shared != null);
2752
+ // ...but 7 slots + 1 reservation = 8: the next open answers
2753
+ // table-full while the reservation's terminal is pending.
2754
+ const overflow = fx.openChannel(.{ .key = 302, .on_event = DirectFx.channelMsg(.event) });
2755
+ try testing.expect(overflow.shared == null);
2756
+
2757
+ // Deliver the alloc-failed open's terminal: the reservation drains
2758
+ // with it...
2759
+ try expectRejected(&fx, 300);
2760
+ // ...and the key that just answered table-full claims the real 8th
2761
+ // slot — even though its own table-full refusal is still staged
2762
+ // (regenerating refusals never reserve).
2763
+ const eighth = fx.openChannel(.{ .key = 302, .on_event = DirectFx.channelMsg(.event) });
2764
+ try testing.expect(eighth.shared != null);
2765
+ // The earlier table-full refusal's terminal still delivers exactly
2766
+ // once.
2767
+ try expectRejected(&fx, 302);
2768
+ }
2769
+
2770
+ test "an open that cannot allocate the services snapshot refuses as executor truth" {
2771
+ var fx = DirectFx.init(testing.allocator);
2772
+ defer fx.deinit();
2773
+ fx.executor = .fake;
2774
+ var failing: ChannelStorageFailingAllocator = .{};
2775
+ fx.channel_storage_allocator = failing.allocator();
2776
+ const null_platform = try testing.allocator.create(platform_mod.NullPlatform);
2777
+ defer testing.allocator.destroy(null_platform);
2778
+ null_platform.* = platform_mod.NullPlatform.init(.{});
2779
+ const host_platform = null_platform.platform();
2780
+ fx.bindServices(&host_platform.services);
2781
+
2782
+ // The snapshot allocation fails at the open's pre-flight: NO
2783
+ // handle exists — a live channel here could accept posts that
2784
+ // never wake the host (producer wakes stay disarmed until another
2785
+ // publication), so the open refuses up front, the same
2786
+ // executor-truth class as a header/staging start failure.
2787
+ failing.armed = true;
2788
+ const dead = fx.openChannel(.{ .key = 90, .on_event = DirectFx.channelMsg(.event) });
2789
+ try testing.expect(dead.shared == null);
2790
+ try testing.expect(!failing.armed);
2791
+ try testing.expectEqual(PostResult.closed, dead.post("never lands"));
2792
+ try expectRejected(&fx, 90);
2793
+
2794
+ // Storage recovered: the key retired with the rejection, the next
2795
+ // open publishes the snapshot and its posts wake the host.
2796
+ const handle = fx.openChannel(.{ .key = 90, .on_event = DirectFx.channelMsg(.event) });
2797
+ try testing.expect(handle.shared != null);
2798
+ try testing.expect(fx.wake_services.load(.seq_cst) != null);
2799
+ try testing.expectEqual(PostResult.accepted, handle.post("healed"));
2800
+ try testing.expect(null_platform.wake_count.load(.acquire) >= 1);
2801
+ _ = try expectData(&fx, 90, "healed");
2802
+ fx.closeChannel(90);
2803
+ while (fx.takeMsg()) |_| {}
2804
+ }
2805
+
2806
+ test "a failed bind-site snapshot publication closes open channels instead of stranding posts" {
2807
+ // Open-before-bind is the one shape where a live channel can meet
2808
+ // a failed publication (the open-site pre-flight is a no-op while
2809
+ // no services are bound, and `openChannel` cannot refuse what was
2810
+ // committed before the bind existed). A channel left OPEN there
2811
+ // would accept posts that never wake the host — and with no
2812
+ // unrelated loop event, never deliver — so the failed bind closes
2813
+ // it: the accepted backlog flushes, the `.closed` terminal
2814
+ // delivers through the bind's own loop-side wake, and the
2815
+ // producer's next post answers `.closed` (its exit signal).
2816
+ var fx = DirectFx.init(testing.allocator);
2817
+ defer fx.deinit();
2818
+ fx.executor = .fake;
2819
+ var failing: ChannelStorageFailingAllocator = .{};
2820
+ fx.channel_storage_allocator = failing.allocator();
2821
+ const null_platform = try testing.allocator.create(platform_mod.NullPlatform);
2822
+ defer testing.allocator.destroy(null_platform);
2823
+ null_platform.* = platform_mod.NullPlatform.init(.{});
2824
+ const host_platform = null_platform.platform();
2825
+
2826
+ const handle = fx.openChannel(.{ .key = 91, .on_event = DirectFx.channelMsg(.event) });
2827
+ try testing.expect(handle.shared != null);
2828
+ // Accepted before the bind: no services exist to wake, the bind
2829
+ // sweep is what un-strands it.
2830
+ try testing.expectEqual(PostResult.accepted, handle.post("early"));
2831
+
2832
+ // The bind-time publication fails: no snapshot...
2833
+ failing.armed = true;
2834
+ fx.bindServices(&host_platform.services);
2835
+ try testing.expect(fx.wake_services.load(.seq_cst) == null);
2836
+ // ...and the channel is CLOSED, never left accepting posts it
2837
+ // cannot deliver: the producer learns immediately...
2838
+ try testing.expectEqual(PostResult.closed, handle.post("stranded?"));
2839
+ // ...the loop was nudged (the close and the bind sweep)...
2840
+ try testing.expect(null_platform.wake_count.load(.acquire) >= 1);
2841
+ // ...and the pre-bind backlog flushes ahead of the terminal.
2842
+ _ = try expectData(&fx, 91, "early");
2843
+ const closed = fx.takeMsg() orelse return error.TestExpectedMsg;
2844
+ try testing.expectEqual(effects_mod.EffectChannelEventKind.closed, closed.event.kind);
2845
+ try testing.expectEqual(@as(?DirectMsg, null), fx.takeMsg());
2846
+ try testing.expect(fx.channelHandle(91) == null);
2847
+
2848
+ // Storage recovered: a later open retries the publication through
2849
+ // its own pre-flight and posts wake normally.
2850
+ const again = fx.openChannel(.{ .key = 91, .on_event = DirectFx.channelMsg(.event) });
2851
+ try testing.expect(again.shared != null);
2852
+ try testing.expect(fx.wake_services.load(.seq_cst) != null);
2853
+ try testing.expectEqual(PostResult.accepted, again.post("healed"));
2854
+ _ = try expectData(&fx, 91, "healed");
2855
+ fx.closeChannel(91);
2856
+ while (fx.takeMsg()) |_| {}
2857
+ }
2858
+
2859
+ test "regenerating channel refusals do not reserve table capacity" {
2860
+ var fx = DirectFx.init(testing.allocator);
2861
+ defer fx.deinit();
2862
+ fx.executor = .fake;
2863
+
2864
+ // Seven live occupancies.
2865
+ var index: u64 = 0;
2866
+ while (index < 7) : (index += 1) {
2867
+ const handle = fx.openChannel(.{ .key = 400 + index, .on_event = DirectFx.channelMsg(.event) });
2868
+ try testing.expect(handle.shared != null);
2869
+ }
2870
+
2871
+ // Three duplicate-key refusals stage regenerating `.rejected`
2872
+ // terminals. They must NOT reserve: replay re-derives each from
2873
+ // the parked occupancy with no slot held on either side, so the
2874
+ // 8th slot stays claimable while all three are pending.
2875
+ index = 0;
2876
+ while (index < 3) : (index += 1) {
2877
+ const dup = fx.openChannel(.{ .key = 400, .on_event = DirectFx.channelMsg(.event) });
2878
+ try testing.expect(dup.shared == null);
2879
+ }
2880
+ const eighth = fx.openChannel(.{ .key = 500, .on_event = DirectFx.channelMsg(.event) });
2881
+ try testing.expect(eighth.shared != null);
2882
+
2883
+ // The table is honestly full: N table-full refusals (regenerating
2884
+ // too — replay's parked table re-derives them) while full...
2885
+ index = 0;
2886
+ while (index < 3) : (index += 1) {
2887
+ const over = fx.openChannel(.{ .key = 600 + index, .on_event = DirectFx.channelMsg(.event) });
2888
+ try testing.expect(over.shared == null);
2889
+ }
2890
+
2891
+ // ...leave the accounting unchanged: close ONE occupancy, drain
2892
+ // every staged refusal and the closed terminal, and exactly one
2893
+ // slot's worth of capacity is back — not one slot minus phantom
2894
+ // reservations.
2895
+ fx.closeChannel(400);
2896
+ var rejected_count: u32 = 0;
2897
+ var closed_count: u32 = 0;
2898
+ while (fx.takeMsg()) |msg| {
2899
+ switch (msg.event.kind) {
2900
+ .rejected => rejected_count += 1,
2901
+ .closed => closed_count += 1,
2902
+ .data => return error.TestUnexpectedData,
2903
+ }
2904
+ }
2905
+ try testing.expectEqual(@as(u32, 6), rejected_count);
2906
+ try testing.expectEqual(@as(u32, 1), closed_count);
2907
+ const refill = fx.openChannel(.{ .key = 700, .on_event = DirectFx.channelMsg(.event) });
2908
+ try testing.expect(refill.shared != null);
2909
+ const full_again = fx.openChannel(.{ .key = 701, .on_event = DirectFx.channelMsg(.event) });
2910
+ try testing.expect(full_again.shared == null);
2911
+ _ = fx.takeMsg();
2912
+ }
2913
+
2914
+ test "teardown with a reservation pending closes cleanly and discards the stage" {
2915
+ var fx = DirectFx.init(testing.allocator);
2916
+ fx.executor = .fake;
2917
+ var failing: ChannelStorageFailingAllocator = .{};
2918
+ fx.channel_storage_allocator = failing.allocator();
2919
+
2920
+ const live = fx.openChannel(.{ .key = 30, .on_event = DirectFx.channelMsg(.event) });
2921
+ try testing.expect(live.shared != null);
2922
+ failing.armed = true;
2923
+ const failed = fx.openChannel(.{ .key = 31, .on_event = DirectFx.channelMsg(.event) });
2924
+ try testing.expect(failed.shared == null);
2925
+ try testing.expect(fx.hasPending());
2926
+
2927
+ // Teardown with the reservation's terminal still staged: the sweep
2928
+ // closes the live channel and discards the stage — reservation
2929
+ // aboard — with nothing left to deliver or leak.
2930
+ fx.deinit();
2931
+ try testing.expect(!fx.hasPending());
2932
+ try testing.expectEqual(PostResult.closed, live.post("after teardown"));
2933
+ // Idempotent repeat (the teardown ordering contract).
2934
+ fx.deinit();
2935
+ }
2936
+
2937
+ // The record/replay boundary: live capacity accounting must agree with
2938
+ // replay's parked table at every position. Replay parks EVERY open in
2939
+ // a real slot until its journaled terminal feeds — including an
2940
+ // alloc-failed open, whose replay twin never touches the allocator —
2941
+ // so a live table that forgets the alloc-failed open's reservation
2942
+ // accepts a 9th open replay answers with a table-full reject, and the
2943
+ // 9th open's journaled executor-truth terminals have no parked request
2944
+ // to feed (`ReplayEffectDivergence`).
2945
+
2946
+ const capacity_key_base: u64 = 70;
2947
+
2948
+ const CapacityMsg = union(enum) {
2949
+ open: u64,
2950
+ close: u64,
2951
+ event: effects_mod.EffectChannelEvent,
2952
+ };
2953
+
2954
+ const CapacityApp = ui_app_mod.UiApp(ChannelSessionModel, CapacityMsg);
2955
+
2956
+ fn capacityUpdate(model: *ChannelSessionModel, msg: CapacityMsg, fx: *CapacityApp.Effects) void {
2957
+ switch (msg) {
2958
+ .open => |key| _ = fx.openChannel(.{ .key = key, .on_event = CapacityApp.Effects.channelMsg(.event) }),
2959
+ .close => |key| fx.closeChannel(key),
2960
+ .event => |event| model.record(event),
2961
+ }
2962
+ }
2963
+
2964
+ fn capacityView(ui: *CapacityApp.Ui, model: *const ChannelSessionModel) CapacityApp.Ui.Node {
2965
+ return ui.column(.{ .gap = 4, .padding = 8 }, .{
2966
+ ui.text(.{}, ui.fmt("{d} data, {d} closed, {d} rejected", .{ model.data_events, model.closed_events, model.rejected_events })),
2967
+ ui.text(.{}, ui.fmt("digest {x} last {s}", .{ model.payload_digest, model.lastLine() })),
2968
+ });
2969
+ }
2970
+
2971
+ /// "cap.open-N" / "cap.close-N" for a single digit N: key
2972
+ /// `capacity_key_base + N`.
2973
+ fn capacityCommand(name: []const u8) ?CapacityMsg {
2974
+ const open_prefix = "cap.open-";
2975
+ const close_prefix = "cap.close-";
2976
+ if (std.mem.startsWith(u8, name, open_prefix) and name.len == open_prefix.len + 1) {
2977
+ return .{ .open = capacity_key_base + (name[open_prefix.len] - '0') };
2978
+ }
2979
+ if (std.mem.startsWith(u8, name, close_prefix) and name.len == close_prefix.len + 1) {
2980
+ return .{ .close = capacity_key_base + (name[close_prefix.len] - '0') };
2981
+ }
2982
+ return null;
2983
+ }
2984
+
2985
+ fn capacityOptions() CapacityApp.Options {
2986
+ return .{
2987
+ .name = "channel-capacity-demo",
2988
+ .scene = channel_session_scene,
2989
+ .canvas_label = channel_canvas_label,
2990
+ .update_fx = capacityUpdate,
2991
+ .view = capacityView,
2992
+ .on_command = capacityCommand,
2993
+ };
2994
+ }
2995
+
2996
+ fn capacityCommandName(buffer: []u8, comptime verb: []const u8, index: u64) []const u8 {
2997
+ return std.fmt.bufPrint(buffer, "cap." ++ verb ++ "-{d}", .{index}) catch unreachable;
2998
+ }
2999
+
3000
+ /// Record the table-limit boundary reference session: seven live opens,
3001
+ /// one alloc-failed open (a staged executor-truth rejection reserving
3002
+ /// the 8th slot), and — inside the staged window, before any drain —
3003
+ /// the open that would be the table's 9th counting the reservation. It
3004
+ /// must answer table-full LIVE, because replay's parked table is full
3005
+ /// at that position: seven parked opens plus the parked alloc-failed
3006
+ /// one.
3007
+ fn recordCapacitySession(gpa: std.mem.Allocator, buffer: *JournalBuffer) !RecordedChannelSession {
3008
+ const recorder = try std.heap.page_allocator.create(session_record.SessionRecorder);
3009
+ defer std.heap.page_allocator.destroy(recorder);
3010
+ recorder.* = session_record.SessionRecorder.init(buffer.sink());
3011
+ recorder.begin(.{ .platform_name = "test", .app_name = "channel-capacity-demo", .window_width = 400, .window_height = 300 });
3012
+
3013
+ const harness = try core.TestHarness().create(gpa, .{ .size = geometry.SizeF.init(400, 300) });
3014
+ defer harness.destroy(gpa);
3015
+ harness.null_platform.gpu_surfaces = true;
3016
+ harness.runtime.options.session_recorder = recorder;
3017
+
3018
+ const app_state = try gpa.create(CapacityApp);
3019
+ defer gpa.destroy(app_state);
3020
+ app_state.* = CapacityApp.init(std.heap.page_allocator, .{}, capacityOptions());
3021
+ defer app_state.deinit();
3022
+ app_state.effects.executor = .fake;
3023
+ var failing: ChannelStorageFailingAllocator = .{};
3024
+ app_state.effects.channel_storage_allocator = failing.allocator();
3025
+ const app = app_state.app();
3026
+
3027
+ try harness.start(app);
3028
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
3029
+ .label = channel_canvas_label,
3030
+ .size = geometry.SizeF.init(400, 300),
3031
+ .scale_factor = 2,
3032
+ .frame_index = 1,
3033
+ .timestamp_ns = 1_000_000,
3034
+ } });
3035
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
3036
+
3037
+ var name_buffer: [16]u8 = undefined;
3038
+ var index: u64 = 0;
3039
+ while (index < 7) : (index += 1) {
3040
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = capacityCommandName(&name_buffer, "open", index), .window_id = 1 } });
3041
+ }
3042
+ // The alloc-failed open: one staged executor-truth `.rejected`.
3043
+ failing.armed = true;
3044
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = capacityCommandName(&name_buffer, "open", 7), .window_id = 1 } });
3045
+ try testing.expect(!failing.armed);
3046
+ // Inside the staged window — no wake between — the would-be 9th.
3047
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = capacityCommandName(&name_buffer, "open", 8), .window_id = 1 } });
3048
+ // Closing the refused key is a no-op on both sides. (Under the
3049
+ // pre-reservation accounting the 9th open claimed a real slot
3050
+ // here, this close staged a `.closed` terminal, and the journaled
3051
+ // executor-truth terminals had no replay twin to feed.)
3052
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = capacityCommandName(&name_buffer, "close", 8), .window_id = 1 } });
3053
+ try harness.runtime.dispatchPlatformEvent(app, .wake);
3054
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
3055
+
3056
+ // Close the seven live channels: seven executor-truth `.closed`
3057
+ // terminals that feed at replay.
3058
+ index = 0;
3059
+ while (index < 7) : (index += 1) {
3060
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = capacityCommandName(&name_buffer, "close", index), .window_id = 1 } });
3061
+ }
3062
+ try harness.runtime.dispatchPlatformEvent(app, .wake);
3063
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
3064
+
3065
+ recorder.finish();
3066
+ try testing.expect(!recorder.failed);
3067
+ return .{
3068
+ .model = app_state.model,
3069
+ .fingerprint = harness.runtime.sessionStateFingerprint(),
3070
+ };
3071
+ }
3072
+
3073
+ // ---------------- replay ordering: mixed rejection provenance
3074
+ //
3075
+ // One staged window can hold BOTH rejection provenances: an
3076
+ // alloc-failed open's executor-truth `.rejected` (journals `.exited`
3077
+ // and FEEDS at replay) followed by a regenerating refusal (occupied
3078
+ // key, full table — re-derived at the replayed dispatch). Live
3079
+ // delivers them through the pending stage's FIFO in dispatch order.
3080
+ // Replay must deliver the same order even though the executor-truth
3081
+ // terminal arrives through the feed, not the re-run dispatch — the
3082
+ // parked open reserves its ordering slot at dispatch and the fed
3083
+ // refusal reclaims it.
3084
+
3085
+ const mixed_key_base: u64 = 810;
3086
+ const mixed_fail_key: u64 = mixed_key_base + 7;
3087
+ const mixed_full_key: u64 = mixed_key_base + 8;
3088
+ const mixed_chain_key: u64 = mixed_key_base + 9;
3089
+
3090
+ /// When set, a delivered `.rejected` for `mixed_full_key` opens the
3091
+ /// chain channel from inside the handler — the state-divergence probe:
3092
+ /// live, the executor-truth rejection has already drained (its
3093
+ /// reservation released, and under replay its parked slot retired)
3094
+ /// when this handler runs, so the chain open is ACCEPTED on both
3095
+ /// sides; a replay that inverts the two rejections runs this handler
3096
+ /// while the alloc-failed open still parks a slot, and the chain open
3097
+ /// answers table-full instead — a Msg stream and a journal the
3098
+ /// recording never produced.
3099
+ var mixed_chain_enabled = false;
3100
+
3101
+ const MixedRejectionModel = struct {
3102
+ data_events: u32 = 0,
3103
+ closed_events: u32 = 0,
3104
+ rejected_events: u32 = 0,
3105
+ /// Order-sensitive digest folding every delivered event's key and
3106
+ /// kind: two rejections delivered in swapped order diverge here
3107
+ /// even though every per-kind count agrees.
3108
+ order_digest: u64 = 0,
3109
+
3110
+ fn record(model: *MixedRejectionModel, event: effects_mod.EffectChannelEvent) void {
3111
+ switch (event.kind) {
3112
+ .data => model.data_events += 1,
3113
+ .closed => model.closed_events += 1,
3114
+ .rejected => model.rejected_events += 1,
3115
+ }
3116
+ var fold: [9]u8 = undefined;
3117
+ std.mem.writeInt(u64, fold[0..8], event.key, .little);
3118
+ fold[8] = @intFromEnum(event.kind);
3119
+ model.order_digest = std.hash.Wyhash.hash(model.order_digest, &fold);
3120
+ }
3121
+ };
3122
+
3123
+ const MixedMsg = union(enum) {
3124
+ open: u64,
3125
+ close: u64,
3126
+ event: effects_mod.EffectChannelEvent,
3127
+ };
3128
+
3129
+ const MixedApp = ui_app_mod.UiApp(MixedRejectionModel, MixedMsg);
3130
+
3131
+ fn mixedUpdate(model: *MixedRejectionModel, msg: MixedMsg, fx: *MixedApp.Effects) void {
3132
+ switch (msg) {
3133
+ .open => |key| _ = fx.openChannel(.{ .key = key, .on_event = MixedApp.Effects.channelMsg(.event) }),
3134
+ .close => |key| fx.closeChannel(key),
3135
+ .event => |event| {
3136
+ model.record(event);
3137
+ if (mixed_chain_enabled and event.kind == .rejected and event.key == mixed_full_key) {
3138
+ _ = fx.openChannel(.{ .key = mixed_chain_key, .on_event = MixedApp.Effects.channelMsg(.event) });
3139
+ }
3140
+ },
3141
+ }
3142
+ }
3143
+
3144
+ fn mixedView(ui: *MixedApp.Ui, model: *const MixedRejectionModel) MixedApp.Ui.Node {
3145
+ // The order digest rides the semantic tree so the fingerprint
3146
+ // checkpoints pin DELIVERY ORDER, not just per-kind counts.
3147
+ return ui.column(.{ .gap = 4, .padding = 8 }, .{
3148
+ ui.text(.{}, ui.fmt("{d} data, {d} closed, {d} rejected", .{ model.data_events, model.closed_events, model.rejected_events })),
3149
+ ui.text(.{}, ui.fmt("order {x}", .{model.order_digest})),
3150
+ });
3151
+ }
3152
+
3153
+ /// "mixr.open-N" / "mixr.close-N" for a single digit N: key
3154
+ /// `mixed_key_base + N`.
3155
+ fn mixedCommand(name: []const u8) ?MixedMsg {
3156
+ const open_prefix = "mixr.open-";
3157
+ const close_prefix = "mixr.close-";
3158
+ if (std.mem.startsWith(u8, name, open_prefix) and name.len == open_prefix.len + 1) {
3159
+ return .{ .open = mixed_key_base + (name[open_prefix.len] - '0') };
3160
+ }
3161
+ if (std.mem.startsWith(u8, name, close_prefix) and name.len == close_prefix.len + 1) {
3162
+ return .{ .close = mixed_key_base + (name[close_prefix.len] - '0') };
3163
+ }
3164
+ return null;
3165
+ }
3166
+
3167
+ fn mixedOptions() MixedApp.Options {
3168
+ return .{
3169
+ .name = "channel-mixed-rejections",
3170
+ .scene = channel_session_scene,
3171
+ .canvas_label = channel_canvas_label,
3172
+ .update_fx = mixedUpdate,
3173
+ .view = mixedView,
3174
+ .on_command = mixedCommand,
3175
+ };
3176
+ }
3177
+
3178
+ const RecordedMixedSession = struct {
3179
+ model: MixedRejectionModel,
3180
+ fingerprint: u64,
3181
+ };
3182
+
3183
+ fn mixedHarnessStart(harness: *core.TestHarness(), app: core.App) !void {
3184
+ try harness.start(app);
3185
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
3186
+ .label = channel_canvas_label,
3187
+ .size = geometry.SizeF.init(400, 300),
3188
+ .scale_factor = 2,
3189
+ .frame_index = 1,
3190
+ .timestamp_ns = 1_000_000,
3191
+ } });
3192
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
3193
+ }
3194
+
3195
+ /// Record the mixed-provenance reference session: seven live opens,
3196
+ /// one alloc-failed open (executor truth, feeds at replay), and —
3197
+ /// inside the same staged window — one table-full open (regenerating,
3198
+ /// re-derived at replay). Live delivers the two rejections in
3199
+ /// dispatch order: alloc-failed first, table-full second.
3200
+ fn recordMixedSession(gpa: std.mem.Allocator, buffer: *JournalBuffer, chain: bool) !RecordedMixedSession {
3201
+ const recorder = try std.heap.page_allocator.create(session_record.SessionRecorder);
3202
+ defer std.heap.page_allocator.destroy(recorder);
3203
+ recorder.* = session_record.SessionRecorder.init(buffer.sink());
3204
+ recorder.begin(.{ .platform_name = "test", .app_name = "channel-mixed-rejections", .window_width = 400, .window_height = 300 });
3205
+
3206
+ const harness = try core.TestHarness().create(gpa, .{ .size = geometry.SizeF.init(400, 300) });
3207
+ defer harness.destroy(gpa);
3208
+ harness.null_platform.gpu_surfaces = true;
3209
+ harness.runtime.options.session_recorder = recorder;
3210
+
3211
+ const app_state = try gpa.create(MixedApp);
3212
+ defer gpa.destroy(app_state);
3213
+ app_state.* = MixedApp.init(std.heap.page_allocator, .{}, mixedOptions());
3214
+ defer app_state.deinit();
3215
+ app_state.effects.executor = .fake;
3216
+ var failing: ChannelStorageFailingAllocator = .{};
3217
+ app_state.effects.channel_storage_allocator = failing.allocator();
3218
+ const app = app_state.app();
3219
+
3220
+ try mixedHarnessStart(harness, app);
3221
+
3222
+ var name_buffer: [16]u8 = undefined;
3223
+ var index: u64 = 0;
3224
+ while (index < 7) : (index += 1) {
3225
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = mixedCommandName(&name_buffer, "open", index), .window_id = 1 } });
3226
+ }
3227
+ // The alloc-failed open: executor truth, staged at dispatch.
3228
+ failing.armed = true;
3229
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = mixedCommandName(&name_buffer, "open", 7), .window_id = 1 } });
3230
+ try testing.expect(!failing.armed);
3231
+ // The table-full open, in the same staged window: 7 slots + 1
3232
+ // reservation exhaust the table, so this refusal is regenerating.
3233
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = mixedCommandName(&name_buffer, "open", 8), .window_id = 1 } });
3234
+ try harness.runtime.dispatchPlatformEvent(app, .wake);
3235
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
3236
+ try testing.expectEqual(@as(u32, 2), app_state.model.rejected_events);
3237
+
3238
+ // Close the live channels (and the chain channel when the second
3239
+ // rejection's handler opened it).
3240
+ index = 0;
3241
+ while (index < 7) : (index += 1) {
3242
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = mixedCommandName(&name_buffer, "close", index), .window_id = 1 } });
3243
+ }
3244
+ if (chain) {
3245
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = mixedCommandName(&name_buffer, "close", 9), .window_id = 1 } });
3246
+ }
3247
+ try harness.runtime.dispatchPlatformEvent(app, .wake);
3248
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
3249
+
3250
+ recorder.finish();
3251
+ try testing.expect(!recorder.failed);
3252
+ return .{
3253
+ .model = app_state.model,
3254
+ .fingerprint = harness.runtime.sessionStateFingerprint(),
3255
+ };
3256
+ }
3257
+
3258
+ fn mixedCommandName(buffer: []u8, comptime verb: []const u8, index: u64) []const u8 {
3259
+ return std.fmt.bufPrint(buffer, "mixr." ++ verb ++ "-{d}", .{index}) catch unreachable;
3260
+ }
3261
+
3262
+ fn replayMixedSession(gpa: std.mem.Allocator, buffer: *JournalBuffer, app_state: *MixedApp, harness: *core.TestHarness()) !session_replay.ReplayReport {
3263
+ harness.null_platform.gpu_surfaces = true;
3264
+ app_state.* = MixedApp.init(std.heap.page_allocator, .{}, mixedOptions());
3265
+ _ = gpa;
3266
+ return session_replay.replaySession(&harness.runtime, app_state.app(), buffer.journalBytes(), .{
3267
+ .verify = true,
3268
+ .require_same_platform = false,
3269
+ });
3270
+ }
3271
+
3272
+ test "mixed executor-truth and regenerating channel rejections replay in live delivery order" {
3273
+ const gpa = testing.allocator;
3274
+ const buffer = try std.heap.page_allocator.create(JournalBuffer);
3275
+ defer std.heap.page_allocator.destroy(buffer);
3276
+ buffer.len = 0;
3277
+ mixed_chain_enabled = false;
3278
+
3279
+ const recorded = try recordMixedSession(gpa, buffer, false);
3280
+ // Live delivery order pinned independently: the alloc-failed open's
3281
+ // rejection first (staged at its dispatch), the table-full open's
3282
+ // second — the pending stage's FIFO.
3283
+ var expected: MixedRejectionModel = .{};
3284
+ expected.record(.{ .key = mixed_fail_key, .kind = .rejected });
3285
+ expected.record(.{ .key = mixed_full_key, .kind = .rejected });
3286
+ var close_index: u64 = 0;
3287
+ while (close_index < 7) : (close_index += 1) {
3288
+ expected.record(.{ .key = mixed_key_base + close_index, .kind = .closed });
3289
+ }
3290
+ try testing.expectEqual(expected.order_digest, recorded.model.order_digest);
3291
+ try testing.expectEqual(@as(u32, 7), recorded.model.closed_events);
3292
+
3293
+ const harness = try core.TestHarness().create(gpa, .{ .size = geometry.SizeF.init(400, 300) });
3294
+ defer harness.destroy(gpa);
3295
+ const app_state = try gpa.create(MixedApp);
3296
+ defer gpa.destroy(app_state);
3297
+ const report = try replayMixedSession(gpa, buffer, app_state, harness);
3298
+ defer app_state.deinit();
3299
+ try testing.expect(report.ok());
3300
+ try testing.expect(report.checkpoints_verified > 0);
3301
+ // The alloc-failed rejection and seven closed terminals feed; the
3302
+ // table-full rejection regenerates.
3303
+ try testing.expectEqual(@as(u64, 8), report.effects_fed);
3304
+ try testing.expectEqual(@as(u64, 1), report.effects_skipped);
3305
+ try testing.expectEqualDeep(recorded.model, app_state.model);
3306
+ try testing.expectEqual(recorded.fingerprint, harness.runtime.sessionStateFingerprint());
3307
+ }
3308
+
3309
+ /// The valid reversed mixed ordering. A table-full refusal cannot
3310
+ /// precede an executor-truth one inside a single staged window — the
3311
+ /// table's idle-minus-reservations margin only ever shrinks as the
3312
+ /// window's opens claim slots and executor-truth refusals add
3313
+ /// reservations, and an alloc-fail needs the margin positive while
3314
+ /// table-full needs it non-positive — so the regenerating-first shape
3315
+ /// uses the OTHER regenerating refusal, the duplicate key.
3316
+ fn recordReversedMixedSession(gpa: std.mem.Allocator, buffer: *JournalBuffer) !RecordedMixedSession {
3317
+ const recorder = try std.heap.page_allocator.create(session_record.SessionRecorder);
3318
+ defer std.heap.page_allocator.destroy(recorder);
3319
+ recorder.* = session_record.SessionRecorder.init(buffer.sink());
3320
+ recorder.begin(.{ .platform_name = "test", .app_name = "channel-mixed-rejections", .window_width = 400, .window_height = 300 });
3321
+
3322
+ const harness = try core.TestHarness().create(gpa, .{ .size = geometry.SizeF.init(400, 300) });
3323
+ defer harness.destroy(gpa);
3324
+ harness.null_platform.gpu_surfaces = true;
3325
+ harness.runtime.options.session_recorder = recorder;
3326
+
3327
+ const app_state = try gpa.create(MixedApp);
3328
+ defer gpa.destroy(app_state);
3329
+ app_state.* = MixedApp.init(std.heap.page_allocator, .{}, mixedOptions());
3330
+ defer app_state.deinit();
3331
+ app_state.effects.executor = .fake;
3332
+ var failing: ChannelStorageFailingAllocator = .{};
3333
+ app_state.effects.channel_storage_allocator = failing.allocator();
3334
+ const app = app_state.app();
3335
+
3336
+ try mixedHarnessStart(harness, app);
3337
+
3338
+ var name_buffer: [16]u8 = undefined;
3339
+ // One live open, then its duplicate: the regenerating refusal
3340
+ // stages FIRST.
3341
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = mixedCommandName(&name_buffer, "open", 0), .window_id = 1 } });
3342
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = mixedCommandName(&name_buffer, "open", 0), .window_id = 1 } });
3343
+ // Then the alloc-failed open: executor truth stages SECOND.
3344
+ failing.armed = true;
3345
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = mixedCommandName(&name_buffer, "open", 7), .window_id = 1 } });
3346
+ try testing.expect(!failing.armed);
3347
+ try harness.runtime.dispatchPlatformEvent(app, .wake);
3348
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
3349
+ try testing.expectEqual(@as(u32, 2), app_state.model.rejected_events);
3350
+
3351
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = mixedCommandName(&name_buffer, "close", 0), .window_id = 1 } });
3352
+ try harness.runtime.dispatchPlatformEvent(app, .wake);
3353
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
3354
+
3355
+ recorder.finish();
3356
+ try testing.expect(!recorder.failed);
3357
+ return .{
3358
+ .model = app_state.model,
3359
+ .fingerprint = harness.runtime.sessionStateFingerprint(),
3360
+ };
3361
+ }
3362
+
3363
+ test "a regenerating rejection recorded ahead of an executor-truth one keeps its lead at replay" {
3364
+ const gpa = testing.allocator;
3365
+ const buffer = try std.heap.page_allocator.create(JournalBuffer);
3366
+ defer std.heap.page_allocator.destroy(buffer);
3367
+ buffer.len = 0;
3368
+ mixed_chain_enabled = false;
3369
+
3370
+ const recorded = try recordReversedMixedSession(gpa, buffer);
3371
+ var expected: MixedRejectionModel = .{};
3372
+ expected.record(.{ .key = mixed_key_base, .kind = .rejected });
3373
+ expected.record(.{ .key = mixed_fail_key, .kind = .rejected });
3374
+ expected.record(.{ .key = mixed_key_base, .kind = .closed });
3375
+ try testing.expectEqual(expected.order_digest, recorded.model.order_digest);
3376
+
3377
+ const harness = try core.TestHarness().create(gpa, .{ .size = geometry.SizeF.init(400, 300) });
3378
+ defer harness.destroy(gpa);
3379
+ const app_state = try gpa.create(MixedApp);
3380
+ defer gpa.destroy(app_state);
3381
+ const report = try replayMixedSession(gpa, buffer, app_state, harness);
3382
+ defer app_state.deinit();
3383
+ try testing.expect(report.ok());
3384
+ try testing.expect(report.checkpoints_verified > 0);
3385
+ // The alloc-failed rejection and one closed terminal feed; the
3386
+ // duplicate-key rejection regenerates.
3387
+ try testing.expectEqual(@as(u64, 2), report.effects_fed);
3388
+ try testing.expectEqual(@as(u64, 1), report.effects_skipped);
3389
+ try testing.expectEqualDeep(recorded.model, app_state.model);
3390
+ try testing.expectEqual(recorded.fingerprint, harness.runtime.sessionStateFingerprint());
3391
+ }
3392
+
3393
+ test "a mixed session whose second rejection handler opens a third channel replays without table divergence" {
3394
+ const gpa = testing.allocator;
3395
+ const buffer = try std.heap.page_allocator.create(JournalBuffer);
3396
+ defer std.heap.page_allocator.destroy(buffer);
3397
+ buffer.len = 0;
3398
+ mixed_chain_enabled = true;
3399
+ defer mixed_chain_enabled = false;
3400
+
3401
+ // Live: the table-full rejection's handler runs AFTER the
3402
+ // alloc-failed rejection drained (its reservation released), so the
3403
+ // chain open claims the freed capacity and is accepted.
3404
+ const recorded = try recordMixedSession(gpa, buffer, true);
3405
+ try testing.expectEqual(@as(u32, 2), recorded.model.rejected_events);
3406
+ try testing.expectEqual(@as(u32, 8), recorded.model.closed_events);
3407
+
3408
+ // Replay must run the same handler against the same table state:
3409
+ // the fed executor-truth rejection retires its parked slot BEFORE
3410
+ // the regenerated table-full rejection delivers, so the chain open
3411
+ // parks in the freed slot and its journaled `.closed` has a twin
3412
+ // to feed. An inverted replay opens the chain channel against a
3413
+ // full parked table and diverges.
3414
+ const harness = try core.TestHarness().create(gpa, .{ .size = geometry.SizeF.init(400, 300) });
3415
+ defer harness.destroy(gpa);
3416
+ const app_state = try gpa.create(MixedApp);
3417
+ defer gpa.destroy(app_state);
3418
+ const report = try replayMixedSession(gpa, buffer, app_state, harness);
3419
+ defer app_state.deinit();
3420
+ try testing.expect(report.ok());
3421
+ try testing.expect(report.checkpoints_verified > 0);
3422
+ // The alloc-failed rejection and eight closed terminals feed; the
3423
+ // table-full rejection regenerates.
3424
+ try testing.expectEqual(@as(u64, 9), report.effects_fed);
3425
+ try testing.expectEqual(@as(u64, 1), report.effects_skipped);
3426
+ try testing.expectEqualDeep(recorded.model, app_state.model);
3427
+ try testing.expectEqual(recorded.fingerprint, harness.runtime.sessionStateFingerprint());
3428
+ }
3429
+
3430
+ test "live table capacity counts the alloc-failed open's reservation so replay agrees at the boundary" {
3431
+ const gpa = testing.allocator;
3432
+ const buffer = try std.heap.page_allocator.create(JournalBuffer);
3433
+ defer std.heap.page_allocator.destroy(buffer);
3434
+ buffer.len = 0;
3435
+
3436
+ const recorded = try recordCapacitySession(gpa, buffer);
3437
+
3438
+ const harness = try core.TestHarness().create(gpa, .{ .size = geometry.SizeF.init(400, 300) });
3439
+ defer harness.destroy(gpa);
3440
+ harness.null_platform.gpu_surfaces = true;
3441
+ const app_state = try gpa.create(CapacityApp);
3442
+ defer gpa.destroy(app_state);
3443
+ app_state.* = CapacityApp.init(std.heap.page_allocator, .{}, capacityOptions());
3444
+ defer app_state.deinit();
3445
+
3446
+ // Replay must agree at every position: the alloc-failed open's
3447
+ // `.rejected` feeds and retires its parked slot, the 9th open's
3448
+ // table-full refusal regenerates against the parked table, and the
3449
+ // seven `.closed` terminals feed.
3450
+ const report = try session_replay.replaySession(&harness.runtime, app_state.app(), buffer.journalBytes(), .{
3451
+ .verify = true,
3452
+ .require_same_platform = false,
3453
+ });
3454
+ try testing.expect(report.ok());
3455
+ try testing.expect(report.checkpoints_verified > 0);
3456
+ try testing.expectEqual(@as(u64, 8), report.effects_fed);
3457
+ try testing.expectEqual(@as(u64, 1), report.effects_skipped);
3458
+ try testing.expectEqualDeep(recorded.model, app_state.model);
3459
+ try testing.expectEqual(recorded.fingerprint, harness.runtime.sessionStateFingerprint());
3460
+
3461
+ // The recorded shape itself: the alloc-failed open's rejection and
3462
+ // the boundary open's LIVE table-full rejection, seven closes, no
3463
+ // data — the 9th never opened on either side.
3464
+ try testing.expectEqual(@as(u32, 2), recorded.model.rejected_events);
3465
+ try testing.expectEqual(@as(u32, 7), recorded.model.closed_events);
3466
+ try testing.expectEqual(@as(u32, 0), recorded.model.data_events);
3467
+ }
3468
+
3469
+ // ------------------------------------------------ live-feed restriction
3470
+
3471
+ test "feeding a terminal into a live channel answers ChannelLiveFeed instead of racing the producer" {
3472
+ var fx = DirectFx.init(testing.allocator);
3473
+ defer fx.deinit();
3474
+ fx.executor = .fake;
3475
+
3476
+ // Pre-restriction this interleaving destroyed a staged post and
3477
+ // stranded its pending count forever: feed a terminal into the
3478
+ // LIVE channel, land an accepted post AFTER the drain snapshot but
3479
+ // BEFORE the queued terminal processes — the pass skips the post
3480
+ // (stamped past the boundary), the terminal's delivery retires the
3481
+ // slot and destroys the staging FIFO with the post inside, and
3482
+ // `hasPending` reads true forever. The feed seam now refuses the
3483
+ // live target outright.
3484
+ const handle = fx.openChannel(.{ .key = 23, .on_event = DirectFx.channelMsg(.event) });
3485
+ try testing.expectError(error.ChannelLiveFeed, fx.feedChannelEvent(23, .closed, "", 0, 0));
3486
+ try testing.expectError(error.ChannelLiveFeed, fx.feedChannelEvent(23, .rejected, "", 0, 0));
3487
+
3488
+ // The occupancy is untouched by the refusal: posts still land and
3489
+ // the ordinary lifecycle completes with an honest pending count.
3490
+ try testing.expectEqual(PostResult.accepted, handle.post("still live"));
3491
+ _ = try expectData(&fx, 23, "still live");
3492
+
3493
+ // A `.closing` occupancy is equally live — its armed close marker
3494
+ // is counted, so a fed terminal would strand that count too.
3495
+ try testing.expectEqual(PostResult.accepted, handle.post("flush me"));
3496
+ fx.closeChannel(23);
3497
+ try testing.expectError(error.ChannelLiveFeed, fx.feedChannelEvent(23, .closed, "", 0, 0));
3498
+ while (fx.takeMsg()) |_| {}
3499
+ try testing.expect(!fx.hasPending());
3500
+ }
3501
+
3502
+ test "teardown with staged entries reconciles the pending count: hasPending never permanently lies" {
3503
+ var fx = DirectFx.init(testing.allocator);
3504
+ fx.executor = .fake;
3505
+
3506
+ const handle = fx.openChannel(.{ .key = 29, .on_event = DirectFx.channelMsg(.event) });
3507
+ try testing.expectEqual(PostResult.accepted, handle.post("staged at teardown"));
3508
+ try testing.expectEqual(PostResult.accepted, handle.post("also staged"));
3509
+ fx.closeChannel(29);
3510
+ try testing.expect(fx.hasPending());
3511
+
3512
+ // Teardown discards the staged backlog AND the close marker (the
3513
+ // families' no-Msg teardown discipline) — the count reconciles to
3514
+ // zero with them, so a caller polling `hasPending` after teardown
3515
+ // reads idle, never a permanent busy signal.
3516
+ fx.deinit();
3517
+ try testing.expect(!fx.hasPending());
3518
+ try testing.expectEqual(PostResult.closed, handle.post("after teardown"));
3519
+ }