@native-sdk/cli 0.8.4 → 0.9.1

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 (161) hide show
  1. package/build/app.zig +1178 -74
  2. package/build.zig +715 -17
  3. package/build.zig.zon +1 -0
  4. package/native-sdk.d.ts +10 -0
  5. package/package.json +12 -11
  6. package/packages/core/compile-surface/core.ts +435 -3
  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/merge_static_archives.mjs +78 -0
  12. package/packages/core/scripts/npm_static_spike.mjs +64 -0
  13. package/packages/core/scripts/run_external_core_compiler.mjs +122 -6
  14. package/packages/core/scripts/run_external_service_compiler.mjs +280 -0
  15. package/packages/core/scripts/stage_external_core.mjs +9 -1
  16. package/packages/core/scripts/stage_external_services.mjs +172 -0
  17. package/packages/core/scripts/surface_manifest_diff.mjs +253 -0
  18. package/packages/core/scripts/vendor_service_packages.mjs +189 -0
  19. package/packages/core/sdk/core.d.ts +224 -0
  20. package/packages/core/sdk/core.ts +694 -22
  21. package/packages/core/sdk/events.d.ts +89 -0
  22. package/packages/core/sdk/events.ts +128 -0
  23. package/packages/core/src/checker.ts +936 -15
  24. package/packages/core/src/cli.ts +156 -3
  25. package/packages/core/src/contract.ts +28 -5
  26. package/packages/core/src/devhost.ts +1876 -16
  27. package/packages/core/src/devhost_journal.mjs +183 -0
  28. package/packages/core/src/devhost_resolver.mjs +17 -1
  29. package/packages/core/src/devhost_service_worker.mjs +90 -0
  30. package/packages/core/src/diagnostics.ts +179 -22
  31. package/packages/core/src/frontend.ts +210 -34
  32. package/packages/core/src/infer.ts +24 -0
  33. package/packages/core/src/modules.ts +129 -80
  34. package/packages/core/src/service_contract.ts +597 -0
  35. package/packages/core/src/sqlite_cli.ts +93 -0
  36. package/packages/core/src/sqlite_codegen.ts +806 -0
  37. package/packages/core/src/sqlite_runtime_policy.ts +364 -0
  38. package/packages/core/src/typed_ast.ts +36 -8
  39. package/skill-data/automation/SKILL.md +1 -1
  40. package/skill-data/core/references/project-anatomy.md +1 -1
  41. package/skill-data/native-ui/SKILL.md +58 -5
  42. package/skill-data/ts-core/SKILL.md +123 -41
  43. package/skill-data/ts-services/SKILL.md +126 -0
  44. package/skill-data/ts-services/references/service-surface.md +604 -0
  45. package/skill-data/zig/SKILL.md +1 -1
  46. package/skills/native-sdk/SKILL.md +1 -1
  47. package/src/app_runner/no_migrations.zig +3 -0
  48. package/src/app_runner/no_services.zig +20 -0
  49. package/src/app_runner/root.zig +133 -4
  50. package/src/app_runner/ts_core_main.zig +254 -8
  51. package/src/app_runner/ts_core_mobile.zig +241 -0
  52. package/src/automation/protocol.zig +5 -1
  53. package/src/automation/snapshot.zig +31 -11
  54. package/src/embed/app_exports.zig +12 -1
  55. package/src/embed/c_api.zig +48 -2
  56. package/src/embed/conversions.zig +4 -5
  57. package/src/embed/host.zig +109 -1
  58. package/src/embed/root.zig +8 -0
  59. package/src/embed/tests.zig +241 -0
  60. package/src/embed/types.zig +51 -0
  61. package/src/embed/ui_host.zig +185 -5
  62. package/src/platform/android/NativeSdkActivity.java +131 -0
  63. package/src/platform/android/android_host.c +182 -1
  64. package/src/platform/android/native_sdk_app.h +17 -0
  65. package/src/platform/ios/native_sdk_app.h +17 -0
  66. package/src/platform/ios/uikit_host.m +115 -0
  67. package/src/platform/linux/cef_host.cpp +8 -2
  68. package/src/platform/linux/gtk_host.c +289 -22
  69. package/src/platform/linux/gtk_host.h +5 -1
  70. package/src/platform/linux/root.zig +109 -22
  71. package/src/platform/macos/appkit_host.h +24 -7
  72. package/src/platform/macos/appkit_host.m +686 -64
  73. package/src/platform/macos/cef_host.mm +400 -66
  74. package/src/platform/macos/root.zig +304 -47
  75. package/src/platform/null_platform.zig +435 -48
  76. package/src/platform/null_platform_tests.zig +113 -0
  77. package/src/platform/root.zig +19 -0
  78. package/src/platform/types.zig +281 -28
  79. package/src/platform/windows/root.zig +207 -27
  80. package/src/platform/windows/webview2_host.cpp +334 -51
  81. package/src/primitives/app_manifest/comptime_scene.zig +2 -0
  82. package/src/primitives/app_manifest/root.zig +4 -0
  83. package/src/primitives/app_manifest/tests.zig +3 -0
  84. package/src/primitives/app_manifest/types.zig +32 -0
  85. package/src/primitives/app_manifest/validation.zig +19 -1
  86. package/src/root.zig +53 -0
  87. package/src/runtime/api.zig +19 -0
  88. package/src/runtime/automation_commands.zig +35 -2
  89. package/src/runtime/automation_snapshot.zig +32 -20
  90. package/src/runtime/bridge_permission_tests.zig +58 -3
  91. package/src/runtime/bridge_responses.zig +4 -2
  92. package/src/runtime/builtin_bridge.zig +11 -1
  93. package/src/runtime/canvas_frame.zig +18 -11
  94. package/src/runtime/canvas_frame_animation_tests.zig +4 -0
  95. package/src/runtime/clock.zig +13 -1
  96. package/src/runtime/core.zig +145 -7
  97. package/src/runtime/credentials_store.zig +115 -0
  98. package/src/runtime/effects.zig +3701 -231
  99. package/src/runtime/effects_credentials_tests.zig +332 -0
  100. package/src/runtime/effects_file_tests.zig +587 -0
  101. package/src/runtime/effects_host_tests.zig +208 -1
  102. package/src/runtime/effects_notification_tests.zig +11 -0
  103. package/src/runtime/effects_relational_tests.zig +314 -0
  104. package/src/runtime/effects_store_tests.zig +211 -0
  105. package/src/runtime/file_access.zig +400 -0
  106. package/src/runtime/file_effect_crash_helper.zig +28 -0
  107. package/src/runtime/file_effect_crash_tests.zig +37 -0
  108. package/src/runtime/flow.zig +35 -10
  109. package/src/runtime/gpu_surface_events.zig +6 -1
  110. package/src/runtime/native_command_event_tests.zig +86 -2
  111. package/src/runtime/persist_store.zig +666 -0
  112. package/src/runtime/pty.zig +5 -2
  113. package/src/runtime/record_store.zig +788 -0
  114. package/src/runtime/relational_store.zig +854 -0
  115. package/src/runtime/root.zig +54 -0
  116. package/src/runtime/runtime_event_tests.zig +70 -0
  117. package/src/runtime/service_host.zig +711 -0
  118. package/src/runtime/service_pool.zig +1314 -0
  119. package/src/runtime/session_blobs.zig +4 -1
  120. package/src/runtime/session_journal.zig +158 -5
  121. package/src/runtime/session_record.zig +215 -0
  122. package/src/runtime/session_replay.zig +206 -11
  123. package/src/runtime/session_tests.zig +81 -0
  124. package/src/runtime/shell_layout.zig +1 -0
  125. package/src/runtime/shell_layout_tests.zig +120 -0
  126. package/src/runtime/sqlite_engine.zig +474 -0
  127. package/src/runtime/state.zig +16 -0
  128. package/src/runtime/system_services.zig +170 -38
  129. package/src/runtime/tests.zig +4 -0
  130. package/src/runtime/ts_core_host.zig +1067 -95
  131. package/src/runtime/ts_core_host_tests.zig +325 -11
  132. package/src/runtime/ts_ui_app.zig +953 -2
  133. package/src/runtime/ui_app.zig +434 -96
  134. package/src/runtime/ui_app_tests.zig +287 -11
  135. package/src/runtime/ui_app_window_tests.zig +61 -7
  136. package/src/runtime/validation.zig +42 -0
  137. package/src/runtime/view.zig +9 -0
  138. package/src/runtime/window_storage.zig +1 -0
  139. package/src/runtime/window_view_runtime.zig +2 -3
  140. package/src/runtime/window_views.zig +19 -0
  141. package/src/tooling/android.zig +21 -16
  142. package/src/tooling/db.zig +160 -0
  143. package/src/tooling/ios.zig +7 -1
  144. package/src/tooling/manifest.zig +214 -2
  145. package/src/tooling/package.zig +116 -0
  146. package/src/tooling/raw_manifest.zig +30 -0
  147. package/src/tooling/root.zig +1 -0
  148. package/src/tooling/templates.zig +189 -4
  149. package/src/tooling/ts_core.zig +366 -17
  150. package/src/tooling/verbs.zig +7 -0
  151. package/third_party/sqlite/README.md +13 -0
  152. package/third_party/sqlite/sqlite3.c +269649 -0
  153. package/third_party/sqlite/sqlite3.h +14349 -0
  154. package/tools/corewire/core_abi.zig +14 -2
  155. package/tools/corewire/emit.zig +98 -29
  156. package/tools/corewire/emit_facade.zig +442 -27
  157. package/tools/corewire/emit_profile.zig +6 -2
  158. package/tools/corewire/emit_service.zig +924 -0
  159. package/tools/corewire/main.zig +122 -0
  160. package/tools/corewire/service_contract.zig +250 -0
  161. package/tools/corewire/sidecar.zig +26 -15
