instant_record 0.1.0 → 0.3.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 (198) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +58 -0
  3. data/README.md +267 -61
  4. data/app/controllers/instant_record/bootstraps_controller.rb +39 -12
  5. data/app/controllers/instant_record/events_controller.rb +58 -6
  6. data/app/controllers/instant_record/files_controller.rb +116 -0
  7. data/app/controllers/instant_record/mutations_controller.rb +84 -5
  8. data/app/controllers/instant_record/native_screens_controller.rb +60 -0
  9. data/app/controllers/instant_record/records_controller.rb +86 -8
  10. data/app/controllers/instant_record/shells_controller.rb +64 -0
  11. data/app/controllers/instant_record/sync_notices_controller.rb +81 -0
  12. data/app/helpers/instant_record/sync_notices_helper.rb +41 -0
  13. data/app/jobs/instant_record/shell_build_job.rb +16 -0
  14. data/app/models/instant_record/change.rb +36 -3
  15. data/app/models/instant_record/mutation_applier.rb +633 -50
  16. data/app/views/instant_record/sync_notices/_notices.html.erb +63 -0
  17. data/compiled/README.md +272 -0
  18. data/compiled/pipeline/browser_migrations.rb +18 -0
  19. data/compiled/pipeline/build.rb +13 -0
  20. data/compiled/pipeline/build_native.rb +14 -0
  21. data/compiled/pipeline/native/host.c +78 -0
  22. data/compiled/pipeline/native/instant_record_native.h +57 -0
  23. data/compiled/pipeline/native_shim.c +149 -0
  24. data/compiled/pipeline/reactor_shim.c +66 -0
  25. data/compiled/pipeline/sqlite/rh_shim.c +5 -0
  26. data/compiled/pipeline/sqlite_release.rb +43 -0
  27. data/compiled/toolchain.env.example +22 -0
  28. data/compiled/web/index.html +20 -0
  29. data/compiled/web/package-lock.json +884 -0
  30. data/compiled/web/package.json +17 -0
  31. data/compiled/web/src/app-host-core.js +556 -0
  32. data/compiled/web/src/app-host.js +16 -0
  33. data/compiled/web/src/branch-manager.js +140 -0
  34. data/compiled/web/src/branch-preview.js +397 -0
  35. data/compiled/web/src/changes.js +191 -0
  36. data/compiled/web/src/faults.js +172 -0
  37. data/compiled/web/src/flight-recorder.js +347 -0
  38. data/compiled/web/src/history-fill.js +68 -0
  39. data/compiled/web/src/http-headers.js +100 -0
  40. data/compiled/web/src/leader-election.js +705 -0
  41. data/compiled/web/src/main.js +608 -0
  42. data/compiled/web/src/manifest.js +112 -0
  43. data/compiled/web/src/opfs-wasi-core.js +109 -0
  44. data/compiled/web/src/opfs-wasi-file.js +8 -0
  45. data/compiled/web/src/reactor-runtime.js +1692 -0
  46. data/compiled/web/src/redactor.js +518 -0
  47. data/compiled/web/src/release-updates.js +48 -0
  48. data/compiled/web/src/replay.js +338 -0
  49. data/compiled/web/src/schema-recovery.js +204 -0
  50. data/compiled/web/src/server-request.js +68 -0
  51. data/compiled/web/src/sha256.js +98 -0
  52. data/compiled/web/src/shell.js +52 -0
  53. data/compiled/web/src/snapshot-store.js +38 -0
  54. data/compiled/web/src/sqlite-redactor.js +111 -0
  55. data/compiled/web/src/storage-backend.js +159 -0
  56. data/compiled/web/src/stream-leader.js +675 -0
  57. data/compiled/web/src/sync-context.js +91 -0
  58. data/compiled/web/src/sync-drain.js +104 -0
  59. data/compiled/web/src/sync-schedule.js +9 -0
  60. data/compiled/web/src/wasi-minimal.js +275 -0
  61. data/compiled/web/src/worker.js +39 -0
  62. data/compiled/web/vite.config.js +27 -0
  63. data/config/routes.rb +25 -0
  64. data/db/migrate/20261119000201_add_scope_to_instant_record_changes.rb +7 -0
  65. data/db/migrate/20261121000001_create_instant_record_sync_notices.rb +21 -0
  66. data/db/migrate/20261121000101_add_partition_to_instant_record_changes.rb +8 -0
  67. data/db/migrate/20261121230300_add_delay_line_to_instant_record_outbox.rb +10 -0
  68. data/exe/instant_record_mcp +6 -0
  69. data/frontend/LiveList.js +67 -0
  70. data/frontend/chord.js +79 -0
  71. data/frontend/file.js +65 -0
  72. data/frontend/files.js +738 -0
  73. data/frontend/focus.js +10 -0
  74. data/frontend/held.js +192 -0
  75. data/frontend/http.js +76 -0
  76. data/frontend/index.js +53 -0
  77. data/frontend/keyboard.js +56 -0
  78. data/frontend/live.js +298 -0
  79. data/frontend/notices.js +118 -0
  80. data/frontend/package.json +15 -0
  81. data/frontend/range.js +10 -0
  82. data/frontend/selection.js +47 -0
  83. data/frontend/shortcuts.js +25 -0
  84. data/frontend/sync-notices.js +130 -0
  85. data/frontend/undo.js +48 -0
  86. data/frontend/window.js +181 -0
  87. data/lib/generators/instant_record/install/install_generator.rb +18 -30
  88. data/lib/generators/instant_record/install/templates/instant_record.rb +34 -0
  89. data/lib/generators/instant_record/ios/ios_generator.rb +71 -0
  90. data/lib/generators/instant_record/ios/templates/App.swift.tt +35 -0
  91. data/lib/generators/instant_record/ios/templates/Info.plist +11 -0
  92. data/lib/generators/instant_record/ios/templates/LibraryEngine.swift +30 -0
  93. data/lib/instant_record/branch/sqlite_store.rb +142 -0
  94. data/lib/instant_record/branch.rb +388 -0
  95. data/lib/instant_record/client/notifier.rb +8 -12
  96. data/lib/instant_record/client/rebaser.rb +565 -0
  97. data/lib/instant_record/client/transport.rb +64 -42
  98. data/lib/instant_record/client.rb +1600 -169
  99. data/lib/instant_record/compiled_site.rb +85 -0
  100. data/lib/instant_record/compiler/app_stage.rb +212 -0
  101. data/lib/instant_record/compiler/ast_lowerer.rb +659 -0
  102. data/lib/instant_record/compiler/browser_migrations.rb +161 -0
  103. data/lib/instant_record/compiler/entry_builder.rb +832 -0
  104. data/lib/instant_record/compiler/fts5_smoke.rb +205 -0
  105. data/lib/instant_record/compiler/gem_vendor.rb +194 -0
  106. data/lib/instant_record/compiler/host_adapters.rb +506 -0
  107. data/lib/instant_record/compiler/kotlin_codegen.rb +209 -0
  108. data/lib/instant_record/compiler/manifest.rb +178 -0
  109. data/lib/instant_record/compiler/native_build.rb +586 -0
  110. data/lib/instant_record/compiler/native_contracts.rb +338 -0
  111. data/lib/instant_record/compiler/path_scrubber.rb +31 -0
  112. data/lib/instant_record/compiler/reachability_tracer.rb +1188 -0
  113. data/lib/instant_record/compiler/route_analyzer.rb +623 -0
  114. data/lib/instant_record/compiler/runner.rb +42 -0
  115. data/lib/instant_record/compiler/schema_lock.rb +606 -0
  116. data/lib/instant_record/compiler/source_pages.rb +77 -0
  117. data/lib/instant_record/compiler/static_linter.rb +770 -0
  118. data/lib/instant_record/compiler/swift_codegen.rb +341 -0
  119. data/lib/instant_record/compiler/toolchain.rb +219 -0
  120. data/lib/instant_record/compiler/wasm_build.rb +704 -0
  121. data/lib/instant_record/compiler/wasm_tree.rb +518 -0
  122. data/lib/instant_record/compiler.rb +277 -0
  123. data/lib/instant_record/configuration.rb +104 -0
  124. data/lib/instant_record/engine.rb +68 -18
  125. data/lib/instant_record/file_store.rb +162 -0
  126. data/lib/instant_record/files.rb +92 -0
  127. data/lib/instant_record/hlc.rb +387 -0
  128. data/lib/instant_record/host.rb +66 -0
  129. data/lib/instant_record/inertia/renderer.rb +52 -0
  130. data/lib/instant_record/inertia.rb +222 -0
  131. data/lib/instant_record/mcp/cli.rb +319 -0
  132. data/lib/instant_record/mcp/host_process.rb +229 -0
  133. data/lib/instant_record/mcp/http_exchange.rb +233 -0
  134. data/lib/instant_record/mcp/replica.rb +556 -0
  135. data/lib/instant_record/mcp/runtime.rb +406 -0
  136. data/lib/instant_record/mcp/server.rb +429 -0
  137. data/lib/instant_record/mcp.rb +47 -0
  138. data/lib/instant_record/native/contract.rb +367 -0
  139. data/lib/instant_record/native/node.rb +125 -0
  140. data/lib/instant_record/native/screen.rb +366 -0
  141. data/lib/instant_record/native/xcode_project.rb +344 -0
  142. data/lib/instant_record/native.rb +41 -0
  143. data/lib/instant_record/outbox_mutation.rb +81 -9
  144. data/lib/instant_record/outbox_upcaster.rb +161 -0
  145. data/lib/instant_record/read_tracker.rb +610 -0
  146. data/lib/instant_record/routing.rb +33 -0
  147. data/lib/instant_record/runtime_scoped.rb +4 -0
  148. data/lib/instant_record/shell.rb +486 -0
  149. data/lib/instant_record/sync_actions.rb +800 -0
  150. data/lib/instant_record/sync_metadata.rb +17 -2
  151. data/lib/instant_record/sync_notice.rb +234 -0
  152. data/lib/instant_record/sync_partition.rb +63 -0
  153. data/lib/instant_record/sync_scope.rb +300 -0
  154. data/lib/instant_record/sync_shape.rb +102 -0
  155. data/lib/instant_record/sync_window.rb +92 -15
  156. data/lib/instant_record/syncable.rb +313 -17
  157. data/lib/instant_record/testing/authoritative_server.rb +547 -0
  158. data/lib/instant_record/testing/chaos_simulator.rb +429 -0
  159. data/lib/instant_record/testing/cruby_host_bridge.rb +370 -0
  160. data/lib/instant_record/testing/fault_network.rb +140 -0
  161. data/lib/instant_record/testing/parity_suite.rb +435 -0
  162. data/lib/instant_record/testing/runtimes/base.rb +184 -0
  163. data/lib/instant_record/testing/runtimes/cruby_runtime.rb +255 -0
  164. data/lib/instant_record/testing/runtimes/native_runtime.rb +346 -0
  165. data/lib/instant_record/testing/runtimes/wasm_runtime.rb +371 -0
  166. data/lib/instant_record/testing/wasm_host_bridge.mjs +240 -0
  167. data/lib/instant_record/testing.rb +333 -0
  168. data/lib/instant_record/trace/redactor.rb +278 -0
  169. data/lib/instant_record/trace/replayer.rb +126 -0
  170. data/lib/instant_record/trace/schema_extractor.rb +37 -0
  171. data/lib/instant_record/trace.rb +22 -0
  172. data/lib/instant_record/version.rb +1 -1
  173. data/lib/instant_record.rb +107 -37
  174. data/lib/tasks/instant_record.rake +299 -47
  175. data/native/ios/InstantRecordNative/Package.swift +12 -0
  176. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/AppHost.swift +706 -0
  177. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Engine.swift +64 -0
  178. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/FileStore.swift +1048 -0
  179. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/HTTPEngine.swift +36 -0
  180. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Icons.swift +19 -0
  181. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Node.swift +64 -0
  182. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/ScreenView.swift +481 -0
  183. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Screens.swift +94 -0
  184. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/StreamClient.swift +74 -0
  185. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/SyncNotice.swift +282 -0
  186. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/SyncSchedule.swift +153 -0
  187. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Theme.swift +140 -0
  188. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Transport.swift +108 -0
  189. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/TypedContracts.swift +237 -0
  190. data/native/ios/README.md +341 -0
  191. data/sig/instant_record/inertia.rbs +47 -0
  192. data/sig/instant_record/native.rbs +38 -0
  193. metadata +194 -18
  194. data/lib/generators/instant_record/install/templates/database.js +0 -32
  195. data/lib/generators/instant_record/install/templates/index.html +0 -69
  196. data/lib/generators/instant_record/install/templates/rails.sw.js +0 -750
  197. data/lib/instant_record/local_schema.rb +0 -75
  198. data/lib/instant_record/pglite_compat.rb +0 -40
