@native-sdk/cli 0.8.4 → 0.9.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 (146) hide show
  1. package/build/app.zig +859 -62
  2. package/build.zig +543 -13
  3. package/build.zig.zon +1 -0
  4. package/native-sdk.d.ts +2 -0
  5. package/package.json +12 -11
  6. package/packages/core/compile-surface/core.ts +365 -2
  7. package/packages/core/package-lock.json +11 -11
  8. package/packages/core/package.json +2 -2
  9. package/packages/core/scripts/compiler_typecheck.mjs +116 -15
  10. package/packages/core/scripts/gen_service_surface.mjs +268 -0
  11. package/packages/core/scripts/npm_static_spike.mjs +64 -0
  12. package/packages/core/scripts/run_external_core_compiler.mjs +77 -6
  13. package/packages/core/scripts/run_external_service_compiler.mjs +240 -0
  14. package/packages/core/scripts/stage_external_core.mjs +9 -1
  15. package/packages/core/scripts/stage_external_services.mjs +172 -0
  16. package/packages/core/scripts/surface_manifest_diff.mjs +253 -0
  17. package/packages/core/scripts/vendor_service_packages.mjs +189 -0
  18. package/packages/core/sdk/core.d.ts +149 -0
  19. package/packages/core/sdk/core.ts +529 -12
  20. package/packages/core/sdk/events.d.ts +36 -0
  21. package/packages/core/sdk/events.ts +57 -0
  22. package/packages/core/src/checker.ts +468 -15
  23. package/packages/core/src/cli.ts +143 -3
  24. package/packages/core/src/contract.ts +26 -5
  25. package/packages/core/src/devhost.ts +1847 -16
  26. package/packages/core/src/devhost_journal.mjs +181 -0
  27. package/packages/core/src/devhost_resolver.mjs +17 -1
  28. package/packages/core/src/devhost_service_worker.mjs +90 -0
  29. package/packages/core/src/diagnostics.ts +82 -16
  30. package/packages/core/src/frontend.ts +204 -34
  31. package/packages/core/src/modules.ts +129 -80
  32. package/packages/core/src/service_contract.ts +597 -0
  33. package/packages/core/src/sqlite_cli.ts +93 -0
  34. package/packages/core/src/sqlite_codegen.ts +806 -0
  35. package/packages/core/src/sqlite_runtime_policy.ts +364 -0
  36. package/packages/core/src/typed_ast.ts +36 -8
  37. package/skill-data/core/references/project-anatomy.md +1 -1
  38. package/skill-data/native-ui/SKILL.md +47 -0
  39. package/skill-data/ts-core/SKILL.md +80 -31
  40. package/skill-data/ts-services/SKILL.md +126 -0
  41. package/skill-data/ts-services/references/service-surface.md +603 -0
  42. package/skill-data/zig/SKILL.md +1 -1
  43. package/skills/native-sdk/SKILL.md +1 -1
  44. package/src/app_runner/no_migrations.zig +3 -0
  45. package/src/app_runner/no_services.zig +20 -0
  46. package/src/app_runner/root.zig +104 -4
  47. package/src/app_runner/ts_core_main.zig +249 -8
  48. package/src/automation/snapshot.zig +23 -5
  49. package/src/embed/app_exports.zig +11 -1
  50. package/src/embed/c_api.zig +48 -2
  51. package/src/embed/conversions.zig +4 -5
  52. package/src/embed/host.zig +109 -1
  53. package/src/embed/root.zig +7 -0
  54. package/src/embed/tests.zig +213 -0
  55. package/src/embed/types.zig +51 -0
  56. package/src/embed/ui_host.zig +119 -5
  57. package/src/platform/android/NativeSdkActivity.java +131 -0
  58. package/src/platform/android/android_host.c +182 -1
  59. package/src/platform/android/native_sdk_app.h +17 -0
  60. package/src/platform/ios/native_sdk_app.h +17 -0
  61. package/src/platform/ios/uikit_host.m +115 -0
  62. package/src/platform/linux/cef_host.cpp +1 -1
  63. package/src/platform/linux/gtk_host.c +89 -17
  64. package/src/platform/linux/gtk_host.h +3 -0
  65. package/src/platform/linux/root.zig +40 -18
  66. package/src/platform/macos/appkit_host.h +16 -3
  67. package/src/platform/macos/appkit_host.m +536 -36
  68. package/src/platform/macos/cef_host.mm +248 -36
  69. package/src/platform/macos/root.zig +244 -34
  70. package/src/platform/null_platform.zig +223 -19
  71. package/src/platform/null_platform_tests.zig +74 -0
  72. package/src/platform/root.zig +9 -0
  73. package/src/platform/types.zig +179 -15
  74. package/src/platform/windows/root.zig +187 -21
  75. package/src/platform/windows/webview2_host.cpp +293 -46
  76. package/src/primitives/app_manifest/comptime_scene.zig +2 -0
  77. package/src/primitives/app_manifest/root.zig +4 -0
  78. package/src/primitives/app_manifest/tests.zig +3 -0
  79. package/src/primitives/app_manifest/types.zig +32 -0
  80. package/src/primitives/app_manifest/validation.zig +19 -1
  81. package/src/root.zig +46 -0
  82. package/src/runtime/api.zig +11 -0
  83. package/src/runtime/automation_snapshot.zig +4 -0
  84. package/src/runtime/bridge_permission_tests.zig +23 -2
  85. package/src/runtime/bridge_responses.zig +3 -1
  86. package/src/runtime/canvas_frame.zig +18 -11
  87. package/src/runtime/canvas_frame_animation_tests.zig +4 -0
  88. package/src/runtime/clock.zig +13 -1
  89. package/src/runtime/core.zig +133 -1
  90. package/src/runtime/credentials_store.zig +115 -0
  91. package/src/runtime/effects.zig +2295 -113
  92. package/src/runtime/effects_credentials_tests.zig +332 -0
  93. package/src/runtime/effects_host_tests.zig +208 -1
  94. package/src/runtime/effects_relational_tests.zig +314 -0
  95. package/src/runtime/effects_store_tests.zig +211 -0
  96. package/src/runtime/flow.zig +14 -1
  97. package/src/runtime/gpu_surface_events.zig +6 -1
  98. package/src/runtime/native_command_event_tests.zig +42 -0
  99. package/src/runtime/persist_store.zig +666 -0
  100. package/src/runtime/record_store.zig +788 -0
  101. package/src/runtime/relational_store.zig +854 -0
  102. package/src/runtime/root.zig +49 -0
  103. package/src/runtime/runtime_event_tests.zig +70 -0
  104. package/src/runtime/service_host.zig +711 -0
  105. package/src/runtime/service_pool.zig +1314 -0
  106. package/src/runtime/session_blobs.zig +1 -1
  107. package/src/runtime/session_journal.zig +102 -0
  108. package/src/runtime/session_record.zig +177 -0
  109. package/src/runtime/session_replay.zig +109 -4
  110. package/src/runtime/shell_layout.zig +1 -0
  111. package/src/runtime/shell_layout_tests.zig +120 -0
  112. package/src/runtime/sqlite_engine.zig +474 -0
  113. package/src/runtime/state.zig +6 -0
  114. package/src/runtime/system_services.zig +49 -10
  115. package/src/runtime/tests.zig +4 -0
  116. package/src/runtime/ts_core_host.zig +788 -86
  117. package/src/runtime/ts_core_host_tests.zig +231 -11
  118. package/src/runtime/ts_ui_app.zig +499 -1
  119. package/src/runtime/ui_app.zig +142 -16
  120. package/src/runtime/ui_app_tests.zig +155 -5
  121. package/src/runtime/validation.zig +22 -0
  122. package/src/runtime/view.zig +9 -0
  123. package/src/runtime/window_storage.zig +1 -0
  124. package/src/runtime/window_view_runtime.zig +2 -3
  125. package/src/runtime/window_views.zig +19 -0
  126. package/src/tooling/android.zig +21 -16
  127. package/src/tooling/db.zig +160 -0
  128. package/src/tooling/ios.zig +7 -1
  129. package/src/tooling/manifest.zig +214 -2
  130. package/src/tooling/package.zig +116 -0
  131. package/src/tooling/raw_manifest.zig +30 -0
  132. package/src/tooling/root.zig +1 -0
  133. package/src/tooling/templates.zig +161 -4
  134. package/src/tooling/ts_core.zig +283 -17
  135. package/src/tooling/verbs.zig +7 -0
  136. package/third_party/sqlite/README.md +13 -0
  137. package/third_party/sqlite/sqlite3.c +269649 -0
  138. package/third_party/sqlite/sqlite3.h +14349 -0
  139. package/tools/corewire/core_abi.zig +14 -2
  140. package/tools/corewire/emit.zig +98 -29
  141. package/tools/corewire/emit_facade.zig +378 -23
  142. package/tools/corewire/emit_profile.zig +6 -2
  143. package/tools/corewire/emit_service.zig +924 -0
  144. package/tools/corewire/main.zig +122 -0
  145. package/tools/corewire/service_contract.zig +250 -0
  146. package/tools/corewire/sidecar.zig +26 -15