@@ -0,0 +1,666 @@
1
+ //! Engine-owned model snapshot storage.
2
+ //!
3
+ //! The app core supplies only its canonical committed-model bytes. This
4
+ //! module owns placement beneath the already-resolved app data directory,
5
+ //! envelopes those bytes with version/shape metadata, and installs snapshots
6
+ //! atomically. The previous valid primary is retained as one backup
7
+ //! generation; restore consults it only when the primary is missing or
8
+ //! structurally corrupt.
9
+
10
+ const std = @import("std");
11
+
12
+ pub const max_snapshot_bytes: usize = 16 * 1024 * 1024;
13
+ pub const store_format: u32 = 1;
14
+ pub const snapshot_name = "snapshot.nsd";
15
+ pub const backup_name = "snapshot.nsd.bak";
16
+
17
+ const magic = "NSDPST01".*;
18
+ const checksum_len = 16;
19
+ const header_len = magic.len + 4 + 4 + 8 + 8 + 8 + checksum_len;
20
+
21
+ pub const Outcome = enum(u8) {
22
+ ok,
23
+ none,
24
+ corrupt,
25
+ version_unknown,
26
+ migrate_failed,
27
+ io_failed,
28
+ rejected,
29
+ };
30
+
31
+ pub const Config = struct {
32
+ schema_version: u64,
33
+ model_fingerprint: u64,
34
+ snapshot_format: u32,
35
+ };
36
+
37
+ pub const RestoreResult = struct {
38
+ outcome: Outcome,
39
+ bytes: []u8 = &.{},
40
+ used_backup: bool = false,
41
+ migration_from_version: ?u64 = null,
42
+
43
+ pub fn deinit(self: *RestoreResult, allocator: std.mem.Allocator) void {
44
+ if (self.bytes.len > 0) allocator.free(self.bytes);
45
+ self.* = .{ .outcome = .none };
46
+ }
47
+ };
48
+
49
+ pub const Store = struct {
50
+ io: std.Io,
51
+ allocator: std.mem.Allocator,
52
+ data_dir: []const u8,
53
+ config: Config,
54
+
55
+ pub fn init(io: std.Io, allocator: std.mem.Allocator, data_dir: []const u8, config: Config) Store {
56
+ return .{ .io = io, .allocator = allocator, .data_dir = data_dir, .config = config };
57
+ }
58
+
59
+ pub fn write(self: Store, snapshot: []const u8) Outcome {
60
+ if (snapshot.len > max_snapshot_bytes) return .rejected;
61
+ if (self.data_dir.len == 0) return .io_failed;
62
+
63
+ const cwd = std.Io.Dir.cwd();
64
+ cwd.createDirPath(self.io, self.data_dir) catch return .io_failed;
65
+
66
+ var primary_buffer: [std.fs.max_path_bytes]u8 = undefined;
67
+ const primary_path = joinPath(&primary_buffer, self.data_dir, snapshot_name) orelse return .io_failed;
68
+ var backup_buffer: [std.fs.max_path_bytes]u8 = undefined;
69
+ const backup_path = joinPath(&backup_buffer, self.data_dir, backup_name) orelse return .io_failed;
70
+
71
+ // An older binary must not displace either generation written by a
72
+ // newer schema. Checking the backup separately matters when the
73
+ // future primary is torn: repeated rollback writes must not erase the
74
+ // last recoverable future generation.
75
+ if (cwd.readFileAlloc(self.io, backup_path, self.allocator, .limited(header_len + max_snapshot_bytes))) |previous| {
76
+ defer self.allocator.free(previous);
77
+ if (decodeEnvelope(previous, null) == .valid and envelopeSchemaVersion(previous) > self.config.schema_version) {
78
+ return .version_unknown;
79
+ }
80
+ } else |_| {}
81
+
82
+ // Preserve only a structurally sound primary. A corrupt primary must
83
+ // never replace the last known-good backup.
84
+ if (cwd.readFileAlloc(self.io, primary_path, self.allocator, .limited(header_len + max_snapshot_bytes))) |previous| {
85
+ defer self.allocator.free(previous);
86
+ if (decodeEnvelope(previous, null) == .valid) {
87
+ if (envelopeSchemaVersion(previous) > self.config.schema_version) return .version_unknown;
88
+ atomicWrite(self.io, cwd, backup_path, previous) catch return .io_failed;
89
+ }
90
+ } else |_| {}
91
+
92
+ const envelope = self.allocator.alloc(u8, header_len + snapshot.len) catch return .io_failed;
93
+ defer self.allocator.free(envelope);
94
+ encodeEnvelope(envelope, self.config, snapshot);
95
+ atomicWrite(self.io, cwd, primary_path, envelope) catch return .io_failed;
96
+ return .ok;
97
+ }
98
+
99
+ pub fn restore(self: Store) RestoreResult {
100
+ if (self.data_dir.len == 0) return .{ .outcome = .io_failed };
101
+ var primary_buffer: [std.fs.max_path_bytes]u8 = undefined;
102
+ const primary_path = joinPath(&primary_buffer, self.data_dir, snapshot_name) orelse return .{ .outcome = .io_failed };
103
+ var backup_buffer: [std.fs.max_path_bytes]u8 = undefined;
104
+ const backup_path = joinPath(&backup_buffer, self.data_dir, backup_name) orelse return .{ .outcome = .io_failed };
105
+
106
+ const primary = self.readOne(primary_path);
107
+ switch (primary.outcome) {
108
+ .ok, .version_unknown, .migrate_failed => return primary,
109
+ .none, .corrupt, .io_failed => {},
110
+ .rejected => unreachable,
111
+ }
112
+
113
+ var backup = self.readOne(backup_path);
114
+ switch (backup.outcome) {
115
+ .ok => {
116
+ backup.used_backup = true;
117
+ return backup;
118
+ },
119
+ .version_unknown, .migrate_failed => return backup,
120
+ .none => return if (primary.outcome == .none)
121
+ .{ .outcome = .none }
122
+ else
123
+ .{ .outcome = primary.outcome },
124
+ .corrupt => return .{ .outcome = if (primary.outcome == .none) .corrupt else primary.outcome },
125
+ .io_failed => return .{ .outcome = if (primary.outcome == .none) .io_failed else primary.outcome },
126
+ .rejected => unreachable,
127
+ }
128
+ }
129
+
130
+ fn readOne(self: Store, path: []const u8) RestoreResult {
131
+ const bytes = std.Io.Dir.cwd().readFileAlloc(
132
+ self.io,
133
+ path,
134
+ self.allocator,
135
+ .limited(header_len + max_snapshot_bytes),
136
+ ) catch |err| return .{ .outcome = if (err == error.FileNotFound) .none else .io_failed };
137
+ defer self.allocator.free(bytes);
138
+
139
+ const decoded = decodeEnvelope(bytes, self.config);
140
+ switch (decoded) {
141
+ .valid => |body| {
142
+ const copy = self.allocator.dupe(u8, body) catch return .{ .outcome = .io_failed };
143
+ return .{ .outcome = .ok, .bytes = copy };
144
+ },
145
+ .corrupt => return .{ .outcome = .corrupt },
146
+ .future_version => return .{ .outcome = .version_unknown },
147
+ .migration_required => |old| {
148
+ const copy = self.allocator.dupe(u8, old.body) catch return .{ .outcome = .io_failed };
149
+ return .{ .outcome = .migrate_failed, .bytes = copy, .migration_from_version = old.version };
150
+ },
151
+ }
152
+ }
153
+ };
154
+
155
+ /// Optional worker-to-host terminal hook. Only failed write outcomes are
156
+ /// reported: successful fire-and-forget persists stay silent, while every
157
+ /// failure crosses the host's effect boundary as a routed Msg.
158
+ pub const OutcomeHandler = struct {
159
+ context: *anyopaque,
160
+ report_fn: *const fn (context: *anyopaque, outcome: Outcome) void,
161
+ };
162
+
163
+ /// Host-side trailing-edge persistence. Command dispatch only copies the
164
+ /// latest committed snapshot into this coordinator; filesystem work stays off
165
+ /// the update/event-loop thread. A reissue replaces the pending bytes, an
166
+ /// issue during a write becomes the next generation, and `deinit` force-flushes
167
+ /// the tail before returning.
168
+ ///
169
+ /// `allocator` must be safe to use from the coordinator worker. Shipping
170
+ /// runners use the page allocator.
171
+ pub const Coordinator = struct {
172
+ store: Store,
173
+ debounce_ms: u32,
174
+ mutex: std.Io.Mutex = .init,
175
+ condition: std.Io.Condition = .init,
176
+ pending: ?[]u8 = null,
177
+ generation: u64 = 0,
178
+ writing: bool = false,
179
+ flush_requested: bool = false,
180
+ stopping: bool = false,
181
+ thread: ?std.Thread = null,
182
+ outcome_handler: ?OutcomeHandler = null,
183
+
184
+ pub fn start(self: *Coordinator, store: Store, debounce_ms: u32) !void {
185
+ try self.startWithOutcomeHandler(store, debounce_ms, null);
186
+ }
187
+
188
+ pub fn startWithOutcomeHandler(self: *Coordinator, store: Store, debounce_ms: u32, outcome_handler: ?OutcomeHandler) !void {
189
+ self.* = .{ .store = store, .debounce_ms = debounce_ms, .outcome_handler = outcome_handler };
190
+ self.thread = try std.Thread.spawn(.{}, workerMain, .{self});
191
+ }
192
+
193
+ /// Queue the newest committed-model bytes. Rejections are synchronous so
194
+ /// an over-bound snapshot is never silently dropped; I/O outcomes are
195
+ /// reported by the worker's closed enum through `OutcomeHandler`.
196
+ pub fn enqueue(self: *Coordinator, snapshot: []const u8) Outcome {
197
+ if (snapshot.len > max_snapshot_bytes) return .rejected;
198
+ const copy = self.store.allocator.dupe(u8, snapshot) catch return .io_failed;
199
+ self.mutex.lockUncancelable(self.store.io);
200
+ defer self.mutex.unlock(self.store.io);
201
+ if (self.stopping) {
202
+ self.store.allocator.free(copy);
203
+ return .rejected;
204
+ }
205
+ if (self.pending) |previous| self.store.allocator.free(previous);
206
+ self.pending = copy;
207
+ self.generation +%= 1;
208
+ self.condition.signal(self.store.io);
209
+ return .ok;
210
+ }
211
+
212
+ pub fn deinit(self: *Coordinator) void {
213
+ self.mutex.lockUncancelable(self.store.io);
214
+ self.stopping = true;
215
+ self.condition.signal(self.store.io);
216
+ self.mutex.unlock(self.store.io);
217
+ if (self.thread) |thread| thread.join();
218
+ self.thread = null;
219
+ }
220
+
221
+ /// Force the current tail to stable storage. Used by platform
222
+ /// deactivate/background and stop hooks so the debounce window cannot
223
+ /// lose the last committed update.
224
+ pub fn flush(self: *Coordinator) void {
225
+ self.mutex.lockUncancelable(self.store.io);
226
+ self.flush_requested = true;
227
+ self.condition.signal(self.store.io);
228
+ while ((self.pending != null or self.writing) and !self.stopping) {
229
+ self.condition.waitUncancelable(self.store.io, &self.mutex);
230
+ }
231
+ self.flush_requested = false;
232
+ self.mutex.unlock(self.store.io);
233
+ }
234
+
235
+ fn workerMain(self: *Coordinator) void {
236
+ while (true) {
237
+ self.mutex.lockUncancelable(self.store.io);
238
+ while (self.pending == null and !self.stopping) {
239
+ self.condition.waitUncancelable(self.store.io, &self.mutex);
240
+ }
241
+ if (self.stopping) {
242
+ const tail = self.pending;
243
+ self.pending = null;
244
+ self.mutex.unlock(self.store.io);
245
+ if (tail) |bytes| {
246
+ const outcome = self.store.write(bytes);
247
+ self.store.allocator.free(bytes);
248
+ self.report(outcome);
249
+ }
250
+ return;
251
+ }
252
+ var observed_generation = self.generation;
253
+ const force = self.flush_requested;
254
+ self.mutex.unlock(self.store.io);
255
+
256
+ // Io.Condition has no timed wait. Polling in short, bounded sleeps
257
+ // keeps shutdown responsive while preserving a true trailing edge:
258
+ // every replacement restarts the full debounce window.
259
+ var waited_ms: u32 = 0;
260
+ while (!force and waited_ms < self.debounce_ms) {
261
+ const slice_ms = @min(self.debounce_ms - waited_ms, 10);
262
+ std.Io.sleep(self.store.io, std.Io.Duration.fromMilliseconds(slice_ms), .awake) catch {};
263
+ waited_ms += slice_ms;
264
+ self.mutex.lockUncancelable(self.store.io);
265
+ if (self.stopping) {
266
+ self.mutex.unlock(self.store.io);
267
+ break;
268
+ }
269
+ if (self.flush_requested) {
270
+ self.mutex.unlock(self.store.io);
271
+ break;
272
+ }
273
+ if (self.generation != observed_generation) {
274
+ observed_generation = self.generation;
275
+ waited_ms = 0;
276
+ }
277
+ self.mutex.unlock(self.store.io);
278
+ }
279
+
280
+ self.mutex.lockUncancelable(self.store.io);
281
+ if (self.stopping) {
282
+ self.mutex.unlock(self.store.io);
283
+ continue;
284
+ }
285
+ const bytes = self.pending.?;
286
+ self.pending = null;
287
+ self.writing = true;
288
+ self.mutex.unlock(self.store.io);
289
+ const outcome = self.store.write(bytes);
290
+ self.store.allocator.free(bytes);
291
+ self.report(outcome);
292
+ self.mutex.lockUncancelable(self.store.io);
293
+ self.writing = false;
294
+ if (self.pending == null) {
295
+ self.flush_requested = false;
296
+ self.condition.broadcast(self.store.io);
297
+ }
298
+ self.mutex.unlock(self.store.io);
299
+ // An enqueue during `write` left `pending` populated; the next
300
+ // iteration gives it its own trailing-edge window.
301
+ }
302
+ }
303
+
304
+ fn report(self: *Coordinator, outcome: Outcome) void {
305
+ if (outcome == .ok) return;
306
+ if (self.outcome_handler) |handler| {
307
+ handler.report_fn(handler.context, outcome);
308
+ } else {
309
+ std.log.err("model persistence write failed: {s}", .{@tagName(outcome)});
310
+ }
311
+ }
312
+ };
313
+
314
+ const Decoded = union(enum) {
315
+ valid: []const u8,
316
+ corrupt,
317
+ future_version,
318
+ migration_required: struct { body: []const u8, version: u64 },
319
+ };
320
+
321
+ fn decodeEnvelope(bytes: []const u8, expected: ?Config) Decoded {
322
+ if (bytes.len < header_len) return .corrupt;
323
+ if (!std.mem.eql(u8, bytes[0..magic.len], &magic)) return .corrupt;
324
+ var at: usize = magic.len;
325
+ const format = takeInt(u32, bytes, &at);
326
+ const snapshot_format = takeInt(u32, bytes, &at);
327
+ const schema_version = takeInt(u64, bytes, &at);
328
+ const model_fingerprint = takeInt(u64, bytes, &at);
329
+ const body_len_u64 = takeInt(u64, bytes, &at);
330
+ const checksum_at = at;
331
+ const checksum = bytes[checksum_at .. checksum_at + checksum_len];
332
+ at += checksum_len;
333
+ if (format != store_format or body_len_u64 > max_snapshot_bytes) return .corrupt;
334
+ const body_len = std.math.cast(usize, body_len_u64) orelse return .corrupt;
335
+ if (bytes.len != header_len + body_len) return .corrupt;
336
+ const body = bytes[at..];
337
+ const actual = checksumEnvelope(bytes[0..checksum_at], body);
338
+ if (!std.crypto.timing_safe.eql([checksum_len]u8, checksum[0..checksum_len].*, actual)) return .corrupt;
339
+
340
+ if (expected) |config| {
341
+ if (schema_version > config.schema_version) return .future_version;
342
+ if (snapshot_format != config.snapshot_format) return .corrupt;
343
+ if (schema_version < config.schema_version) return .{ .migration_required = .{ .body = body, .version = schema_version } };
344
+ if (model_fingerprint != config.model_fingerprint) return .corrupt;
345
+ }
346
+ return .{ .valid = body };
347
+ }
348
+
349
+ fn encodeEnvelope(out: []u8, config: Config, snapshot: []const u8) void {
350
+ std.debug.assert(out.len == header_len + snapshot.len);
351
+ @memcpy(out[0..magic.len], &magic);
352
+ var at: usize = magic.len;
353
+ putInt(u32, out, &at, store_format);
354
+ putInt(u32, out, &at, config.snapshot_format);
355
+ putInt(u64, out, &at, config.schema_version);
356
+ putInt(u64, out, &at, config.model_fingerprint);
357
+ putInt(u64, out, &at, snapshot.len);
358
+ const checksum_at = at;
359
+ at += checksum_len;
360
+ @memcpy(out[at..], snapshot);
361
+ const checksum = checksumEnvelope(out[0..checksum_at], snapshot);
362
+ @memcpy(out[checksum_at .. checksum_at + checksum_len], &checksum);
363
+ }
364
+
365
+ fn checksumEnvelope(header: []const u8, body: []const u8) [checksum_len]u8 {
366
+ var digest: [32]u8 = undefined;
367
+ var hasher = std.crypto.hash.sha2.Sha256.init(.{});
368
+ hasher.update(header);
369
+ hasher.update(body);
370
+ hasher.final(&digest);
371
+ return digest[0..checksum_len].*;
372
+ }
373
+
374
+ fn putInt(comptime T: type, out: []u8, at: *usize, value: T) void {
375
+ const size = @sizeOf(T);
376
+ std.mem.writeInt(T, out[at.*..][0..size], value, .little);
377
+ at.* += size;
378
+ }
379
+
380
+ fn takeInt(comptime T: type, bytes: []const u8, at: *usize) T {
381
+ const size = @sizeOf(T);
382
+ const value = std.mem.readInt(T, bytes[at.*..][0..size], .little);
383
+ at.* += size;
384
+ return value;
385
+ }
386
+
387
+ /// Read the schema field from an envelope already accepted by the structural
388
+ /// `decodeEnvelope(bytes, null)` check.
389
+ fn envelopeSchemaVersion(bytes: []const u8) u64 {
390
+ const at = magic.len + @sizeOf(u32) + @sizeOf(u32);
391
+ return std.mem.readInt(u64, bytes[at..][0..@sizeOf(u64)], .little);
392
+ }
393
+
394
+ fn joinPath(buffer: []u8, dir: []const u8, name: []const u8) ?[]const u8 {
395
+ return std.fmt.bufPrint(buffer, "{s}{s}{s}", .{ dir, std.fs.path.sep_str, name }) catch null;
396
+ }
397
+
398
+ fn atomicWrite(io: std.Io, dir: std.Io.Dir, path: []const u8, bytes: []const u8) !void {
399
+ var atomic = try dir.createFileAtomic(io, path, .{ .make_path = true, .replace = true });
400
+ defer atomic.deinit(io);
401
+ try atomic.file.writePositionalAll(io, bytes, 0);
402
+ try atomic.file.sync(io);
403
+ try atomic.replace(io);
404
+ }
405
+
406
+ fn testDirPath(tmp: *const std.testing.TmpDir, buffer: []u8) ![]const u8 {
407
+ return std.fmt.bufPrint(buffer, ".zig-cache/tmp/{s}/persist", .{tmp.sub_path[0..]});
408
+ }
409
+
410
+ test "snapshot store round-trips metadata and bytes" {
411
+ var tmp = std.testing.tmpDir(.{});
412
+ defer tmp.cleanup();
413
+ var path_buffer: [256]u8 = undefined;
414
+ const path = try testDirPath(&tmp, &path_buffer);
415
+ const config: Config = .{ .schema_version = 3, .model_fingerprint = 0x1234, .snapshot_format = 1 };
416
+ const store = Store.init(std.testing.io, std.testing.allocator, path, config);
417
+
418
+ try std.testing.expectEqual(Outcome.none, store.restore().outcome);
419
+ try std.testing.expectEqual(Outcome.ok, store.write("canonical model bytes"));
420
+ var restored = store.restore();
421
+ defer restored.deinit(std.testing.allocator);
422
+ try std.testing.expectEqual(Outcome.ok, restored.outcome);
423
+ try std.testing.expectEqualStrings("canonical model bytes", restored.bytes);
424
+ try std.testing.expect(!restored.used_backup);
425
+ }
426
+
427
+ test "snapshot store falls back to the previous generation when primary is torn" {
428
+ var tmp = std.testing.tmpDir(.{});
429
+ defer tmp.cleanup();
430
+ var path_buffer: [256]u8 = undefined;
431
+ const path = try testDirPath(&tmp, &path_buffer);
432
+ const config: Config = .{ .schema_version = 1, .model_fingerprint = 7, .snapshot_format = 1 };
433
+ const store = Store.init(std.testing.io, std.testing.allocator, path, config);
434
+
435
+ try std.testing.expectEqual(Outcome.ok, store.write("first"));
436
+ try std.testing.expectEqual(Outcome.ok, store.write("second"));
437
+ var primary_buffer: [512]u8 = undefined;
438
+ const primary = joinPath(&primary_buffer, path, snapshot_name).?;
439
+ try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = primary, .data = "torn" });
440
+
441
+ var restored = store.restore();
442
+ defer restored.deinit(std.testing.allocator);
443
+ try std.testing.expectEqual(Outcome.ok, restored.outcome);
444
+ try std.testing.expectEqualStrings("first", restored.bytes);
445
+ try std.testing.expect(restored.used_backup);
446
+ }
447
+
448
+ test "snapshot store falls back when primary metadata is corrupted" {
449
+ var tmp = std.testing.tmpDir(.{});
450
+ defer tmp.cleanup();
451
+ var path_buffer: [256]u8 = undefined;
452
+ const path = try testDirPath(&tmp, &path_buffer);
453
+ const config: Config = .{ .schema_version = 1, .model_fingerprint = 7, .snapshot_format = 1 };
454
+ const store = Store.init(std.testing.io, std.testing.allocator, path, config);
455
+
456
+ try std.testing.expectEqual(Outcome.ok, store.write("first"));
457
+ try std.testing.expectEqual(Outcome.ok, store.write("second"));
458
+ var primary_buffer: [512]u8 = undefined;
459
+ const primary = joinPath(&primary_buffer, path, snapshot_name).?;
460
+ const envelope = try std.Io.Dir.cwd().readFileAlloc(
461
+ std.testing.io,
462
+ primary,
463
+ std.testing.allocator,
464
+ .limited(header_len + max_snapshot_bytes),
465
+ );
466
+ defer std.testing.allocator.free(envelope);
467
+ envelope[magic.len + @sizeOf(u32) + @sizeOf(u32)] ^= 0x80;
468
+ try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = primary, .data = envelope });
469
+
470
+ var restored = store.restore();
471
+ defer restored.deinit(std.testing.allocator);
472
+ try std.testing.expectEqual(Outcome.ok, restored.outcome);
473
+ try std.testing.expectEqualStrings("first", restored.bytes);
474
+ try std.testing.expect(restored.used_backup);
475
+ }
476
+
477
+ test "snapshot store does not mistake a corrupt orphaned backup for first boot" {
478
+ var tmp = std.testing.tmpDir(.{});
479
+ defer tmp.cleanup();
480
+ var path_buffer: [256]u8 = undefined;
481
+ const path = try testDirPath(&tmp, &path_buffer);
482
+ try std.Io.Dir.cwd().createDirPath(std.testing.io, path);
483
+ var backup_buffer: [512]u8 = undefined;
484
+ const backup = joinPath(&backup_buffer, path, backup_name).?;
485
+ try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = backup, .data = "torn" });
486
+
487
+ const store = Store.init(std.testing.io, std.testing.allocator, path, .{
488
+ .schema_version = 1,
489
+ .model_fingerprint = 7,
490
+ .snapshot_format = 1,
491
+ });
492
+ try std.testing.expectEqual(Outcome.corrupt, store.restore().outcome);
493
+ }
494
+
495
+ test "snapshot store keeps the live generation when interrupted before atomic replace" {
496
+ var tmp = std.testing.tmpDir(.{});
497
+ defer tmp.cleanup();
498
+ var path_buffer: [256]u8 = undefined;
499
+ const path = try testDirPath(&tmp, &path_buffer);
500
+ const config: Config = .{ .schema_version = 1, .model_fingerprint = 7, .snapshot_format = 1 };
501
+ const store = Store.init(std.testing.io, std.testing.allocator, path, config);
502
+ try std.testing.expectEqual(Outcome.ok, store.write("stable"));
503
+
504
+ // Exercise the exact primitive atomicWrite uses, but stop after the
505
+ // temporary file is synced and before replace. Deinit removes the
506
+ // abandoned same-directory temporary file; the installed generation is
507
+ // untouched, which is the process-kill boundary the store relies on.
508
+ var primary_buffer: [512]u8 = undefined;
509
+ const primary = joinPath(&primary_buffer, path, snapshot_name).?;
510
+ var interrupted = try std.Io.Dir.cwd().createFileAtomic(std.testing.io, primary, .{ .make_path = true, .replace = true });
511
+ try interrupted.file.writePositionalAll(std.testing.io, "not installed", 0);
512
+ try interrupted.file.sync(std.testing.io);
513
+ interrupted.deinit(std.testing.io);
514
+
515
+ var restored = store.restore();
516
+ defer restored.deinit(std.testing.allocator);
517
+ try std.testing.expectEqual(Outcome.ok, restored.outcome);
518
+ try std.testing.expectEqualStrings("stable", restored.bytes);
519
+ try std.testing.expect(!restored.used_backup);
520
+ }
521
+
522
+ test "snapshot store closes version and shape mismatches" {
523
+ var tmp = std.testing.tmpDir(.{});
524
+ defer tmp.cleanup();
525
+ var path_buffer: [256]u8 = undefined;
526
+ const path = try testDirPath(&tmp, &path_buffer);
527
+ const old = Store.init(std.testing.io, std.testing.allocator, path, .{ .schema_version = 2, .model_fingerprint = 9, .snapshot_format = 1 });
528
+ try std.testing.expectEqual(Outcome.ok, old.write("model"));
529
+
530
+ const newer = Store.init(std.testing.io, std.testing.allocator, path, .{ .schema_version = 3, .model_fingerprint = 10, .snapshot_format = 1 });
531
+ var migration = newer.restore();
532
+ defer migration.deinit(std.testing.allocator);
533
+ try std.testing.expectEqual(Outcome.migrate_failed, migration.outcome);
534
+ try std.testing.expectEqual(@as(?u64, 2), migration.migration_from_version);
535
+ try std.testing.expectEqualStrings("model", migration.bytes);
536
+ const older = Store.init(std.testing.io, std.testing.allocator, path, .{ .schema_version = 1, .model_fingerprint = 9, .snapshot_format = 1 });
537
+ try std.testing.expectEqual(Outcome.version_unknown, older.restore().outcome);
538
+ const changed = Store.init(std.testing.io, std.testing.allocator, path, .{ .schema_version = 2, .model_fingerprint = 10, .snapshot_format = 1 });
539
+ try std.testing.expectEqual(Outcome.corrupt, changed.restore().outcome);
540
+ }
541
+
542
+ test "snapshot store refuses downgrade writes and preserves the future generation" {
543
+ var tmp = std.testing.tmpDir(.{});
544
+ defer tmp.cleanup();
545
+ var path_buffer: [256]u8 = undefined;
546
+ const path = try testDirPath(&tmp, &path_buffer);
547
+ const future = Store.init(std.testing.io, std.testing.allocator, path, .{
548
+ .schema_version = 3,
549
+ .model_fingerprint = 30,
550
+ .snapshot_format = 2,
551
+ });
552
+ try std.testing.expectEqual(Outcome.ok, future.write("future model"));
553
+
554
+ const rollback = Store.init(std.testing.io, std.testing.allocator, path, .{
555
+ .schema_version = 2,
556
+ .model_fingerprint = 20,
557
+ .snapshot_format = 1,
558
+ });
559
+ try std.testing.expectEqual(Outcome.version_unknown, rollback.restore().outcome);
560
+ try std.testing.expectEqual(Outcome.version_unknown, rollback.write("rollback model"));
561
+ try std.testing.expectEqual(Outcome.version_unknown, rollback.write("second rollback model"));
562
+
563
+ var restored = future.restore();
564
+ defer restored.deinit(std.testing.allocator);
565
+ try std.testing.expectEqual(Outcome.ok, restored.outcome);
566
+ try std.testing.expectEqualStrings("future model", restored.bytes);
567
+
568
+ var backup_buffer: [512]u8 = undefined;
569
+ const backup = joinPath(&backup_buffer, path, backup_name).?;
570
+ const bytes = std.Io.Dir.cwd().readFileAlloc(std.testing.io, backup, std.testing.allocator, .limited(header_len + max_snapshot_bytes));
571
+ try std.testing.expectError(error.FileNotFound, bytes);
572
+
573
+ // A torn future primary still leaves a future backup. Rollback writes must
574
+ // protect that last recoverable generation too.
575
+ try std.testing.expectEqual(Outcome.ok, future.write("newest future model"));
576
+ var primary_buffer: [512]u8 = undefined;
577
+ const primary = joinPath(&primary_buffer, path, snapshot_name).?;
578
+ try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = primary, .data = "torn" });
579
+ try std.testing.expectEqual(Outcome.version_unknown, rollback.write("rollback over torn primary"));
580
+
581
+ var recovered = future.restore();
582
+ defer recovered.deinit(std.testing.allocator);
583
+ try std.testing.expectEqual(Outcome.ok, recovered.outcome);
584
+ try std.testing.expectEqualStrings("future model", recovered.bytes);
585
+ try std.testing.expect(recovered.used_backup);
586
+ }
587
+
588
+ test "snapshot store rejects over-bound models without touching disk" {
589
+ var tmp = std.testing.tmpDir(.{});
590
+ defer tmp.cleanup();
591
+ var path_buffer: [256]u8 = undefined;
592
+ const path = try testDirPath(&tmp, &path_buffer);
593
+ const store = Store.init(std.testing.io, std.testing.allocator, path, .{ .schema_version = 1, .model_fingerprint = 1, .snapshot_format = 1 });
594
+ const oversized = try std.testing.allocator.alloc(u8, max_snapshot_bytes + 1);
595
+ defer std.testing.allocator.free(oversized);
596
+ try std.testing.expectEqual(Outcome.rejected, store.write(oversized));
597
+ try std.testing.expectEqual(Outcome.none, store.restore().outcome);
598
+ }
599
+
600
+ test "snapshot coordinator coalesces to the trailing snapshot" {
601
+ var tmp = std.testing.tmpDir(.{});
602
+ defer tmp.cleanup();
603
+ var path_buffer: [256]u8 = undefined;
604
+ const path = try testDirPath(&tmp, &path_buffer);
605
+ const store = Store.init(std.testing.io, std.heap.page_allocator, path, .{ .schema_version = 1, .model_fingerprint = 1, .snapshot_format = 1 });
606
+ var coordinator: Coordinator = undefined;
607
+ try coordinator.start(store, 50);
608
+ try std.testing.expectEqual(Outcome.ok, coordinator.enqueue("superseded"));
609
+ try std.testing.expectEqual(Outcome.ok, coordinator.enqueue("latest"));
610
+ try std.Io.sleep(std.testing.io, std.Io.Duration.fromMilliseconds(80), .awake);
611
+ coordinator.deinit();
612
+
613
+ var restored = store.restore();
614
+ defer restored.deinit(std.heap.page_allocator);
615
+ try std.testing.expectEqual(Outcome.ok, restored.outcome);
616
+ try std.testing.expectEqualStrings("latest", restored.bytes);
617
+
618
+ var backup_buffer: [512]u8 = undefined;
619
+ const backup = joinPath(&backup_buffer, path, backup_name).?;
620
+ const bytes = std.Io.Dir.cwd().readFileAlloc(std.testing.io, backup, std.testing.allocator, .limited(header_len + max_snapshot_bytes));
621
+ try std.testing.expectError(error.FileNotFound, bytes);
622
+ }
623
+
624
+ test "snapshot coordinator force-flushes its tail on lifecycle flush" {
625
+ var tmp = std.testing.tmpDir(.{});
626
+ defer tmp.cleanup();
627
+ var path_buffer: [256]u8 = undefined;
628
+ const path = try testDirPath(&tmp, &path_buffer);
629
+ const store = Store.init(std.testing.io, std.heap.page_allocator, path, .{ .schema_version = 1, .model_fingerprint = 1, .snapshot_format = 1 });
630
+ var coordinator: Coordinator = undefined;
631
+ try coordinator.start(store, 60_000);
632
+ defer coordinator.deinit();
633
+ try std.testing.expectEqual(Outcome.ok, coordinator.enqueue("quit tail"));
634
+ coordinator.flush();
635
+
636
+ var restored = store.restore();
637
+ defer restored.deinit(std.heap.page_allocator);
638
+ try std.testing.expectEqual(Outcome.ok, restored.outcome);
639
+ try std.testing.expectEqualStrings("quit tail", restored.bytes);
640
+ }
641
+
642
+ test "snapshot coordinator reports worker I/O failures through its terminal hook" {
643
+ var tmp = std.testing.tmpDir(.{});
644
+ defer tmp.cleanup();
645
+ var path_buffer: [256]u8 = undefined;
646
+ const path = try testDirPath(&tmp, &path_buffer);
647
+ // A regular file at the would-be data directory makes createDirPath fail
648
+ // deterministically after the request has reached the worker.
649
+ try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = path, .data = "not a directory" });
650
+ const store = Store.init(std.testing.io, std.heap.page_allocator, path, .{ .schema_version = 1, .model_fingerprint = 1, .snapshot_format = 1 });
651
+ const Capture = struct {
652
+ seen: Outcome = .ok,
653
+
654
+ fn report(context: *anyopaque, outcome: Outcome) void {
655
+ const self: *@This() = @ptrCast(@alignCast(context));
656
+ self.seen = outcome;
657
+ }
658
+ };
659
+ var capture: Capture = .{};
660
+ var coordinator: Coordinator = undefined;
661
+ try coordinator.startWithOutcomeHandler(store, 60_000, .{ .context = &capture, .report_fn = Capture.report });
662
+ defer coordinator.deinit();
663
+ try std.testing.expectEqual(Outcome.ok, coordinator.enqueue("cannot land"));
664
+ coordinator.flush();
665
+ try std.testing.expectEqual(Outcome.io_failed, capture.seen);
666
+ }
@@ -924,7 +924,9 @@ const f_dupfd_cloexec: c_int = switch (builtin.os.tag) {
924
924
  fn errnoValue() c_int {
925
925
  return switch (builtin.os.tag) {
926
926
  .macos => c.__error().*,
927
- .linux => c.__errno_location().*,
927
+ // Bionic spells the errno accessor `__errno`; glibc and musl agree
928
+ // on `__errno_location`.
929
+ .linux => if (comptime builtin.abi.isAndroid()) c.__errno().* else c.__errno_location().*,
928
930
  else => 0,
929
931
  };
930
932
  }
@@ -962,7 +964,8 @@ const c = struct {
962
964
  extern "c" fn fcntl(fd: c_int, cmd: c_int, ...) c_int;
963
965
  extern "c" fn poll(fds: [*]Pollfd, nfds: c_uint, timeout: c_int) c_int;
964
966
  extern "c" fn __error() *c_int; // Darwin errno
965
- extern "c" fn __errno_location() *c_int; // Linux errno
967
+ extern "c" fn __errno_location() *c_int; // Linux errno (glibc/musl)
968
+ extern "c" fn __errno() *c_int; // Bionic errno
966
969
  };
967
970
 
968
971
  /// A nudge pipe for the io thread: [read end, write end]. BOTH ends are