@@ -0,0 +1,435 @@
1
+ require "json"
2
+ require "securerandom"
3
+ require "uri"
4
+
5
+ module InstantRecord
6
+ module Testing
7
+ # Executes shared model, controller, sync, 32-bit boundary, identity-reset,
8
+ # mid-bootstrap-abort, split-SSE, and frontend/http.js assertions simultaneously
9
+ # across all active runtimes (CRuby, Wasm AppHost, Native C ABI Fiddle) and
10
+ # asserts empty WASI/native stderr plus bit-for-bit convergence.
11
+ class ParitySuite
12
+ MODELS = %w[Issue AuthNote].freeze
13
+ ENDPOINT = InstantRecord::DEFAULT_MOUNT_PATH
14
+
15
+ ScenarioResult = Struct.new(:name, :runtimes, :elapsed_ms, :status, keyword_init: true)
16
+
17
+ def initialize(runtimes:, artifacts:, rails_app: nil, database_url: nil, out: $stdout)
18
+ @runtime_names = Array(runtimes).map(&:to_sym)
19
+ @artifacts = artifacts
20
+ @rails_app = rails_app
21
+ @database_url = database_url
22
+ @out = out
23
+ end
24
+
25
+ def run
26
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
27
+ @server = AuthoritativeServer.build(rails_app: @rails_app, database_url: @database_url, models: MODELS)
28
+ @network = FaultNetwork.new(@server)
29
+ @drivers = build_drivers
30
+
31
+ @out.puts "InstantRecord dual-runtime parity (#{@server.backend_label}; runtimes: #{@runtime_names.join(', ')})"
32
+
33
+ results = []
34
+ scenarios.each do |scenario_name|
35
+ t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
36
+ @server.reset_data!
37
+ @network.heal_all!
38
+ send(:"scenario_#{scenario_name}")
39
+ ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0) * 1000).round(1)
40
+ results << ScenarioResult.new(name: scenario_name, runtimes: @runtime_names, elapsed_ms: ms, status: :passed)
41
+ @out.puts " [PASS] #{scenario_name} (#{ms}ms)"
42
+ end
43
+
44
+ total_ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000).round(1)
45
+ @out.puts "All #{results.size} parity scenarios passed across [#{@runtime_names.join(', ')}] in #{total_ms}ms."
46
+ { ok: true, backend: @server.backend_label, runtimes: @runtime_names, scenarios: results, elapsed_ms: total_ms }
47
+ ensure
48
+ @drivers&.each_value do |driver|
49
+ driver.close
50
+ rescue StandardError
51
+ nil
52
+ end
53
+ @server&.close
54
+ end
55
+
56
+ private
57
+
58
+ def scenarios
59
+ list = %i[
60
+ boot_and_config_32bit_safety
61
+ controller_crud_and_outbox_sync
62
+ server_only_validation_rejection_rollback
63
+ int32_boundary_values
64
+ identity_scoping_switch_and_reset
65
+ mid_bootstrap_abort_and_idempotent_retry
66
+ split_sse_framing_and_echo_suppression
67
+ ]
68
+ list << :frontend_http_compiled_fetch_path if @runtime_names.include?(:wasm)
69
+ list
70
+ end
71
+
72
+ def build_drivers
73
+ @runtime_names.each_with_object({}) do |rt, acc|
74
+ acc[rt] =
75
+ case rt
76
+ when :cruby
77
+ Runtimes::CRubyRuntime.new(network: @network, server: @server, model_names: MODELS)
78
+ when :wasm
79
+ Runtimes::WasmRuntime.new(
80
+ wasm_path: @artifacts.wasm_path,
81
+ web_node_modules: @artifacts.web_node_modules,
82
+ network: @network
83
+ )
84
+ when :native
85
+ Runtimes::NativeRuntime.new(
86
+ lib_path: @artifacts.native_lib_path,
87
+ network: @network
88
+ )
89
+ end
90
+ end
91
+ end
92
+
93
+ def spawn_clients(prefix, identity: nil)
94
+ @drivers.each_with_object({}) do |(rt, driver), acc|
95
+ cid = "#{prefix}_#{rt}"
96
+ @network.register_client(cid, identity: identity)
97
+ acc[rt] = driver.create_client(cid)
98
+ end
99
+ end
100
+
101
+ def assert_equal!(expected, actual, message)
102
+ return if expected == actual
103
+
104
+ raise ParityMismatch, "#{message}\nExpected: #{expected.inspect}\nActual: #{actual.inspect}"
105
+ end
106
+
107
+ def assert_true!(cond, message)
108
+ raise ParityMismatch, message unless cond
109
+ end
110
+
111
+ # Assert all clients match the authoritative server's visible state AND
112
+ # match each other bit-for-bit in canonical JSON.
113
+ def assert_converged!(clients, identity: nil, label:)
114
+ expected_tables = @server.visible_state(identity: identity)
115
+ expected_json = InstantRecord::Testing.canonical_json(expected_tables)
116
+
117
+ snapshots = {}
118
+ clients.each do |rt, client|
119
+ snap = client.snapshot_state(model_names: MODELS)
120
+ snapshots[rt] = snap
121
+
122
+ assert_equal!(0, snap[:pending], "#{label} [#{rt}]: expected pending=0 after convergence")
123
+ snap[:sync_states].each do |model, rows|
124
+ unsynced = rows.reject { |r| r["sync_state"] == "synced" }
125
+ assert_true!(unsynced.empty?, "#{label} [#{rt}]: unsynced #{model} rows remain: #{unsynced.inspect}")
126
+ end
127
+
128
+ actual_json = InstantRecord::Testing.canonical_json(snap[:tables])
129
+ unless actual_json == expected_json
130
+ raise ConvergenceError,
131
+ "#{label} [#{rt}] diverged from authoritative server (#{@server.backend_label}):\n" \
132
+ "--- server ---\n#{expected_json}\n--- #{rt} ---\n#{actual_json}"
133
+ end
134
+ end
135
+
136
+ # Cross-runtime bit-for-bit comparison.
137
+ ref_rt = clients.keys.first
138
+ ref_json = InstantRecord::Testing.canonical_json(snapshots[ref_rt][:tables])
139
+ snapshots.each do |rt, snap|
140
+ next if rt == ref_rt
141
+
142
+ other_json = InstantRecord::Testing.canonical_json(snap[:tables])
143
+ unless other_json == ref_json
144
+ raise ParityMismatch,
145
+ "#{label}: #{rt} diverged from #{ref_rt}:\n--- #{ref_rt} ---\n#{ref_json}\n--- #{rt} ---\n#{other_json}"
146
+ end
147
+ end
148
+
149
+ snapshots
150
+ end
151
+
152
+ def converge_all!(clients, rounds: 4)
153
+ rounds.times do
154
+ clients.each_value { |c| c.sync(ENDPOINT) }
155
+ end
156
+ end
157
+
158
+ # 1. Boot & 32-bit config safety (catches wasm32 RangeError on boot/first sync).
159
+ def scenario_boot_and_config_32bit_safety
160
+ clients = spawn_clients("boot")
161
+ clients.each do |rt, client|
162
+ state = client.sync_state
163
+ assert_equal!(false, state[:bootstrapped], "boot [#{rt}]: must start unbootstrapped")
164
+ assert_equal!(0, state[:cursor], "boot [#{rt}]: cursor must start at 0")
165
+ assert_equal!(0, state[:pending], "boot [#{rt}]: pending must start at 0")
166
+
167
+ plan = client.sync_plan
168
+ assert_equal!(true, plan["bootstrap"], "boot [#{rt}]: sync_plan must request bootstrap")
169
+ assert_equal!("", plan["push"], "boot [#{rt}]: sync_plan push must be empty")
170
+
171
+ res = client.sync(ENDPOINT)
172
+ assert_equal!(0, res[:exit], "boot [#{rt}]: sync exit must be 0")
173
+ assert_equal!(0, res[:pending], "boot [#{rt}]: pending must be 0 after empty bootstrap")
174
+ assert_equal!(true, client.sync_state[:bootstrapped], "boot [#{rt}]: must be bootstrapped after sync")
175
+ end
176
+
177
+ assert_converged!(clients, label: "boot_and_config_32bit_safety")
178
+ end
179
+
180
+ # 2. Model & controller CRUD (GET/POST/PATCH/DELETE via _method) + outbox sync.
181
+ def scenario_controller_crud_and_outbox_sync
182
+ clients = spawn_clients("crud")
183
+ converge_all!(clients, rounds: 1)
184
+
185
+ created_ids = {}
186
+ clients.each do |rt, client|
187
+ title = "Parity issue from #{rt}"
188
+ post_res = client.request("POST", "/todo/issues", body: URI.encode_www_form("issue[title]" => title))
189
+ assert_true!([200, 302, 303].include?(post_res[:status]), "crud [#{rt}]: POST /todo/issues returned #{post_res[:status]}")
190
+
191
+ index_res = client.request("GET", "/todo")
192
+ assert_equal!(200, index_res[:status], "crud [#{rt}]: GET /todo status")
193
+ assert_true!(index_res[:body].include?(title), "crud [#{rt}]: GET /todo body missing #{title.inspect}")
194
+
195
+ plan = client.sync_plan
196
+ refute_empty = !plan["push"].to_s.empty?
197
+ assert_true!(refute_empty, "crud [#{rt}]: sync_plan must carry queued create mutation")
198
+ assert_equal!(1, client.sync_state[:pending], "crud [#{rt}]: pending must be 1 before sync")
199
+
200
+ snap = client.snapshot_state(model_names: MODELS)
201
+ created = snap[:tables]["Issue"].find { |r| r["title"] == title }
202
+ assert_true!(!created.nil?, "crud [#{rt}]: created Issue missing from local SQLite")
203
+ created_ids[rt] = created["id"]
204
+
205
+ # PATCH via Rails form _method=patch.
206
+ patch_res = client.request("POST", "/todo/issues/#{created['id']}", body: URI.encode_www_form("_method" => "patch", "done" => "1"))
207
+ assert_true!([200, 302, 303].include?(patch_res[:status]), "crud [#{rt}]: PATCH returned #{patch_res[:status]}")
208
+
209
+ client.sync(ENDPOINT)
210
+ end
211
+
212
+ # All runtimes now pull each other's issues and converge.
213
+ converge_all!(clients, rounds: 2)
214
+ snaps = assert_converged!(clients, label: "crud_after_create_and_patch")
215
+ assert_equal!(clients.size, snaps.values.first[:tables]["Issue"].size, "crud: all clients' issues must be present")
216
+ snaps.values.first[:tables]["Issue"].each do |row|
217
+ assert_equal!("done", row["state"], "crud: PATCH state=done must converge on #{row['id']}")
218
+ end
219
+
220
+ # DELETE via _method=delete from the first runtime and verify convergence everywhere.
221
+ first_rt = clients.keys.first
222
+ victim_id = created_ids[first_rt]
223
+ del_res = clients[first_rt].request("POST", "/todo/issues/#{victim_id}", body: URI.encode_www_form("_method" => "delete"))
224
+ assert_true!([200, 302, 303].include?(del_res[:status]), "crud [#{first_rt}]: DELETE returned #{del_res[:status]}")
225
+
226
+ converge_all!(clients, rounds: 2)
227
+ snaps_after = assert_converged!(clients, label: "crud_after_delete")
228
+ assert_equal!(clients.size - 1, snaps_after.values.first[:tables]["Issue"].size, "crud: deleted issue must be gone everywhere")
229
+ end
230
+
231
+ # 3. Server-only validation rejection ("reject me") & rollback alongside a valid write.
232
+ def scenario_server_only_validation_rejection_rollback
233
+ clients = spawn_clients("reject")
234
+ converge_all!(clients, rounds: 1)
235
+
236
+ clients.each do |rt, client|
237
+ client.local_write(model: "Issue", operation: "create", attributes: { "title" => "reject me" })
238
+ client.local_write(model: "Issue", operation: "create", attributes: { "title" => "keep from #{rt}" })
239
+ assert_equal!(2, client.sync_state[:pending], "reject [#{rt}]: both writes must queue optimistically")
240
+
241
+ res = client.sync(ENDPOINT)
242
+ assert_equal!(0, res[:pending], "reject [#{rt}]: rejected mutation must not jam the outbox")
243
+ end
244
+
245
+ converge_all!(clients, rounds: 2)
246
+ snaps = assert_converged!(clients, label: "server_only_validation_rejection")
247
+ titles = snaps.values.first[:tables]["Issue"].map { |r| r["title"] }
248
+ assert_true!(!titles.include?("reject me"), "reject: 'reject me' must be rolled back everywhere")
249
+ clients.each_key do |rt|
250
+ assert_true!(titles.include?("keep from #{rt}"), "reject: valid write from #{rt} must survive")
251
+ end
252
+ end
253
+
254
+ # 4. 32-bit signed integer boundary values (wasm32 INT32_MAX = 2_147_483_647).
255
+ def scenario_int32_boundary_values
256
+ boundary_title = "int32 [#{INT32_MIN}, #{INT32_MAX}, #{INT32_MAX + 1}, 9223372036854775807]"
257
+ seeded = @server.seed_boundary_record(
258
+ model_name: "Issue",
259
+ id: "int32-bootstrap-row",
260
+ title: boundary_title,
261
+ server_version: INT32_MAX - 1,
262
+ cursor_id: INT32_MAX - 1
263
+ )
264
+ assert_equal!(INT32_MAX - 1, seeded[:change].id, "int32: server seed cursor must equal INT32_MAX - 1")
265
+
266
+ clients = spawn_clients("int32")
267
+ clients.each do |rt, client|
268
+ res = client.sync(ENDPOINT)
269
+ assert_equal!(0, res[:exit], "int32 [#{rt}]: bootstrap sync exit must be 0")
270
+ assert_equal!(INT32_MAX - 1, client.sync_state[:cursor], "int32 [#{rt}]: cursor must preserve INT32_MAX - 1")
271
+ end
272
+ assert_converged!(clients, label: "int32_after_bootstrap")
273
+
274
+ # Now stream an SSE event right at INT32_MAX (2_147_483_647) for both id and version.
275
+ updated_stamp = (Time.now.utc + 5).iso8601(InstantRecord::TIME_PRECISION)
276
+ max_row = @server.seed_boundary_record(
277
+ model_name: "Issue",
278
+ id: "int32-max-stream-row",
279
+ title: "max int32 cursor & version",
280
+ server_version: INT32_MAX,
281
+ cursor_id: INT32_MAX,
282
+ updated_at: Time.parse(updated_stamp)
283
+ )
284
+ sse_payload = JSON.generate(
285
+ "type" => "Issue",
286
+ "id" => max_row[:record].id,
287
+ "operation" => "create",
288
+ "version" => INT32_MAX,
289
+ "attributes" => InstantRecord.wire_attributes(max_row[:record].attributes)
290
+ )
291
+ frame = "id: #{INT32_MAX}\nevent: change\ndata: #{sse_payload}\n\n"
292
+
293
+ clients.each do |rt, client|
294
+ res = client.consume_stream(frame)
295
+ assert_equal!(1, res[:applied], "int32 [#{rt}]: INT32_MAX SSE frame must apply")
296
+ assert_equal!(INT32_MAX, res[:cursor], "int32 [#{rt}]: cursor must equal INT32_MAX without overflow")
297
+ assert_equal!(INT32_MAX, client.sync_state[:cursor], "int32 [#{rt}]: persisted cursor must equal INT32_MAX")
298
+ end
299
+
300
+ snaps = assert_converged!(clients, label: "int32_after_max_stream")
301
+ row = snaps.values.first[:tables]["Issue"].find { |r| r["id"] == "int32-max-stream-row" }
302
+ assert_equal!(INT32_MAX, row["server_version"], "int32: server_version must round-trip INT32_MAX")
303
+ end
304
+
305
+ # 5. Identity scoping, switch (ada -> ben), event: reset, scoped purge vs unscoped survival.
306
+ def scenario_identity_scoping_switch_and_reset
307
+ @server.server_write(model_name: "AuthNote", operation: "create", id: "n-everyone", attributes: { title: "Public note", body: "all", audience: "everyone", owner_id: "ada" })
308
+ @server.server_write(model_name: "AuthNote", operation: "create", id: "n-members", attributes: { title: "Members note", body: "team", audience: "members", owner_id: "ben" })
309
+ @server.server_write(model_name: "AuthNote", operation: "create", id: "n-admins", attributes: { title: "Payroll", body: "secret", audience: "admins", owner_id: "ada" })
310
+ @server.server_write(model_name: "AuthNote", operation: "create", id: "n-ada", attributes: { title: "Ada private", body: "mine", audience: "owner", owner_id: "ada" })
311
+ @server.server_write(model_name: "AuthNote", operation: "create", id: "n-ben", attributes: { title: "Ben private", body: "mine", audience: "owner", owner_id: "ben" })
312
+ @server.server_write(model_name: "Issue", operation: "create", id: "i-shared", attributes: { title: "Shared unscoped issue", state: "open" })
313
+
314
+ clients = spawn_clients("ident", identity: "ada")
315
+ converge_all!(clients, rounds: 1)
316
+ snaps_ada = assert_converged!(clients, identity: "ada", label: "identity_as_ada")
317
+ ada_note_ids = snaps_ada.values.first[:tables]["AuthNote"].map { |r| r["id"] }
318
+ assert_equal!(%w[n-ada n-admins n-everyone n-members], ada_note_ids, "identity: ada must see public, members, admins, and own")
319
+
320
+ # Queue one scoped AuthNote and one unscoped Issue while offline, then switch identity to ben.
321
+ clients.each do |rt, client|
322
+ @network.set_partition(client.id, :offline)
323
+ client.local_write(model: "AuthNote", operation: "create", attributes: { title: "Ada queued #{rt}", body: "queued", audience: "owner", owner_id: "ada" })
324
+ client.local_write(model: "Issue", operation: "create", attributes: { title: "Unscoped queued #{rt}" })
325
+ assert_equal!(2, client.sync_state[:pending], "identity [#{rt}]: 2 writes must be queued")
326
+
327
+ @network.set_identity(client.id, "ben")
328
+ @network.set_partition(client.id, :online)
329
+ end
330
+
331
+ # First sync receives rejection for stale scoped write + reset event on /events;
332
+ # follow-up sync re-bootstraps cleanly as ben while keeping unscoped Issue writes.
333
+ converge_all!(clients, rounds: 3)
334
+ snaps_ben = assert_converged!(clients, identity: "ben", label: "identity_after_switch_to_ben")
335
+
336
+ ben_note_ids = snaps_ben.values.first[:tables]["AuthNote"].map { |r| r["id"] }
337
+ assert_equal!(%w[n-ben n-everyone n-members], ben_note_ids, "identity: ben must not see admin or ada-private notes")
338
+
339
+ issue_titles = snaps_ben.values.first[:tables]["Issue"].map { |r| r["title"] }
340
+ clients.each_key do |rt|
341
+ assert_true!(issue_titles.include?("Unscoped queued #{rt}"), "identity: unscoped Issue from #{rt} must survive reset")
342
+ end
343
+ end
344
+
345
+ # 6. Mid-bootstrap abort (network_drop, server_503, truncated_body) + idempotent retry.
346
+ def scenario_mid_bootstrap_abort_and_idempotent_retry
347
+ @server.server_write(model_name: "Issue", operation: "create", id: "boot-1", attributes: { title: "Server row 1" })
348
+ @server.server_write(model_name: "Issue", operation: "create", id: "boot-2", attributes: { title: "Server row 2" })
349
+
350
+ %i[network_drop server_503 truncated_body].each do |abort_mode|
351
+ clients = spawn_clients("abort_#{abort_mode}")
352
+ clients.each do |rt, client|
353
+ # Queue a local write before bootstrap has ever succeeded.
354
+ client.local_write(model: "Issue", operation: "create", attributes: { title: "Pre-boot #{abort_mode} #{rt}" })
355
+ @network.arm_bootstrap_abort(client.id, abort_mode)
356
+
357
+ client.sync(ENDPOINT)
358
+ state = client.sync_state
359
+ assert_equal!(false, state[:bootstrapped], "abort(#{abort_mode}) [#{rt}]: must remain unbootstrapped after aborted bootstrap")
360
+ end
361
+
362
+ # Retry now that the one-shot abort cleared: must bootstrap idempotently & converge.
363
+ converge_all!(clients, rounds: 2)
364
+ assert_converged!(clients, label: "mid_bootstrap_abort_#{abort_mode}")
365
+ end
366
+ end
367
+
368
+ # 7. Split SSE chunk framing (including multibyte UTF-8) & echo suppression.
369
+ def scenario_split_sse_framing_and_echo_suppression
370
+ clients = spawn_clients("sse")
371
+ converge_all!(clients, rounds: 1)
372
+
373
+ stamp = Time.now.utc.iso8601(InstantRecord::TIME_PRECISION)
374
+ seeded = @server.server_write(
375
+ model_name: "Issue",
376
+ operation: "create",
377
+ id: "sse-split-1",
378
+ attributes: { title: "café — split frame", state: "open", created_at: Time.parse(stamp), updated_at: Time.parse(stamp) }
379
+ )
380
+ cursor = @server.current_cursor
381
+ payload = JSON.generate(
382
+ "type" => "Issue",
383
+ "id" => seeded.id,
384
+ "operation" => "create",
385
+ "version" => seeded.server_version,
386
+ "attributes" => InstantRecord.wire_attributes(seeded.attributes)
387
+ )
388
+ frame = "id: #{cursor}\nevent: change\ndata: #{payload}\n\n"
389
+ part1 = frame[0, 17]
390
+ part2 = frame[17, 29]
391
+ part3 = frame[46..]
392
+
393
+ clients.each do |rt, client|
394
+ r1 = client.consume_stream(part1)
395
+ assert_equal!(0, r1[:applied], "sse [#{rt}]: partial chunk 1 must apply 0")
396
+ r2 = client.consume_stream(part2)
397
+ assert_equal!(0, r2[:applied], "sse [#{rt}]: partial chunk 2 must apply 0")
398
+ r3 = client.consume_stream(part3)
399
+ assert_equal!(1, r3[:applied], "sse [#{rt}]: final chunk must apply 1")
400
+ assert_equal!(cursor, r3[:cursor], "sse [#{rt}]: cursor must advance to #{cursor}")
401
+ assert_equal!(true, r3[:notified], "sse [#{rt}]: genuine remote change must notify")
402
+ assert_equal!([{ type: "Issue", id: "sse-split-1" }], r3[:changes], "sse [#{rt}]: notice must list Issue:sse-split-1")
403
+
404
+ # Echo suppression: re-applying the exact same row with equal updated_at changes nothing.
405
+ echo_frame = "id: #{cursor + 1}\nevent: change\ndata: #{payload}\n\n"
406
+ echo = client.consume_stream(echo_frame)
407
+ assert_equal!(0, echo[:applied], "sse [#{rt}]: identical echo must apply 0")
408
+ assert_equal!(false, echo[:notified], "sse [#{rt}]: identical echo must stay quiet")
409
+ assert_equal!(cursor + 1, echo[:cursor], "sse [#{rt}]: cursor still advances past echoed event")
410
+ end
411
+
412
+ assert_converged!(clients, label: "split_sse_framing_and_echo_suppression")
413
+ end
414
+
415
+ # 8. Exercise frontend/http.js (`write` and `localHttpClient.request`) directly
416
+ # against live AppHost#request in Node (covers frontend/http.js:36-70).
417
+ def scenario_frontend_http_compiled_fetch_path
418
+ wasm_driver = @drivers[:wasm]
419
+ @network.register_client("frontend_http_wasm")
420
+ client = wasm_driver.create_client("frontend_http_wasm")
421
+ client.sync(ENDPOINT)
422
+
423
+ res = client.verify_frontend_http
424
+ assert_equal!(true, res["ok"], "frontend/http.js: verify_frontend_http must succeed")
425
+ assert_equal!(200, res["pageStatus"], "frontend/http.js: localHttpClient GET must return 200")
426
+ assert_equal!(true, res["containsWrittenTitle"], "frontend/http.js: write() POST must persist to AppHost SQLite")
427
+ assert_true!(res["calls"].any? { |c| c["method"] == "POST" && c["path"] == "/todo/issues" }, "frontend/http.js: must send POST /todo/issues")
428
+ assert_true!(res["calls"].any? { |c| c["path"].include?("_inertia=1") && c["path"].include?("_only=issues") }, "frontend/http.js: localHttpClient must set _inertia=1 and _only")
429
+
430
+ client.sync(ENDPOINT)
431
+ assert_converged!({ wasm: client }, label: "frontend_http_compiled_fetch_path")
432
+ end
433
+ end
434
+ end
435
+ end
@@ -0,0 +1,184 @@
1
+ require "json"
2
+ require "sqlite3"
3
+ require "tempfile"
4
+ require "uri"
5
+
6
+ module InstantRecord
7
+ module Testing
8
+ module Runtimes
9
+ # Shared strict stderr validation, notice parsing, and direct SQLite
10
+ # database snapshot reader used across CRuby, Wasm, and Native drivers.
11
+ module Base
12
+ OFFLINE_WARNING_PATTERN = /\A\[instant_record\] (?:bootstrap|drain|poll|fetch_history) failed \(offline\?\): /.freeze
13
+
14
+ def assert_clean_stderr!(errors, context:, allow_offline_warning: false)
15
+ lines = Array(errors).map { |line| line.to_s.strip }.reject(&:empty?)
16
+ return if lines.empty?
17
+
18
+ unexpected =
19
+ if allow_offline_warning
20
+ lines.reject { |line| OFFLINE_WARNING_PATTERN.match?(line) }
21
+ else
22
+ lines
23
+ end
24
+
25
+ return if unexpected.empty?
26
+
27
+ raise InstantRecord::Testing::StderrError,
28
+ "Unexpected stderr during #{context}:\n #{unexpected.join("\n ")}"
29
+ end
30
+
31
+ def parse_notice(text)
32
+ raw = text.to_s
33
+ return { notified: false, changes: nil } unless raw.start_with?("records_changed")
34
+
35
+ lines = raw.split("\n")[1..].to_a.reject(&:empty?)
36
+ return { notified: true, changes: nil } if lines.empty?
37
+
38
+ changes = []
39
+ unlisted = false
40
+ lines.each do |line|
41
+ next if line.start_with?("sync_notice:")
42
+ next if unlisted
43
+
44
+ if line.start_with?("{")
45
+ parsed = JSON.parse(line)
46
+ if parsed.is_a?(Hash) && parsed["type"] && parsed["id"]
47
+ changes << { type: parsed["type"].to_s, id: parsed["id"].to_s }
48
+ else
49
+ unlisted = true
50
+ end
51
+ else
52
+ at = line.index(":")
53
+ if at && at > 0
54
+ changes << { type: line[0...at], id: line[(at + 1)..] }
55
+ else
56
+ unlisted = true
57
+ end
58
+ end
59
+ rescue JSON::ParserError
60
+ unlisted = true
61
+ end
62
+ { notified: true, changes: (!unlisted && !changes.empty?) ? changes : nil }
63
+ end
64
+
65
+ def table_name_for(model_name)
66
+ case model_name.to_s
67
+ when "Issue" then "issues"
68
+ when "AuthNote" then "auth_notes"
69
+ when "Note" then "notes"
70
+ when "Message" then "messages"
71
+ when "Channel" then "channels"
72
+ when "ChatUser" then "chat_users"
73
+ when "MailEntry" then "mail_entries"
74
+ when "AssistantChat" then "assistant_chats"
75
+ when "AssistantTurn" then "assistant_turns"
76
+ else
77
+ model = InstantRecord.synced_model(model_name.to_s) || model_name.to_s.safe_constantize
78
+ model ? model.table_name : "#{model_name.to_s.downcase}s"
79
+ end
80
+ end
81
+
82
+ # Read ground-truth synced tables, sync_state, outbox count, and sync
83
+ # metadata directly from a client's SQLite file.
84
+ def read_sqlite_file_state(db_path, model_names:)
85
+ db = SQLite3::Database.new(db_path, readonly: true)
86
+ db.results_as_hash = true
87
+ tables = {}
88
+ sync_states = {}
89
+
90
+ Array(model_names).each do |model_name|
91
+ table = table_name_for(model_name)
92
+ exists = db.get_first_value("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", [table])
93
+ unless exists
94
+ tables[model_name] = []
95
+ sync_states[model_name] = []
96
+ next
97
+ end
98
+
99
+ raw_rows = db.execute("SELECT * FROM \"#{table}\" ORDER BY id ASC")
100
+ rows = raw_rows.map { |r| r.reject { |k, _| k.is_a?(Integer) } }
101
+ tables[model_name] = InstantRecord::Testing.canonical_rows(rows)
102
+ sync_states[model_name] = rows.map { |r| { "id" => r["id"].to_s, "sync_state" => r["sync_state"].to_s } }
103
+ end
104
+
105
+ pending = db.get_first_value("SELECT COUNT(*) FROM instant_record_outbox").to_i
106
+ meta_rows = db.execute("SELECT key, value FROM instant_record_sync_metadata")
107
+ metadata = meta_rows.each_with_object({}) { |r, acc| acc[r["key"].to_s] = r["value"] }
108
+
109
+ {
110
+ tables: tables,
111
+ sync_states: sync_states,
112
+ pending: pending,
113
+ cursor: metadata["cursor"] ? metadata["cursor"].to_i : 0,
114
+ bootstrapped: !metadata["cursor"].nil?,
115
+ identity: metadata["identity"].to_s,
116
+ metadata: metadata
117
+ }
118
+ ensure
119
+ db&.close
120
+ end
121
+
122
+ def read_sqlite_bytes_state(bytes, model_names:)
123
+ Tempfile.create(["ir-wasm-db", ".sqlite3"], binmode: true) do |tmp|
124
+ tmp.write(bytes)
125
+ tmp.flush
126
+ read_sqlite_file_state(tmp.path, model_names: model_names)
127
+ end
128
+ end
129
+
130
+ # Build an HTTP/1.1 raw request string matching AppHost#request and
131
+ # WasmBridge/NativeBridge handle_request expectations.
132
+ def build_http_request(method, path, body: "", content_type: "application/x-www-form-urlencoded", cookies: {})
133
+ verb = method.to_s.upcase
134
+ body_str = body.to_s
135
+ if verb == "POST" && content_type.start_with?("application/x-www-form-urlencoded")
136
+ override = URI.decode_www_form(body_str).to_h["_method"]
137
+ verb = override.upcase if override && override.match?(/\A(?:patch|put|delete)\z/i)
138
+ end
139
+
140
+ cookie_header = cookies.map { |k, v| "#{k}=#{v}" }.join("; ")
141
+ head = +"#{verb} #{path} HTTP/1.1\r\nHost: localhost\r\n"
142
+ head << "Cookie: #{cookie_header}\r\n" unless cookie_header.empty?
143
+ unless body_str.empty?
144
+ head << "Content-Type: #{content_type}\r\nContent-Length: #{body_str.bytesize}\r\n"
145
+ end
146
+ head << "\r\n"
147
+ head + body_str
148
+ end
149
+
150
+ def parse_bridge_http_response(raw, cookies: nil)
151
+ text = raw.to_s
152
+ split = text.index("\n\n")
153
+ head = split ? text[0...split] : text
154
+ body = split ? text[(split + 2)..] : ""
155
+ lines = head.split("\n")
156
+ status = lines.first.to_i
157
+ status = 500 if status == 0
158
+ headers = []
159
+ lines[1..].to_a.each do |line|
160
+ colon = line.index(": ")
161
+ next unless colon
162
+
163
+ name = line[0...colon]
164
+ value = line[(colon + 2)..]
165
+ if name.downcase == "set-cookie" && cookies
166
+ pair = value.split(";").first.to_s
167
+ eq = pair.index("=")
168
+ if eq
169
+ if value.match?(/max-age=0/i)
170
+ cookies.delete(pair[0...eq])
171
+ else
172
+ cookies[pair[0...eq]] = pair[(eq + 1)..]
173
+ end
174
+ end
175
+ else
176
+ headers << [name, value]
177
+ end
178
+ end
179
+ { status: status, headers: headers, body: body }
180
+ end
181
+ end
182
+ end
183
+ end
184
+ end