@@ -0,0 +1,1314 @@
1
+ //! In-process TypeScript service carrier.
2
+ //!
3
+ //! The service modules compile into a library-mode archive (thread-instanced,
4
+ //! runtime-localized) that links into the app binary; this pool owns a small
5
+ //! fixed set of worker threads, and each worker thread initializes and owns
6
+ //! one complete archive instance for its whole lifetime. HostCallBinding
7
+ //! callbacks only copy/enqueue on the loop thread; completions are polled
8
+ //! back onto that thread by Effects, so the journaling/replay boundary is
9
+ //! byte-identical to the child-process carrier's. Nothing starts before the
10
+ //! first real request, so replay never spawns a pool thread and never enters
11
+ //! the archive.
12
+ //!
13
+ //! Dispatch and ordering:
14
+ //! - Requests queue centrally; a worker takes the oldest request whose key
15
+ //! has no earlier queued twin and no active twin. Same-key requests
16
+ //! therefore run strictly FIFO and never concurrently; different keys run
17
+ //! in parallel across instances. A poisoned instance retains its key until
18
+ //! its detached dispatch physically returns, so replacement work cannot
19
+ //! overlap side effects from an operation that ignored cancellation.
20
+ //! - Fire-and-forget sends share key 0 and serialize among themselves.
21
+ //!
22
+ //! Cancellation and deadlines ride the same cooperative token the child
23
+ //! carrier publishes: a marker file at the request's cancellation path,
24
+ //! polled by the generated service code. A deadline (or an app cancel)
25
+ //! publishes the marker and grants `cooperative_cancel_grace_ms`; an
26
+ //! operation that returns inside the grace keeps its instance warm, exactly
27
+ //! like the child process staying alive after a cooperative unwind. There is
28
+ //! no process to kill past the grace, so an operation that ignores its token
29
+ //! POISONS its instance instead: the worker thread is abandoned (detached;
30
+ //! its instance memory is reclaimed only at process exit), the request
31
+ //! routes `kind: "timeout"`, and a replacement worker with a fresh instance
32
+ //! joins the pool. A detected runtime trap routes `kind: "service_trap"` the
33
+ //! same way: the per-instance panic sink stages the error, poisons exactly
34
+ //! the instance it fired in, parks the trapped thread, and the pool spawns a
35
+ //! replacement — other instances keep answering throughout. Hardware faults
36
+ //! (stack overflow above all) are process-wide on any in-process carrier;
37
+ //! the child-process carrier remains the fully isolated option.
38
+ //!
39
+ //! Streaming operations emit interim chunks through a per-request relay
40
+ //! file ([len u32 LE][bytes] frames appended by the generated facade); the
41
+ //! pool's supervisor thread tails the file while the operation runs and
42
+ //! posts each frame to the request's external channel, so chunks stay live
43
+ //! mid-operation and always precede the typed terminal.
44
+
45
+ const std = @import("std");
46
+ const builtin = @import("builtin");
47
+ const effects = @import("effects.zig");
48
+ const platform = @import("../platform/root.zig");
49
+ const service_host = @import("service_host.zig");
50
+
51
+ const transport_error = "{\"kind\":\"service_host\",\"message\":\"service archive rejected the request\"}";
52
+ const timeout_error = "{\"kind\":\"timeout\",\"message\":\"service request timed out\"}";
53
+
54
+ /// Same budget discipline as the child carrier: bound the whole request
55
+ /// from admission through queueing and dispatch.
56
+ pub const default_request_timeout_ms: u32 = service_host.default_request_timeout_ms;
57
+ pub const cooperative_cancel_grace_ms: u32 = service_host.cooperative_cancel_grace_ms;
58
+
59
+ /// Ceiling on configured pool width; the default stays far below it.
60
+ pub const max_pool_workers: usize = 16;
61
+
62
+ /// The default pool width: enough parallelism for independent keys without
63
+ /// paying an instance heap per core on wide machines.
64
+ pub fn defaultWorkerCount() usize {
65
+ const cores = std.Thread.getCpuCount() catch 1;
66
+ return @max(1, @min(4, cores));
67
+ }
68
+
69
+ /// How often the supervisor tails active stream-relay files.
70
+ const stream_poll_ms: u32 = 2;
71
+
72
+ /// Detached dispatches expose one atomic returned flag. The supervisor polls
73
+ /// it at the same low cadence as stream relays so it can release the key and
74
+ /// the request resources without letting the abandoned thread touch the pool.
75
+ const abandoned_poll_ms: u32 = 2;
76
+
77
+ pub const PoolOptions = struct {
78
+ /// Worker-thread count; null resolves `defaultWorkerCount()` on first use.
79
+ max_workers: ?usize = null,
80
+ };
81
+
82
+ /// Test-only synchronization at the completion ownership handoff. Production
83
+ /// pool layouts contain no pointer to this barrier (`builtin.is_test` gates
84
+ /// the field); the end-to-end suite uses it to make grace-boundary races
85
+ /// deterministic instead of depending on scheduler timing.
86
+ pub const TestCompletionBarrier = struct {
87
+ claimed: std.Io.Event = .unset,
88
+ release: std.Io.Event = .unset,
89
+ };
90
+
91
+ pub fn ServicePool(comptime Registry: type) type {
92
+ return struct {
93
+ const Self = @This();
94
+
95
+ const abi = struct {
96
+ const prefix = Registry.inproc_symbol_prefix;
97
+ const PanicSinkFn = *const fn (?*anyopaque, [*]const u8, usize, u64) callconv(.c) void;
98
+ const init_fn = @extern(*const fn () callconv(.c) void, .{ .name = prefix ++ "init" });
99
+ const set_panic_sink_fn = @extern(*const fn (PanicSinkFn, ?*anyopaque) callconv(.c) void, .{ .name = prefix ++ "set_panic_sink" });
100
+ const collect_fn = @extern(*const fn () callconv(.c) void, .{ .name = prefix ++ "collect" });
101
+ const dispatch_fn = @extern(*const fn (u32, [*]const u8, usize, [*]const u8, usize, [*]const u8, usize, *[*]const u8, *usize) callconv(.c) void, .{ .name = prefix ++ "dispatch" });
102
+ const contract_fingerprint_fn = @extern(*const fn (*[*]const u8, *usize) callconv(.c) void, .{ .name = prefix ++ "contract_fingerprint" });
103
+ };
104
+
105
+ const Request = struct {
106
+ key: u64,
107
+ request_id: u32,
108
+ operation: u16,
109
+ payload: []u8,
110
+ answer: bool,
111
+ deadline: std.Io.Clock.Timestamp,
112
+ channel: ?effects.ChannelHandle,
113
+ };
114
+ const Result = struct { key: u64, ok: bool, bytes: []u8 };
115
+
116
+ const Stream = struct {
117
+ path: []u8,
118
+ channel: effects.ChannelHandle,
119
+ file: ?std.Io.File = null,
120
+ /// Partial-frame carry between supervisor polls.
121
+ pending: std.ArrayList(u8) = .empty,
122
+ /// Set by the worker when the operation returned; the supervisor
123
+ /// answers with one final drain and `drained`.
124
+ finishing: bool = false,
125
+ drained: std.Io.Event = .unset,
126
+ /// The supervisor is reading this stream outside the pool mutex.
127
+ in_poll: bool = false,
128
+ /// The owner retired while the supervisor was mid-poll; the
129
+ /// supervisor destroys the stream when its poll completes.
130
+ orphaned: bool = false,
131
+ };
132
+
133
+ const Active = struct {
134
+ key: u64,
135
+ request_id: u32,
136
+ payload: []u8,
137
+ answer: bool,
138
+ deadline: std.Io.Clock.Timestamp,
139
+ cancelled: bool = false,
140
+ /// A terminal outcome was already decided (timeout staged, trap
141
+ /// staged, or cancel discarded); any later result is dropped.
142
+ retired: bool = false,
143
+ timed_out: bool = false,
144
+ cancel_published: bool = false,
145
+ grace_deadline: ?std.Io.Clock.Timestamp = null,
146
+ /// Allocated after the pick (the slot installs atomically with
147
+ /// the dequeue, under the pool mutex, so a same-key twin can
148
+ /// never double-pick); a cancellation published before the path
149
+ /// exists writes its marker when the path attaches.
150
+ cancel_path: ?[]u8 = null,
151
+ stream: ?*Stream = null,
152
+ };
153
+
154
+ const WorkerState = enum { idle, busy, poisoned, exited };
155
+ const ExecutionState = enum(u8) { running, completing, trapping, poisoned };
156
+
157
+ const Worker = struct {
158
+ pool: *Self,
159
+ /// Process-lifetime executor handle copied out of the pool. A
160
+ /// poisoned thread may need to park after the pool itself was
161
+ /// destroyed (for example when an abandoned dispatch traps).
162
+ io: std.Io,
163
+ thread: std.Thread = undefined,
164
+ /// Guarded by pool.mutex.
165
+ state: WorkerState = .idle,
166
+ active: ?Active = null,
167
+ exited_event: std.Io.Event = .unset,
168
+ /// Atomic ownership handoff around the archive call. Completion
169
+ /// and the supervisor race to claim `running`; a trap can preempt
170
+ /// either execution or completion. Only the winner may touch
171
+ /// request teardown. The Worker struct itself is leaked on poison
172
+ /// so this stays readable after the pool is gone.
173
+ execution_state: std.atomic.Value(ExecutionState) = .init(.running),
174
+ /// A poisoned dispatch sets this after it physically stops. The
175
+ /// supervisor then releases its key/resources; until then a
176
+ /// same-key replacement remains queued.
177
+ returned_flag: std.atomic.Value(bool) = .init(false),
178
+ };
179
+
180
+ allocator: std.mem.Allocator,
181
+ io: std.Io,
182
+ cwd: []const u8,
183
+ options: PoolOptions,
184
+ mutex: std.Io.Mutex = .init,
185
+ condition: std.Io.Condition = .init,
186
+ /// Supervisor wake latch (deadline/grace/stream state changed).
187
+ supervisor_event: std.Io.Event = .unset,
188
+ supervisor_thread: ?std.Thread = null,
189
+ queue: std.ArrayList(Request) = .empty,
190
+ results: std.ArrayList(Result) = .empty,
191
+ last_polled: ?[]u8 = null,
192
+ services: ?platform.PlatformServices = null,
193
+ channels: ?effects.HostChannelBinding = null,
194
+ workers: std.ArrayList(*Worker) = .empty,
195
+ shutting_down: bool = false,
196
+ next_request_id: u32 = 1,
197
+ request_timeout_ms: u32 = default_request_timeout_ms,
198
+ fingerprint_state: enum { unchecked, ok, rejected } = .unchecked,
199
+ /// Wakes in flight outside the mutex; shutdown waits for zero so a
200
+ /// worker can never call a severed PlatformServices handle.
201
+ waking: usize = 0,
202
+ waking_condition: std.Io.Condition = .init,
203
+ poisoned_total: u64 = 0,
204
+ test_completion_barrier: if (builtin.is_test) ?*TestCompletionBarrier else void = if (builtin.is_test) null else {},
205
+
206
+ pub fn init(allocator: std.mem.Allocator, io: std.Io, cwd: []const u8, options: PoolOptions) Self {
207
+ return .{ .allocator = allocator, .io = io, .cwd = cwd, .options = options };
208
+ }
209
+
210
+ pub fn binding(self: *Self) effects.HostCallBinding {
211
+ return .{
212
+ .context = self,
213
+ .send_fn = send,
214
+ .request_fn = request,
215
+ .cancel_fn = cancel,
216
+ .reject_duplicate_keys = true,
217
+ .poll_fn = poll,
218
+ .pending_fn = pending,
219
+ .bind_services_fn = bindServices,
220
+ .bind_channels_fn = bindChannels,
221
+ .shutdown_fn = shutdown,
222
+ };
223
+ }
224
+
225
+ /// Configure the carrier for deterministic timeout tests; production
226
+ /// uses the conservative default.
227
+ pub fn setRequestTimeoutMs(self: *Self, timeout_ms: u32) void {
228
+ std.debug.assert(timeout_ms > 0);
229
+ self.mutex.lockUncancelable(self.io);
230
+ defer self.mutex.unlock(self.io);
231
+ self.request_timeout_ms = timeout_ms;
232
+ }
233
+
234
+ /// Pause after a dispatch claims `.completing`, before its final stream
235
+ /// drain. Tests install this before the first request; it is unavailable
236
+ /// in production builds and adds no field to their pool layout.
237
+ pub fn setCompletionBarrierForTesting(self: *Self, barrier: *TestCompletionBarrier) void {
238
+ if (comptime !builtin.is_test) @compileError("completion barriers are test-only");
239
+ self.test_completion_barrier = barrier;
240
+ }
241
+
242
+ /// Diagnostic visibility: whether any pool thread was ever started.
243
+ /// The replay suites pin this false — replay must never initialize
244
+ /// the archive.
245
+ pub fn started(self: *Self) bool {
246
+ self.mutex.lockUncancelable(self.io);
247
+ defer self.mutex.unlock(self.io);
248
+ return self.workers.items.len > 0;
249
+ }
250
+
251
+ /// Diagnostic visibility: instances abandoned to traps or ignored
252
+ /// cancellation tokens over this pool's lifetime.
253
+ pub fn poisonedCount(self: *Self) u64 {
254
+ self.mutex.lockUncancelable(self.io);
255
+ defer self.mutex.unlock(self.io);
256
+ return self.poisoned_total;
257
+ }
258
+
259
+ /// Live worker threads (poisoned and exited instances excluded).
260
+ pub fn workerCount(self: *Self) usize {
261
+ self.mutex.lockUncancelable(self.io);
262
+ defer self.mutex.unlock(self.io);
263
+ var count: usize = 0;
264
+ for (self.workers.items) |worker| {
265
+ if (worker.state == .idle or worker.state == .busy) count += 1;
266
+ }
267
+ return count;
268
+ }
269
+
270
+ /// Safe after Effects shutdown; repeated shutdown is inert.
271
+ pub fn deinit(self: *Self) void {
272
+ shutdown(self);
273
+ self.mutex.lockUncancelable(self.io);
274
+ for (self.queue.items) |entry| self.allocator.free(entry.payload);
275
+ self.queue.deinit(self.allocator);
276
+ for (self.results.items) |entry| self.allocator.free(entry.bytes);
277
+ self.results.deinit(self.allocator);
278
+ if (self.last_polled) |bytes| self.allocator.free(bytes);
279
+ self.last_polled = null;
280
+ for (self.workers.items) |worker| {
281
+ if (worker.state == .poisoned and worker.returned_flag.load(.acquire)) {
282
+ _ = self.reapReturnedPoisonedLocked(worker);
283
+ }
284
+ // Poisoned workers' structs stay allocated: their abandoned
285
+ // threads may still read the atomic re-entry flag. Bounded
286
+ // by the poison count.
287
+ if (worker.state == .exited) self.allocator.destroy(worker);
288
+ }
289
+ self.workers.deinit(self.allocator);
290
+ self.mutex.unlock(self.io);
291
+ }
292
+
293
+ // ------------------------------------------------------ admission
294
+
295
+ fn send(context: *anyopaque, name: []const u8, payload: []const u8) void {
296
+ const self: *Self = @ptrCast(@alignCast(context));
297
+ const operation_index = Registry.indexOf(name) orelse return;
298
+ const operation = Registry.operationAt(operation_index) orelse return;
299
+ if (operation.streaming) return;
300
+ self.enqueue(0, operation.index, payload, false, operation.deadline_ms orelse self.request_timeout_ms, null);
301
+ }
302
+
303
+ fn request(context: *anyopaque, name: []const u8, key: u64, payload: []const u8) void {
304
+ const self: *Self = @ptrCast(@alignCast(context));
305
+ const operation_index = Registry.indexOf(name) orelse {
306
+ self.stageStatic(key, false, transport_error);
307
+ return;
308
+ };
309
+ const operation = Registry.operationAt(operation_index) orelse {
310
+ self.stageStatic(key, false, transport_error);
311
+ return;
312
+ };
313
+ var request_payload = payload;
314
+ var channel: ?effects.ChannelHandle = null;
315
+ if (operation.streaming) {
316
+ if (payload.len < 8) {
317
+ self.stageStatic(key, false, transport_error);
318
+ return;
319
+ }
320
+ const channel_number = @as(f64, @bitCast(readU64(payload, 0)));
321
+ if (!std.math.isFinite(channel_number) or channel_number < 1 or channel_number >= 9_007_199_254_740_992 or @floor(channel_number) != channel_number) {
322
+ self.stageStatic(key, false, transport_error);
323
+ return;
324
+ }
325
+ const channel_key: u64 = @intFromFloat(channel_number);
326
+ const channel_binding = self.channels orelse {
327
+ self.stageStatic(key, false, transport_error);
328
+ return;
329
+ };
330
+ channel = channel_binding.acquire_fn(channel_binding.context, channel_key) orelse {
331
+ self.stageStatic(key, false, transport_error);
332
+ return;
333
+ };
334
+ request_payload = payload[8..];
335
+ }
336
+ self.enqueue(key, operation.index, request_payload, true, operation.deadline_ms orelse self.request_timeout_ms, channel);
337
+ }
338
+
339
+ fn cancel(context: *anyopaque, key: u64) void {
340
+ const self: *Self = @ptrCast(@alignCast(context));
341
+ self.mutex.lockUncancelable(self.io);
342
+ var index: usize = 0;
343
+ while (index < self.queue.items.len) {
344
+ if (self.queue.items[index].answer and self.queue.items[index].key == key) {
345
+ const removed = self.queue.orderedRemove(index);
346
+ self.allocator.free(removed.payload);
347
+ } else index += 1;
348
+ }
349
+ index = 0;
350
+ while (index < self.results.items.len) {
351
+ if (self.results.items[index].key == key) {
352
+ const removed = self.results.orderedRemove(index);
353
+ self.allocator.free(removed.bytes);
354
+ } else index += 1;
355
+ }
356
+ for (self.workers.items) |worker| {
357
+ if (worker.state != .busy) continue;
358
+ if (worker.active) |*active| {
359
+ if (!active.answer or active.key != key or active.retired) continue;
360
+ active.cancelled = true;
361
+ self.publishCancellationLocked(active);
362
+ }
363
+ }
364
+ // Wake workers so queue removals and newly published cancellation
365
+ // state are observed. The active request keeps its key reserved
366
+ // until its dispatch physically returns.
367
+ self.condition.broadcast(self.io);
368
+ self.supervisor_event.set(self.io);
369
+ self.mutex.unlock(self.io);
370
+ }
371
+
372
+ fn bindServices(context: *anyopaque, services: *const platform.PlatformServices) void {
373
+ const self: *Self = @ptrCast(@alignCast(context));
374
+ self.mutex.lockUncancelable(self.io);
375
+ self.services = services.*;
376
+ self.mutex.unlock(self.io);
377
+ }
378
+
379
+ fn bindChannels(context: *anyopaque, channels: effects.HostChannelBinding) void {
380
+ const self: *Self = @ptrCast(@alignCast(context));
381
+ self.channels = channels;
382
+ }
383
+
384
+ fn pending(context: *anyopaque) bool {
385
+ const self: *Self = @ptrCast(@alignCast(context));
386
+ self.mutex.lockUncancelable(self.io);
387
+ defer self.mutex.unlock(self.io);
388
+ return self.results.items.len > 0;
389
+ }
390
+
391
+ fn poll(context: *anyopaque) ?effects.HostCallCompletion {
392
+ const self: *Self = @ptrCast(@alignCast(context));
393
+ self.mutex.lockUncancelable(self.io);
394
+ defer self.mutex.unlock(self.io);
395
+ if (self.last_polled) |bytes| self.allocator.free(bytes);
396
+ self.last_polled = null;
397
+ if (self.results.items.len == 0) return null;
398
+ const result = self.results.orderedRemove(0);
399
+ self.last_polled = result.bytes;
400
+ return .{ .key = result.key, .ok = result.ok, .bytes = result.bytes };
401
+ }
402
+
403
+ fn shutdown(context: *anyopaque) void {
404
+ const self: *Self = @ptrCast(@alignCast(context));
405
+ self.mutex.lockUncancelable(self.io);
406
+ if (self.shutting_down) {
407
+ self.mutex.unlock(self.io);
408
+ return;
409
+ }
410
+ self.shutting_down = true;
411
+ // Every busy operation gets the cooperative token; the exit wait
412
+ // below is the grace. The supervisor keeps running until no
413
+ // worker is busy — it drains finishing streams and poisons
414
+ // token-ignoring operations at their grace deadline.
415
+ for (self.workers.items) |worker| {
416
+ if (worker.state != .busy) continue;
417
+ if (worker.active) |*active| {
418
+ if (!active.retired) self.publishCancellationLocked(active);
419
+ }
420
+ }
421
+ self.condition.broadcast(self.io);
422
+ self.supervisor_event.set(self.io);
423
+
424
+ const exit_deadline = std.Io.Clock.Timestamp.fromNow(self.io, .{
425
+ .raw = std.Io.Duration.fromMilliseconds(2 * cooperative_cancel_grace_ms + 200),
426
+ .clock = .awake,
427
+ });
428
+ var index: usize = 0;
429
+ while (index < self.workers.items.len) : (index += 1) {
430
+ const worker = self.workers.items[index];
431
+ if (worker.state == .poisoned) continue; // detached at poison time
432
+ if (worker.state == .exited) {
433
+ self.mutex.unlock(self.io);
434
+ worker.thread.join();
435
+ self.mutex.lockUncancelable(self.io);
436
+ continue;
437
+ }
438
+ self.mutex.unlock(self.io);
439
+ const timed_out = timed_out: {
440
+ worker.exited_event.waitTimeout(self.io, .{ .deadline = exit_deadline }) catch break :timed_out true;
441
+ break :timed_out false;
442
+ };
443
+ self.mutex.lockUncancelable(self.io);
444
+ if (worker.state == .poisoned) continue; // trapped or abandoned meanwhile
445
+ if (timed_out and worker.state != .exited) {
446
+ // The operation ignored its token even at shutdown:
447
+ // abandon the instance like every other hard timeout.
448
+ if (self.poisonWorkerLocked(worker, .running)) continue;
449
+
450
+ // Completion or the trap sink claimed teardown first.
451
+ // Let that owner finish while the pool is still alive;
452
+ // both paths signal the same state-change latch.
453
+ if (worker.execution_state.load(.acquire) == .poisoned) continue;
454
+ self.mutex.unlock(self.io);
455
+ worker.exited_event.waitUncancelable(self.io);
456
+ self.mutex.lockUncancelable(self.io);
457
+ if (worker.state == .poisoned) continue;
458
+ }
459
+ self.mutex.unlock(self.io);
460
+ worker.thread.join();
461
+ self.mutex.lockUncancelable(self.io);
462
+ }
463
+ const supervisor = self.supervisor_thread;
464
+ self.supervisor_thread = null;
465
+ self.supervisor_event.set(self.io);
466
+ self.mutex.unlock(self.io);
467
+ if (supervisor) |thread| thread.join();
468
+ self.mutex.lockUncancelable(self.io);
469
+ self.services = null;
470
+ while (self.waking > 0) self.waking_condition.waitUncancelable(self.io, &self.mutex);
471
+ self.mutex.unlock(self.io);
472
+ }
473
+
474
+ // ------------------------------------------------------- staging
475
+
476
+ fn stageStatic(self: *Self, key: u64, ok: bool, bytes: []const u8) void {
477
+ const copy = self.allocator.dupe(u8, bytes) catch return;
478
+ self.stageOwned(.{ .key = key, .ok = ok, .bytes = copy });
479
+ }
480
+
481
+ fn stageOwned(self: *Self, result: Result) void {
482
+ self.mutex.lockUncancelable(self.io);
483
+ self.stageOwnedLocked(result);
484
+ const services = self.takeWakeLocked();
485
+ self.mutex.unlock(self.io);
486
+ self.finishWake(services);
487
+ }
488
+
489
+ fn stageOwnedLocked(self: *Self, result: Result) void {
490
+ if (self.shutting_down) {
491
+ self.allocator.free(result.bytes);
492
+ return;
493
+ }
494
+ self.results.append(self.allocator, result) catch {
495
+ self.allocator.free(result.bytes);
496
+ return;
497
+ };
498
+ }
499
+
500
+ /// Reserve the right to wake after unlocking. Shutdown waits for
501
+ /// every reservation to finish before the platform handle is severed.
502
+ fn takeWakeLocked(self: *Self) ?platform.PlatformServices {
503
+ const services = self.services orelse return null;
504
+ self.waking += 1;
505
+ return services;
506
+ }
507
+
508
+ fn finishWake(self: *Self, services: ?platform.PlatformServices) void {
509
+ const bound = services orelse return;
510
+ bound.wake() catch {};
511
+ self.mutex.lockUncancelable(self.io);
512
+ self.waking -= 1;
513
+ self.waking_condition.broadcast(self.io);
514
+ self.mutex.unlock(self.io);
515
+ }
516
+
517
+ // ------------------------------------------------------- enqueue
518
+
519
+ fn enqueue(self: *Self, key: u64, operation: u16, payload: []const u8, answer: bool, timeout_ms: u32, channel: ?effects.ChannelHandle) void {
520
+ const copy = self.allocator.dupe(u8, payload) catch {
521
+ if (answer) self.stageStatic(key, false, transport_error);
522
+ return;
523
+ };
524
+ const deadline = std.Io.Clock.Timestamp.fromNow(self.io, .{
525
+ .raw = std.Io.Duration.fromMilliseconds(timeout_ms),
526
+ .clock = .awake,
527
+ });
528
+ self.mutex.lockUncancelable(self.io);
529
+ if (self.shutting_down) {
530
+ self.mutex.unlock(self.io);
531
+ self.allocator.free(copy);
532
+ if (answer) self.stageStatic(key, false, transport_error);
533
+ return;
534
+ }
535
+ const request_id = self.next_request_id;
536
+ self.next_request_id +%= 1;
537
+ if (self.next_request_id == 0) self.next_request_id = 1;
538
+ self.queue.append(self.allocator, .{
539
+ .key = key,
540
+ .request_id = request_id,
541
+ .operation = operation,
542
+ .payload = copy,
543
+ .answer = answer,
544
+ .deadline = deadline,
545
+ .channel = channel,
546
+ }) catch {
547
+ self.mutex.unlock(self.io);
548
+ self.allocator.free(copy);
549
+ if (answer) self.stageStatic(key, false, transport_error);
550
+ return;
551
+ };
552
+ if (!self.ensureCapacityLocked()) {
553
+ const removed = self.queue.pop().?;
554
+ self.mutex.unlock(self.io);
555
+ self.allocator.free(removed.payload);
556
+ if (answer) self.stageStatic(key, false, transport_error);
557
+ return;
558
+ }
559
+ // A newly admitted deadline may be earlier than every deadline
560
+ // the supervisor observed before parking. Wake both schedulers:
561
+ // a worker may be able to run it now, while the supervisor owns
562
+ // expiry if every eligible worker remains occupied.
563
+ self.condition.signal(self.io);
564
+ self.supervisor_event.set(self.io);
565
+ self.mutex.unlock(self.io);
566
+ }
567
+
568
+ /// Lazily grow the pool toward its width: the supervisor plus one
569
+ /// worker on first use, another worker whenever the queued backlog
570
+ /// exceeds the idle set and capacity remains. Returns false only
571
+ /// when the pool has no worker at all and cannot start one.
572
+ fn ensureCapacityLocked(self: *Self) bool {
573
+ const target = @min(max_pool_workers, @max(1, self.options.max_workers orelse defaultWorkerCount()));
574
+ if (self.supervisor_thread == null) {
575
+ self.supervisor_thread = std.Thread.spawn(.{}, supervisorMain, .{self}) catch null;
576
+ if (self.supervisor_thread == null) return false;
577
+ }
578
+ var live: usize = 0;
579
+ var idle: usize = 0;
580
+ for (self.workers.items) |worker| {
581
+ switch (worker.state) {
582
+ .idle => {
583
+ live += 1;
584
+ idle += 1;
585
+ },
586
+ .busy => live += 1,
587
+ .poisoned, .exited => {},
588
+ }
589
+ }
590
+ if (live >= target or idle >= self.queue.items.len) return true;
591
+ const spawned = self.spawnWorkerLocked();
592
+ return spawned or live > 0;
593
+ }
594
+
595
+ fn spawnWorkerLocked(self: *Self) bool {
596
+ const worker = self.allocator.create(Worker) catch return false;
597
+ worker.* = .{ .pool = self, .io = self.io };
598
+ self.workers.append(self.allocator, worker) catch {
599
+ self.allocator.destroy(worker);
600
+ return false;
601
+ };
602
+ worker.thread = std.Thread.spawn(.{}, workerMain, .{worker}) catch {
603
+ _ = self.workers.pop();
604
+ self.allocator.destroy(worker);
605
+ return false;
606
+ };
607
+ return true;
608
+ }
609
+
610
+ // --------------------------------------------------------- worker
611
+
612
+ fn keyBusyLocked(self: *Self, key: u64) bool {
613
+ for (self.workers.items) |worker| {
614
+ const active = worker.active orelse continue;
615
+ if (active.key != key) continue;
616
+ if (worker.state == .busy) return true;
617
+ if (worker.state == .poisoned and !worker.returned_flag.load(.acquire)) return true;
618
+ }
619
+ return false;
620
+ }
621
+
622
+ /// The oldest queue entry whose key has no active/abandoned twin —
623
+ /// FIFO per key follows directly from the queue-order scan, while a
624
+ /// busy key never hides later independent work from an idle worker.
625
+ fn pickRequestLocked(self: *Self) ?Request {
626
+ var index: usize = 0;
627
+ while (index < self.queue.items.len) : (index += 1) {
628
+ const key = self.queue.items[index].key;
629
+ if (!self.keyBusyLocked(key)) return self.queue.orderedRemove(index);
630
+ }
631
+ return null;
632
+ }
633
+
634
+ fn workerMain(worker: *Worker) void {
635
+ const self = worker.pool;
636
+ // The calling thread is the instance: one deterministic init and
637
+ // one per-instance sink registration for this thread's lifetime.
638
+ abi.init_fn();
639
+ abi.set_panic_sink_fn(&trapSink, worker);
640
+ self.verifyFingerprint();
641
+ self.mutex.lockUncancelable(self.io);
642
+ while (!self.shutting_down) {
643
+ const work = self.pickRequestLocked() orelse {
644
+ worker.state = .idle;
645
+ self.condition.waitUncancelable(self.io, &self.mutex);
646
+ continue;
647
+ };
648
+ worker.state = .busy;
649
+ if (self.fingerprint_state == .rejected) {
650
+ worker.state = .idle;
651
+ self.mutex.unlock(self.io);
652
+ self.allocator.free(work.payload);
653
+ if (work.answer) self.stageStatic(work.key, false, transport_error);
654
+ self.mutex.lockUncancelable(self.io);
655
+ continue;
656
+ }
657
+ // The active slot installs atomically with the dequeue:
658
+ // from here a same-key twin is blocked and a cancel or
659
+ // deadline finds this request supervisable.
660
+ worker.execution_state.store(.running, .release);
661
+ worker.returned_flag.store(false, .release);
662
+ worker.active = .{
663
+ .key = work.key,
664
+ .request_id = work.request_id,
665
+ .payload = work.payload,
666
+ .answer = work.answer,
667
+ .deadline = work.deadline,
668
+ };
669
+ self.supervisor_event.set(self.io);
670
+ self.mutex.unlock(self.io);
671
+ self.executeRequest(worker, work);
672
+ // A hard-timed-out request abandoned this worker. The
673
+ // request path set `returned_flag` without touching the pool;
674
+ // the supervisor owns resource/key retirement from here.
675
+ if (worker.execution_state.load(.acquire) == .poisoned) return;
676
+ self.mutex.lockUncancelable(self.io);
677
+ worker.state = .idle;
678
+ }
679
+ worker.state = .exited;
680
+ worker.exited_event.set(self.io);
681
+ self.supervisor_event.set(self.io);
682
+ self.mutex.unlock(self.io);
683
+ }
684
+
685
+ fn executeRequest(self: *Self, worker: *Worker, work: Request) void {
686
+ const cancel_path = self.cancellationPath(work.request_id) catch null;
687
+ var stream: ?*Stream = null;
688
+ if (cancel_path != null) {
689
+ if (work.channel) |channel| {
690
+ stream = self.createStream(work.request_id, channel);
691
+ }
692
+ }
693
+ const setup_failed = cancel_path == null or (work.channel != null and stream == null);
694
+ self.mutex.lockUncancelable(self.io);
695
+ if (worker.active) |*active| {
696
+ active.cancel_path = cancel_path;
697
+ active.stream = stream;
698
+ // A cancellation or deadline published before the marker
699
+ // path existed writes its marker now.
700
+ if (active.cancel_published) {
701
+ if (std.Io.Dir.cwd().createFile(self.io, cancel_path.?, .{ .truncate = true })) |file| {
702
+ file.close(self.io);
703
+ } else |_| {}
704
+ }
705
+ // The supervisor may be parked on a distant deadline; an
706
+ // attached stream needs its 2 ms tailing cadence now.
707
+ if (stream != null) self.supervisor_event.set(self.io);
708
+ }
709
+ if (worker.state == .poisoned) {
710
+ if (worker.active) |*active| active.retired = true;
711
+ worker.returned_flag.store(true, .release);
712
+ self.supervisor_event.set(self.io);
713
+ self.mutex.unlock(self.io);
714
+ return;
715
+ }
716
+ if (setup_failed) {
717
+ if (worker.active) |*active| active.retired = true;
718
+ self.retireActiveLocked(worker);
719
+ self.mutex.unlock(self.io);
720
+ if (work.answer) self.stageStatic(work.key, false, transport_error);
721
+ return;
722
+ }
723
+ const already_expired = std.Io.Clock.Timestamp.compare(
724
+ std.Io.Clock.Timestamp.now(self.io, .awake),
725
+ .gte,
726
+ work.deadline,
727
+ );
728
+ if (already_expired) {
729
+ // Deadlines include queue time: an expired request never
730
+ // enters the archive (parity with the child carrier).
731
+ const active = &worker.active.?;
732
+ active.retired = true;
733
+ active.timed_out = true;
734
+ var expired_staged = false;
735
+ if (work.answer and !active.cancelled) {
736
+ if (self.allocator.dupe(u8, timeout_error)) |copy| {
737
+ self.stageOwnedLocked(.{ .key = work.key, .ok = false, .bytes = copy });
738
+ expired_staged = true;
739
+ } else |_| {}
740
+ }
741
+ const services = if (expired_staged) self.takeWakeLocked() else null;
742
+ self.retireActiveLocked(worker);
743
+ self.mutex.unlock(self.io);
744
+ self.finishWake(services);
745
+ return;
746
+ }
747
+ self.mutex.unlock(self.io);
748
+
749
+ var out_ptr: [*]const u8 = undefined;
750
+ var out_len: usize = 0;
751
+ const empty = [_]u8{0};
752
+ const payload_ptr: [*]const u8 = if (work.payload.len > 0) work.payload.ptr else &empty;
753
+ const marker_path: []const u8 = cancel_path.?;
754
+ const stream_path: []const u8 = if (stream) |value| value.path else "";
755
+ const stream_ptr: [*]const u8 = if (stream_path.len > 0) stream_path.ptr else &empty;
756
+ abi.dispatch_fn(
757
+ work.operation,
758
+ payload_ptr,
759
+ work.payload.len,
760
+ marker_path.ptr,
761
+ marker_path.len,
762
+ stream_ptr,
763
+ stream_path.len,
764
+ &out_ptr,
765
+ &out_len,
766
+ );
767
+ // Atomically claim completion before touching any pool-owned
768
+ // request resource. If the supervisor won the race, the Worker
769
+ // is process-lived but the pool may already be gone: publish the
770
+ // one safe returned bit and leave everything else to the
771
+ // supervisor (or leak it at process teardown).
772
+ if (worker.execution_state.cmpxchgStrong(.running, .completing, .acq_rel, .acquire)) |actual| {
773
+ std.debug.assert(actual == .poisoned);
774
+ worker.returned_flag.store(true, .release);
775
+ return;
776
+ }
777
+ if (comptime builtin.is_test) {
778
+ if (self.test_completion_barrier) |barrier| {
779
+ barrier.claimed.set(self.io);
780
+ barrier.release.waitUncancelable(self.io);
781
+ }
782
+ }
783
+
784
+ var completion: ?Result = null;
785
+ if (work.answer) {
786
+ if (out_len >= 1) {
787
+ if (self.allocator.dupe(u8, out_ptr[1..out_len])) |copy| {
788
+ completion = .{ .key = work.key, .ok = out_ptr[0] == 0, .bytes = copy };
789
+ } else |_| {}
790
+ }
791
+ if (completion == null) {
792
+ if (self.allocator.dupe(u8, transport_error)) |copy| {
793
+ completion = .{ .key = work.key, .ok = false, .bytes = copy };
794
+ } else |_| {}
795
+ }
796
+ }
797
+ // Reference-cycle collection between requests keeps a long-lived
798
+ // instance's heap bounded; the returned bytes were copied above.
799
+ abi.collect_fn();
800
+
801
+ // Chunks precede the terminal: the supervisor drains the relay
802
+ // file completely before the result stages.
803
+ if (stream) |value| self.finishStream(value);
804
+
805
+ self.mutex.lockUncancelable(self.io);
806
+ var staged = false;
807
+ if (worker.active) |*active| {
808
+ if (completion) |result| {
809
+ if (active.retired or active.cancelled or self.shutting_down) {
810
+ self.allocator.free(result.bytes);
811
+ } else if (active.timed_out) {
812
+ // Cooperative timeout: the operation honored the
813
+ // token inside the grace; the instance stays warm
814
+ // and the request routes the timeout kind.
815
+ self.allocator.free(result.bytes);
816
+ active.retired = true;
817
+ if (self.allocator.dupe(u8, timeout_error)) |copy| {
818
+ self.stageOwnedLocked(.{ .key = work.key, .ok = false, .bytes = copy });
819
+ staged = true;
820
+ } else |_| {}
821
+ } else {
822
+ active.retired = true;
823
+ self.stageOwnedLocked(result);
824
+ staged = true;
825
+ }
826
+ }
827
+ } else if (completion) |result| {
828
+ self.allocator.free(result.bytes);
829
+ }
830
+ const services = if (staged) self.takeWakeLocked() else null;
831
+ self.retireActiveLocked(worker);
832
+ self.mutex.unlock(self.io);
833
+ self.finishWake(services);
834
+ }
835
+
836
+ /// Clear the worker's active slot and release its request-scoped
837
+ /// resources. Pool mutex held.
838
+ fn retireActiveLocked(self: *Self, worker: *Worker) void {
839
+ const active = worker.active orelse return;
840
+ self.allocator.free(active.payload);
841
+ if (active.cancel_path) |path| {
842
+ std.Io.Dir.cwd().deleteFile(self.io, path) catch {};
843
+ self.allocator.free(path);
844
+ }
845
+ if (active.stream) |stream| self.releaseStreamLocked(stream);
846
+ worker.active = null;
847
+ // A completed request may unblock a queued same-key twin.
848
+ self.condition.broadcast(self.io);
849
+ self.supervisor_event.set(self.io);
850
+ }
851
+
852
+ // ------------------------------------------------------ poisoning
853
+
854
+ /// Abandon a worker whose operation ignored its cooperative token
855
+ /// (or trapped): detach the thread, retain the request's resources and
856
+ /// key until dispatch physically stops, and refill the pool. Pool mutex
857
+ /// held.
858
+ fn poisonWorkerLocked(self: *Self, worker: *Worker, expected: ExecutionState) bool {
859
+ if (worker.execution_state.cmpxchgStrong(expected, .poisoned, .acq_rel, .acquire) != null) return false;
860
+ std.debug.assert(worker.state != .poisoned);
861
+ worker.state = .poisoned;
862
+ worker.thread.detach();
863
+ // This is a state-change latch too: shutdown waiters re-check
864
+ // `worker.state` and skip joining a detached poisoned thread.
865
+ worker.exited_event.set(self.io);
866
+ self.poisoned_total += 1;
867
+ // Keep the active slot and all request storage alive: the detached
868
+ // archive call may still be reading those bytes/paths. Its key
869
+ // remains reserved until `returned_flag`; then the supervisor can
870
+ // reclaim the resources because the dispatch physically stopped.
871
+ self.condition.broadcast(self.io);
872
+ self.supervisor_event.set(self.io);
873
+ if (!self.shutting_down) _ = self.spawnWorkerLocked();
874
+ return true;
875
+ }
876
+
877
+ /// Reclaim a poisoned request only after its detached dispatch has
878
+ /// physically stopped. Pool mutex held.
879
+ fn reapReturnedPoisonedLocked(self: *Self, worker: *Worker) bool {
880
+ if (worker.state != .poisoned or !worker.returned_flag.load(.acquire) or worker.active == null) return false;
881
+ self.retireActiveLocked(worker);
882
+ return true;
883
+ }
884
+
885
+ /// The per-instance trap sink: runs on the trapping worker thread,
886
+ /// stages the error, poisons exactly this instance, and parks the
887
+ /// thread forever (the sink must not return).
888
+ fn trapSink(context: ?*anyopaque, msg: [*]const u8, msg_len: usize, address: u64) callconv(.c) void {
889
+ _ = address;
890
+ const worker: *Worker = @ptrCast(@alignCast(context.?));
891
+ var state = worker.execution_state.load(.acquire);
892
+ while (state != .poisoned) {
893
+ const claimable = state == .running or state == .completing;
894
+ std.debug.assert(claimable);
895
+ if (worker.execution_state.cmpxchgWeak(state, .trapping, .acq_rel, .acquire)) |actual| {
896
+ state = actual;
897
+ continue;
898
+ }
899
+ break;
900
+ }
901
+ if (state == .poisoned) {
902
+ // The supervisor already detached this instance. A later
903
+ // trap must never follow Worker.pool into freed pool memory.
904
+ worker.returned_flag.store(true, .release);
905
+ parkWorker(worker);
906
+ }
907
+ const self = worker.pool;
908
+ const message = msg[0..msg_len];
909
+ self.mutex.lockUncancelable(self.io);
910
+ var staged = false;
911
+ if (worker.active) |*active| {
912
+ if (active.answer and !active.retired and !active.cancelled and !self.shutting_down) {
913
+ active.retired = true;
914
+ if (trapErrorJson(self.allocator, message)) |bytes| {
915
+ self.stageOwnedLocked(.{ .key = active.key, .ok = false, .bytes = bytes });
916
+ staged = true;
917
+ } else |_| {}
918
+ } else {
919
+ active.retired = true;
920
+ }
921
+ }
922
+ const poisoned = self.poisonWorkerLocked(worker, .trapping);
923
+ std.debug.assert(poisoned);
924
+ // A trapped dispatch can never resume past the sink, so it has
925
+ // physically stopped for same-key serialization purposes.
926
+ worker.returned_flag.store(true, .release);
927
+ self.supervisor_event.set(self.io);
928
+ const services = if (staged) self.takeWakeLocked() else null;
929
+ self.mutex.unlock(self.io);
930
+ self.finishWake(services);
931
+ parkWorker(worker);
932
+ }
933
+
934
+ fn parkWorker(worker: *Worker) noreturn {
935
+ // The instance is poisoned and this thread IS the instance; only
936
+ // its stack and process-lived Worker remain resident.
937
+ var park: std.Io.Event = .unset;
938
+ while (true) park.waitUncancelable(worker.io);
939
+ }
940
+
941
+ // ------------------------------------------------------ supervisor
942
+
943
+ /// One thread supervises every in-flight request: deadline expiry,
944
+ /// the cooperative-cancel grace, and stream-relay tailing. It exits
945
+ /// only when the pool is shutting down AND no worker is busy, so a
946
+ /// worker draining its stream at shutdown is never stranded.
947
+ fn supervisorMain(self: *Self) void {
948
+ while (true) {
949
+ self.supervisor_event.reset();
950
+ var staged_wake = false;
951
+ var streams_buffer: [max_pool_workers]*Stream = undefined;
952
+ var streams_len: usize = 0;
953
+ var next_deadline: ?std.Io.Clock.Timestamp = null;
954
+
955
+ self.mutex.lockUncancelable(self.io);
956
+ var any_busy = false;
957
+ var any_abandoned = false;
958
+ const now = std.Io.Clock.Timestamp.now(self.io, .awake);
959
+ // Queue time belongs to the request deadline. Expire queued
960
+ // work here as well as at pick time, including a same-key
961
+ // replacement waiting for an abandoned predecessor.
962
+ var queue_index: usize = 0;
963
+ while (queue_index < self.queue.items.len) {
964
+ const queued = self.queue.items[queue_index];
965
+ if (!std.Io.Clock.Timestamp.compare(now, .gte, queued.deadline)) {
966
+ next_deadline = earlier(next_deadline, queued.deadline);
967
+ queue_index += 1;
968
+ continue;
969
+ }
970
+ const expired = self.queue.orderedRemove(queue_index);
971
+ self.allocator.free(expired.payload);
972
+ if (expired.answer) {
973
+ if (self.allocator.dupe(u8, timeout_error)) |copy| {
974
+ self.stageOwnedLocked(.{ .key = expired.key, .ok = false, .bytes = copy });
975
+ staged_wake = true;
976
+ } else |_| {}
977
+ }
978
+ }
979
+ // Index-based: poisoning refills the pool, which appends to
980
+ // this list mid-iteration.
981
+ var worker_index: usize = 0;
982
+ while (worker_index < self.workers.items.len) : (worker_index += 1) {
983
+ const worker = self.workers.items[worker_index];
984
+ if (worker.state == .poisoned) {
985
+ if (!self.reapReturnedPoisonedLocked(worker) and worker.active != null) any_abandoned = true;
986
+ continue;
987
+ }
988
+ if (worker.state != .busy) continue;
989
+ any_busy = true;
990
+ if (worker.active) |*active| {
991
+ if (active.grace_deadline) |grace| {
992
+ if (std.Io.Clock.Timestamp.compare(now, .gte, grace) and !active.retired) {
993
+ // The token was ignored through the grace:
994
+ // abandon this instance only while dispatch
995
+ // still owns `.running`.
996
+ if (self.poisonWorkerLocked(worker, .running)) {
997
+ if (active.timed_out and active.answer and !active.cancelled) {
998
+ if (self.allocator.dupe(u8, timeout_error)) |copy| {
999
+ self.stageOwnedLocked(.{ .key = active.key, .ok = false, .bytes = copy });
1000
+ staged_wake = true;
1001
+ } else |_| {}
1002
+ }
1003
+ active.retired = true;
1004
+ any_abandoned = true;
1005
+ continue;
1006
+ }
1007
+ // Completion (or the trap sink) claimed the
1008
+ // request first. It owns teardown now; fall
1009
+ // through so a completing stream is still
1010
+ // tailed and can finish its final-drain wait.
1011
+ // Its owner signals the supervisor again when
1012
+ // finishing/retirement changes state.
1013
+ } else if (!active.retired) {
1014
+ next_deadline = earlier(next_deadline, grace);
1015
+ }
1016
+ } else if (!active.cancel_published) {
1017
+ if (std.Io.Clock.Timestamp.compare(now, .gte, active.deadline)) {
1018
+ active.timed_out = true;
1019
+ self.publishCancellationLocked(active);
1020
+ next_deadline = earlier(next_deadline, active.grace_deadline.?);
1021
+ } else {
1022
+ next_deadline = earlier(next_deadline, active.deadline);
1023
+ }
1024
+ }
1025
+ if (active.stream) |stream| {
1026
+ if (streams_len < streams_buffer.len) {
1027
+ stream.in_poll = true;
1028
+ streams_buffer[streams_len] = stream;
1029
+ streams_len += 1;
1030
+ }
1031
+ }
1032
+ }
1033
+ }
1034
+ const exit_now = self.shutting_down and !any_busy;
1035
+ const services = if (staged_wake) self.takeWakeLocked() else null;
1036
+ self.mutex.unlock(self.io);
1037
+ self.finishWake(services);
1038
+ if (exit_now) return;
1039
+
1040
+ for (streams_buffer[0..streams_len]) |stream| self.pollStream(stream);
1041
+
1042
+ if (streams_len > 0) {
1043
+ const poll_deadline = std.Io.Clock.Timestamp.fromNow(self.io, .{
1044
+ .raw = std.Io.Duration.fromMilliseconds(stream_poll_ms),
1045
+ .clock = .awake,
1046
+ });
1047
+ next_deadline = earlier(next_deadline, poll_deadline);
1048
+ }
1049
+ if (any_abandoned and !self.shutting_down) {
1050
+ const poll_deadline = std.Io.Clock.Timestamp.fromNow(self.io, .{
1051
+ .raw = std.Io.Duration.fromMilliseconds(abandoned_poll_ms),
1052
+ .clock = .awake,
1053
+ });
1054
+ next_deadline = earlier(next_deadline, poll_deadline);
1055
+ }
1056
+ if (next_deadline) |deadline| {
1057
+ self.supervisor_event.waitTimeout(self.io, .{ .deadline = deadline }) catch {};
1058
+ } else {
1059
+ self.supervisor_event.waitUncancelable(self.io);
1060
+ }
1061
+ }
1062
+ }
1063
+
1064
+ fn earlier(current: ?std.Io.Clock.Timestamp, candidate: std.Io.Clock.Timestamp) std.Io.Clock.Timestamp {
1065
+ const existing = current orelse return candidate;
1066
+ return if (std.Io.Clock.Timestamp.compare(candidate, .lt, existing)) candidate else existing;
1067
+ }
1068
+
1069
+ /// Publish the cooperative token (marker file) and start the grace
1070
+ /// clock. Pool mutex held. A request whose marker path is not yet
1071
+ /// attached writes the marker when the path arrives.
1072
+ fn publishCancellationLocked(self: *Self, active: *Active) void {
1073
+ if (!active.cancel_published) {
1074
+ active.cancel_published = true;
1075
+ active.grace_deadline = std.Io.Clock.Timestamp.fromNow(self.io, .{
1076
+ .raw = std.Io.Duration.fromMilliseconds(cooperative_cancel_grace_ms),
1077
+ .clock = .awake,
1078
+ });
1079
+ if (active.cancel_path) |path| {
1080
+ if (std.Io.Dir.cwd().createFile(self.io, path, .{ .truncate = true })) |file| {
1081
+ file.close(self.io);
1082
+ } else |_| {}
1083
+ }
1084
+ }
1085
+ self.supervisor_event.set(self.io);
1086
+ }
1087
+
1088
+ // -------------------------------------------------------- streams
1089
+
1090
+ fn createStream(self: *Self, request_id: u32, channel: effects.ChannelHandle) ?*Stream {
1091
+ const path = self.streamPath(request_id) catch return null;
1092
+ std.Io.Dir.cwd().deleteFile(self.io, path) catch {};
1093
+ const stream = self.allocator.create(Stream) catch {
1094
+ self.allocator.free(path);
1095
+ return null;
1096
+ };
1097
+ stream.* = .{ .path = path, .channel = channel };
1098
+ return stream;
1099
+ }
1100
+
1101
+ /// Worker side of stream completion: hand the relay to the
1102
+ /// supervisor for the final drain and wait for it, so every chunk
1103
+ /// precedes the typed terminal. The supervisor keeps running while
1104
+ /// any worker is busy, including through shutdown, so the wait is
1105
+ /// bounded.
1106
+ fn finishStream(self: *Self, stream: *Stream) void {
1107
+ self.mutex.lockUncancelable(self.io);
1108
+ stream.finishing = true;
1109
+ self.supervisor_event.set(self.io);
1110
+ self.mutex.unlock(self.io);
1111
+ stream.drained.waitUncancelable(self.io);
1112
+ }
1113
+
1114
+ /// Release a stream whose owner retired: destroy it immediately, or
1115
+ /// mark it orphaned when the supervisor is mid-poll and let the
1116
+ /// supervisor destroy it as its poll completes. Pool mutex held.
1117
+ fn releaseStreamLocked(self: *Self, stream: *Stream) void {
1118
+ if (stream.in_poll) {
1119
+ stream.orphaned = true;
1120
+ return;
1121
+ }
1122
+ self.destroyStreamLocked(stream);
1123
+ }
1124
+
1125
+ fn destroyStreamLocked(self: *Self, stream: *Stream) void {
1126
+ if (stream.file) |file| file.close(self.io);
1127
+ std.Io.Dir.cwd().deleteFile(self.io, stream.path) catch {};
1128
+ self.allocator.free(stream.path);
1129
+ stream.pending.deinit(self.allocator);
1130
+ self.allocator.destroy(stream);
1131
+ }
1132
+
1133
+ /// Tail one relay file: read whatever new frames the operation has
1134
+ /// appended and post each to the external channel. Runs on the
1135
+ /// supervisor thread with the pool mutex released; the `in_poll`
1136
+ /// mark keeps the stream alive until this poll completes.
1137
+ fn pollStream(self: *Self, stream: *Stream) void {
1138
+ self.readStreamFrames(stream);
1139
+ self.mutex.lockUncancelable(self.io);
1140
+ const finished = stream.finishing;
1141
+ self.mutex.unlock(self.io);
1142
+ if (finished) {
1143
+ // The operation returned before `finishing` was set, so
1144
+ // every chunk byte is already in the file: one more read
1145
+ // pass makes the drain complete.
1146
+ self.readStreamFrames(stream);
1147
+ }
1148
+ self.mutex.lockUncancelable(self.io);
1149
+ stream.in_poll = false;
1150
+ if (stream.orphaned) {
1151
+ self.destroyStreamLocked(stream);
1152
+ self.mutex.unlock(self.io);
1153
+ return;
1154
+ }
1155
+ if (finished) stream.finishing = false;
1156
+ self.mutex.unlock(self.io);
1157
+ if (finished) stream.drained.set(self.io);
1158
+ }
1159
+
1160
+ fn readStreamFrames(self: *Self, stream: *Stream) void {
1161
+ if (stream.file == null) {
1162
+ stream.file = std.Io.Dir.cwd().openFile(self.io, stream.path, .{}) catch null;
1163
+ }
1164
+ const file = stream.file orelse return;
1165
+ var buffer: [16 * 1024]u8 = undefined;
1166
+ read: while (true) {
1167
+ const slices: [1][]u8 = .{&buffer};
1168
+ const count = file.readStreaming(self.io, &slices) catch break :read;
1169
+ if (count == 0) break :read;
1170
+ stream.pending.appendSlice(self.allocator, buffer[0..count]) catch break :read;
1171
+ }
1172
+ while (stream.pending.items.len >= 4) {
1173
+ const frame_len = readU32(stream.pending.items, 0);
1174
+ if (stream.pending.items.len < 4 + frame_len) break;
1175
+ _ = stream.channel.post(stream.pending.items[4 .. 4 + frame_len]);
1176
+ stream.pending.replaceRange(self.allocator, 0, 4 + frame_len, &.{}) catch break;
1177
+ }
1178
+ }
1179
+
1180
+ // ---------------------------------------------------------- fence
1181
+
1182
+ /// The pairing check between the linked archive and this registry:
1183
+ /// the facade's fingerprint export against the registry's constant.
1184
+ /// A mismatch rejects every request rather than dispatching under a
1185
+ /// skewed contract — the in-process analog of the child's hello
1186
+ /// fence.
1187
+ fn verifyFingerprint(self: *Self) void {
1188
+ self.mutex.lockUncancelable(self.io);
1189
+ if (self.fingerprint_state != .unchecked) {
1190
+ self.mutex.unlock(self.io);
1191
+ return;
1192
+ }
1193
+ self.mutex.unlock(self.io);
1194
+ var ptr: [*]const u8 = undefined;
1195
+ var len: usize = 0;
1196
+ abi.contract_fingerprint_fn(&ptr, &len);
1197
+ const matches = len == Registry.contract_fingerprint.len and
1198
+ std.mem.eql(u8, ptr[0..len], &Registry.contract_fingerprint);
1199
+ self.mutex.lockUncancelable(self.io);
1200
+ if (self.fingerprint_state == .unchecked) {
1201
+ self.fingerprint_state = if (matches) .ok else .rejected;
1202
+ }
1203
+ self.mutex.unlock(self.io);
1204
+ }
1205
+
1206
+ // ---------------------------------------------------------- paths
1207
+
1208
+ fn cancellationPath(self: *Self, request_id: u32) ![]u8 {
1209
+ return self.markerPath("cancel", request_id);
1210
+ }
1211
+
1212
+ fn streamPath(self: *Self, request_id: u32) ![]u8 {
1213
+ return self.markerPath("stream", request_id);
1214
+ }
1215
+
1216
+ fn markerPath(self: *Self, comptime kind: []const u8, request_id: u32) ![]u8 {
1217
+ const root = if (self.cwd.len > 0) self.cwd else ".";
1218
+ const absolute_root = if (std.fs.path.isAbsolute(root))
1219
+ null
1220
+ else
1221
+ try std.Io.Dir.cwd().realPathFileAlloc(self.io, root, self.allocator);
1222
+ defer if (absolute_root) |path| self.allocator.free(path);
1223
+ const resolved_root = absolute_root orelse root;
1224
+ const pid: u32 = switch (builtin.os.tag) {
1225
+ .windows => std.os.windows.GetCurrentProcessId(),
1226
+ .wasi, .freestanding, .emscripten => 0,
1227
+ else => @intCast(@max(0, std.posix.system.getpid())),
1228
+ };
1229
+ return std.fmt.allocPrint(
1230
+ self.allocator,
1231
+ "{s}{c}.native-service-" ++ kind ++ "-{d}-{x}-{d}",
1232
+ .{ resolved_root, std.fs.path.sep, pid, @intFromPtr(self), request_id },
1233
+ );
1234
+ }
1235
+ };
1236
+ }
1237
+
1238
+ /// One trap error payload: the structured trap-teaching message's text
1239
+ /// field as JSON. The encoding is [0x01]text[0x1F]code[0x1F]symbol
1240
+ /// ([0x1F]remediation); a plain message rides whole.
1241
+ fn trapErrorJson(allocator: std.mem.Allocator, message: []const u8) ![]u8 {
1242
+ var text = message;
1243
+ var code: []const u8 = "";
1244
+ if (text.len > 0 and text[0] == 0x01) {
1245
+ text = text[1..];
1246
+ if (std.mem.indexOfScalar(u8, text, 0x1f)) |sep| {
1247
+ const rest = text[sep + 1 ..];
1248
+ text = text[0..sep];
1249
+ code = if (std.mem.indexOfScalar(u8, rest, 0x1f)) |next| rest[0..next] else rest;
1250
+ }
1251
+ }
1252
+ var out = std.Io.Writer.Allocating.init(allocator);
1253
+ errdefer out.deinit();
1254
+ const w = &out.writer;
1255
+ try w.writeAll("{\"kind\":\"service_trap\",\"message\":");
1256
+ try appendJsonString(w, std.mem.trimEnd(u8, text, "\n"));
1257
+ if (code.len > 0) {
1258
+ try w.writeAll(",\"code\":");
1259
+ try appendJsonString(w, code);
1260
+ }
1261
+ try w.writeAll("}");
1262
+ return out.toOwnedSlice();
1263
+ }
1264
+
1265
+ fn appendJsonString(w: *std.Io.Writer, value: []const u8) !void {
1266
+ try w.writeByte('"');
1267
+ for (value) |byte| switch (byte) {
1268
+ '"' => try w.writeAll("\\\""),
1269
+ '\\' => try w.writeAll("\\\\"),
1270
+ '\n' => try w.writeAll("\\n"),
1271
+ '\r' => try w.writeAll("\\r"),
1272
+ '\t' => try w.writeAll("\\t"),
1273
+ else => if (byte < 0x20)
1274
+ try w.print("\\u00{x:0>2}", .{byte})
1275
+ else
1276
+ try w.writeByte(byte),
1277
+ };
1278
+ try w.writeByte('"');
1279
+ }
1280
+
1281
+ fn readU32(bytes: []const u8, at: usize) u32 {
1282
+ return @as(u32, bytes[at]) |
1283
+ (@as(u32, bytes[at + 1]) << 8) |
1284
+ (@as(u32, bytes[at + 2]) << 16) |
1285
+ (@as(u32, bytes[at + 3]) << 24);
1286
+ }
1287
+
1288
+ fn readU64(bytes: []const u8, at: usize) u64 {
1289
+ return @as(u64, readU32(bytes, at)) | (@as(u64, readU32(bytes, at + 4)) << 32);
1290
+ }
1291
+
1292
+ test "trap errors carry the structured teaching's text and code as JSON" {
1293
+ const structured = "\x01scriptc: RangeError: pop() on an empty array\n\x1fSC4014\x1fnsc_svc_dispatch";
1294
+ const encoded = try trapErrorJson(std.testing.allocator, structured);
1295
+ defer std.testing.allocator.free(encoded);
1296
+ try std.testing.expectEqualStrings(
1297
+ "{\"kind\":\"service_trap\",\"message\":\"scriptc: RangeError: pop() on an empty array\",\"code\":\"SC4014\"}",
1298
+ encoded,
1299
+ );
1300
+
1301
+ const plain = try trapErrorJson(std.testing.allocator, "plain \"quoted\" failure");
1302
+ defer std.testing.allocator.free(plain);
1303
+ try std.testing.expectEqualStrings(
1304
+ "{\"kind\":\"service_trap\",\"message\":\"plain \\\"quoted\\\" failure\"}",
1305
+ plain,
1306
+ );
1307
+ }
1308
+
1309
+ test "pool defaults stay within the documented bounds" {
1310
+ const workers = defaultWorkerCount();
1311
+ try std.testing.expect(workers >= 1 and workers <= 4);
1312
+ try std.testing.expectEqual(service_host.default_request_timeout_ms, default_request_timeout_ms);
1313
+ try std.testing.expectEqual(service_host.cooperative_cancel_grace_ms, cooperative_cancel_grace_ms);
1314
+ }