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,429 @@
1
+ require "json"
2
+
3
+ module InstantRecord
4
+ module Testing
5
+ # Deterministic seeded multi-client chaos simulator.
6
+ # Drives heterogeneous clients (CRuby, Wasm AppHost, Native C ABI Fiddle)
7
+ # simultaneously against one authoritative server through randomized:
8
+ # - network partitions (offline, drop_post, drop_get, server_503, drop_after_apply)
9
+ # - per-client clock skew (LWW conflicts & tie-breaking)
10
+ # - 32-bit integer boundary values (server_version near INT32_MAX, boundary text)
11
+ # - identity switches (anonymous / ada / ben / cleo -> reset & re-bootstrap)
12
+ # - mid-bootstrap aborts (network_drop, server_503, truncated_body)
13
+ # - split SSE stream chunks
14
+ # - server-only validation rejections ("reject me") & unauthorized writes
15
+ #
16
+ # Enforces zero unexpected stderr, exit == 0, and pending >= 0 at every step,
17
+ # then heals all partitions and asserts bit-for-bit convergence against the
18
+ # authoritative server and across runtimes.
19
+ class ChaosSimulator
20
+ MODELS = %w[Issue AuthNote].freeze
21
+ ENDPOINT = InstantRecord::DEFAULT_MOUNT_PATH
22
+ IDENTITIES = [nil, "ada", "ben", "cleo"].freeze
23
+ AUDIENCES = %w[everyone members admins owner].freeze
24
+ CLOCK_SKEWS = [-120.0, -5.0, 0.0, 0.0, 5.0, 120.0].freeze
25
+
26
+ Report = Struct.new(:seed, :steps, :clients, :runtimes, :backend, :elapsed_ms, :stats, :trace, keyword_init: true)
27
+
28
+ def initialize(seed:, steps: 60, client_count: 3, runtimes:, artifacts:, rails_app: nil, database_url: nil, out: $stdout)
29
+ @seed = Integer(seed)
30
+ @steps = [Integer(steps), 1].max
31
+ @client_count = [Integer(client_count), 1].max
32
+ @runtime_names = Array(runtimes).map(&:to_sym)
33
+ @artifacts = artifacts
34
+ @rails_app = rails_app
35
+ @database_url = database_url
36
+ @out = out
37
+ @rng = Random.new(@seed)
38
+ @trace = []
39
+ @stats = Hash.new(0)
40
+ @known_issue_ids = []
41
+ @known_note_ids = []
42
+ @boundary_ids = {}
43
+ end
44
+
45
+ def run
46
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
47
+ @server = AuthoritativeServer.build(rails_app: @rails_app, database_url: @database_url, models: MODELS)
48
+ @server.reset_data!
49
+ @network = FaultNetwork.new(@server)
50
+ @drivers = build_drivers
51
+ @clients = spawn_clients
52
+
53
+ @out.puts "InstantRecord chaos simulation (seed=#{@seed}, steps=#{@steps}, clients=#{@clients.size}, backend=#{@server.backend_label}, runtimes=[#{@clients.map(&:runtime_name).join(',')}])"
54
+
55
+ seed_initial_records!
56
+ run_chaos_steps!
57
+ heal_and_verify_convergence!
58
+
59
+ elapsed_ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000).round(1)
60
+ @out.puts " [PASS] seed=#{@seed} converged bit-for-bit (#{@steps} steps, #{elapsed_ms}ms, ops=#{@stats.sort.to_h})"
61
+
62
+ Report.new(
63
+ seed: @seed,
64
+ steps: @steps,
65
+ clients: @clients.size,
66
+ runtimes: @clients.map(&:runtime_name),
67
+ backend: @server.backend_label,
68
+ elapsed_ms: elapsed_ms,
69
+ stats: @stats.dup,
70
+ trace: @trace.dup
71
+ )
72
+ rescue StandardError => e
73
+ raise e.class, format_failure(e)
74
+ ensure
75
+ @drivers&.each_value do |driver|
76
+ driver.close
77
+ rescue StandardError
78
+ nil
79
+ end
80
+ @server&.close
81
+ end
82
+
83
+ private
84
+
85
+ def build_drivers
86
+ @runtime_names.each_with_object({}) do |rt, acc|
87
+ acc[rt] =
88
+ case rt
89
+ when :cruby
90
+ Runtimes::CRubyRuntime.new(network: @network, server: @server, model_names: MODELS)
91
+ when :wasm
92
+ Runtimes::WasmRuntime.new(
93
+ wasm_path: @artifacts.wasm_path,
94
+ web_node_modules: @artifacts.web_node_modules,
95
+ network: @network
96
+ )
97
+ when :native
98
+ Runtimes::NativeRuntime.new(
99
+ lib_path: @artifacts.native_lib_path,
100
+ network: @network
101
+ )
102
+ end
103
+ end
104
+ end
105
+
106
+ def spawn_clients
107
+ Array.new(@client_count) do |i|
108
+ rt = @runtime_names[i % @runtime_names.size]
109
+ cid = "c#{i}_#{rt}"
110
+ identity = IDENTITIES[@rng.rand(IDENTITIES.size)]
111
+ skew = CLOCK_SKEWS[@rng.rand(CLOCK_SKEWS.size)]
112
+ @network.register_client(cid, identity: identity, clock_skew: skew)
113
+ record_trace("init #{cid} rt=#{rt} identity=#{identity.inspect} skew=#{skew}s")
114
+ @drivers[rt].create_client(cid)
115
+ end
116
+ end
117
+
118
+ def seed_initial_records!
119
+ 2.times do |i|
120
+ id = "seed-issue-#{@seed}-#{i}"
121
+ @server.server_write(model_name: "Issue", operation: "create", id: id, attributes: { title: "Seed issue #{i}", state: "open" })
122
+ @known_issue_ids << id
123
+ end
124
+ [
125
+ ["seed-note-public", "ada", "everyone"],
126
+ ["seed-note-members", "ben", "members"],
127
+ ["seed-note-admins", "ada", "admins"],
128
+ ["seed-note-ada", "ada", "owner"],
129
+ ["seed-note-ben", "ben", "owner"]
130
+ ].each do |id, owner, audience|
131
+ @server.server_write(
132
+ model_name: "AuthNote",
133
+ operation: "create",
134
+ id: id,
135
+ attributes: { title: "Seed #{audience}", body: "seed", audience: audience, owner_id: owner }
136
+ )
137
+ @known_note_ids << id
138
+ end
139
+
140
+ # Guarantee at least one mid-bootstrap abort on step 0 for client 0.
141
+ first = @clients.first
142
+ abort_mode = %i[network_drop server_503 truncated_body][@rng.rand(3)]
143
+ @network.arm_bootstrap_abort(first.id, abort_mode)
144
+ record_trace("arm_bootstrap_abort #{first.id} mode=#{abort_mode}")
145
+ @stats[:bootstrap_aborts] += 1
146
+ first.sync(ENDPOINT)
147
+ if first.sync_state[:bootstrapped]
148
+ raise ConvergenceError, "#{first.id} unexpectedly became bootstrapped after #{abort_mode} abort"
149
+ end
150
+ end
151
+
152
+ def run_chaos_steps!
153
+ @steps.times do |step_idx|
154
+ client = @clients[@rng.rand(@clients.size)]
155
+ roll = @rng.rand(100)
156
+
157
+ if roll < 22
158
+ step_local_issue_write(step_idx, client)
159
+ elsif roll < 34
160
+ step_local_auth_note_write(step_idx, client)
161
+ elsif roll < 44
162
+ step_server_write(step_idx)
163
+ elsif roll < 56
164
+ step_toggle_partition_or_skew(step_idx, client)
165
+ elsif roll < 74
166
+ step_sync_pass(step_idx, client)
167
+ elsif roll < 84
168
+ step_split_sse_stream(step_idx, client)
169
+ elsif roll < 92
170
+ step_switch_identity(step_idx, client)
171
+ elsif roll < 96
172
+ step_arm_bootstrap_abort(step_idx, client)
173
+ else
174
+ step_int32_boundary_event(step_idx)
175
+ end
176
+
177
+ verify_step_invariants!(step_idx, client)
178
+ end
179
+ end
180
+
181
+ def step_local_issue_write(step_idx, client)
182
+ snap = client.snapshot_state(model_names: MODELS)
183
+ local_issues = snap[:tables]["Issue"].reject { |r| @boundary_ids[r["id"]] }
184
+ op_roll = @rng.rand(10)
185
+
186
+ if local_issues.empty? || op_roll < 5
187
+ # Occasionally emit a server-rejected title ("reject me") to test rollback under chaos.
188
+ title = @rng.rand(6) == 0 ? "reject me" : "chaos-#{@seed}-s#{step_idx}-#{client.id}"
189
+ id = client.local_write(model: "Issue", operation: "create", attributes: { "title" => title })
190
+ @known_issue_ids << id if id && title != "reject me"
191
+ @stats[:local_issue_create] += 1
192
+ record_trace("step=#{step_idx} #{client.id} create Issue title=#{title.inspect} id=#{id}")
193
+ elsif op_roll < 8
194
+ target = local_issues[@rng.rand(local_issues.size)]
195
+ new_state = target["state"] == "done" ? "open" : "done"
196
+ client.local_write(model: "Issue", operation: "update", id: target["id"], attributes: { "state" => new_state })
197
+ @stats[:local_issue_update] += 1
198
+ record_trace("step=#{step_idx} #{client.id} update Issue id=#{target['id']} state=#{new_state}")
199
+ else
200
+ target = local_issues[@rng.rand(local_issues.size)]
201
+ client.local_write(model: "Issue", operation: "destroy", id: target["id"])
202
+ @stats[:local_issue_destroy] += 1
203
+ record_trace("step=#{step_idx} #{client.id} destroy Issue id=#{target['id']}")
204
+ end
205
+ end
206
+
207
+ def step_local_auth_note_write(step_idx, client)
208
+ snap = client.snapshot_state(model_names: MODELS)
209
+ local_notes = snap[:tables]["AuthNote"]
210
+ policy = @network.policy(client.id)
211
+
212
+ if local_notes.empty? || @rng.rand(3) < 2
213
+ # Mix authorized owner writes with occasional unauthorized owner writes (rejected by server).
214
+ owner = (@rng.rand(4) == 0 || policy.identity.nil?) ? %w[ada ben cleo][@rng.rand(3)] : policy.identity
215
+ audience = AUDIENCES[@rng.rand(AUDIENCES.size)]
216
+ title = "note-#{@seed}-s#{step_idx}-#{client.id}"
217
+ id = client.local_write(
218
+ model: "AuthNote",
219
+ operation: "create",
220
+ attributes: { "title" => title, "body" => "chaos body #{step_idx}", "audience" => audience, "owner_id" => owner }
221
+ )
222
+ @known_note_ids << id if id
223
+ @stats[:local_note_create] += 1
224
+ record_trace("step=#{step_idx} #{client.id} create AuthNote owner=#{owner} audience=#{audience} id=#{id}")
225
+ else
226
+ target = local_notes[@rng.rand(local_notes.size)]
227
+ client.local_write(model: "AuthNote", operation: "destroy", id: target["id"])
228
+ @stats[:local_note_destroy] += 1
229
+ record_trace("step=#{step_idx} #{client.id} destroy AuthNote id=#{target['id']}")
230
+ end
231
+ end
232
+
233
+ def step_server_write(step_idx)
234
+ skew = CLOCK_SKEWS[@rng.rand(CLOCK_SKEWS.size)]
235
+ if @rng.rand(2) == 0
236
+ id = "srv-issue-#{@seed}-#{step_idx}"
237
+ @server.server_write(
238
+ model_name: "Issue",
239
+ operation: "create",
240
+ id: id,
241
+ attributes: { title: "Server issue s#{step_idx}", state: "open" },
242
+ clock_offset: skew
243
+ )
244
+ @known_issue_ids << id
245
+ @stats[:server_write] += 1
246
+ record_trace("step=#{step_idx} server create Issue id=#{id} clock_offset=#{skew}s")
247
+ else
248
+ mutable = @known_issue_ids.reject { |i| @boundary_ids[i] }
249
+ return if mutable.empty?
250
+
251
+ victim = mutable[@rng.rand(mutable.size)]
252
+ if @rng.rand(3) == 0
253
+ @server.server_write(model_name: "Issue", operation: "destroy", id: victim)
254
+ @stats[:server_destroy] += 1
255
+ record_trace("step=#{step_idx} server destroy Issue id=#{victim}")
256
+ else
257
+ state = @rng.rand(2) == 0 ? "done" : "open"
258
+ @server.server_write(model_name: "Issue", operation: "update", id: victim, attributes: { state: state }, clock_offset: skew)
259
+ @stats[:server_update] += 1
260
+ record_trace("step=#{step_idx} server update Issue id=#{victim} state=#{state} clock_offset=#{skew}s")
261
+ end
262
+ end
263
+ end
264
+
265
+ def step_toggle_partition_or_skew(step_idx, client)
266
+ mode = FaultNetwork::PARTITION_MODES[@rng.rand(FaultNetwork::PARTITION_MODES.size)]
267
+ skew = CLOCK_SKEWS[@rng.rand(CLOCK_SKEWS.size)]
268
+ @network.set_partition(client.id, mode)
269
+ @network.set_clock_skew(client.id, skew)
270
+ @stats[:partition_changes] += 1
271
+ record_trace("step=#{step_idx} #{client.id} partition=#{mode} clock_skew=#{skew}s")
272
+ end
273
+
274
+ def step_sync_pass(step_idx, client)
275
+ res = client.sync(ENDPOINT)
276
+ @stats[:sync_passes] += 1
277
+ record_trace("step=#{step_idx} #{client.id} sync pending=#{res[:pending]} cursor=#{res[:cursor]} changed=#{res[:changed]} fault=#{res[:fault_fired]}")
278
+ end
279
+
280
+ def step_split_sse_stream(step_idx, client)
281
+ state = client.sync_state
282
+ return step_sync_pass(step_idx, client) unless state[:bootstrapped]
283
+
284
+ url = "#{ENDPOINT}/events?after=#{state[:cursor]}&window=0"
285
+ url += "&identity=#{state[:identity]}" unless state[:identity].empty?
286
+ reply = @network.exchange(client.id, "GET", url, "")
287
+ return unless reply[:status] == 200 && !reply[:body].empty?
288
+
289
+ body = reply[:body]
290
+ parts = 2 + @rng.rand(3)
291
+ chunk_size = [(body.length / parts), 1].max
292
+ applied_total = 0
293
+ offset = 0
294
+ while offset < body.length
295
+ piece = body[offset, chunk_size]
296
+ offset += chunk_size
297
+ res = client.consume_stream(piece)
298
+ applied_total += res[:applied]
299
+ end
300
+ @stats[:split_sse] += 1
301
+ record_trace("step=#{step_idx} #{client.id} split_sse parts=#{parts} applied=#{applied_total}")
302
+ end
303
+
304
+ def step_switch_identity(step_idx, client)
305
+ current = @network.policy(client.id).identity
306
+ choices = IDENTITIES - [current]
307
+ next_id = choices[@rng.rand(choices.size)]
308
+ @network.set_identity(client.id, next_id)
309
+ @stats[:identity_switches] += 1
310
+ record_trace("step=#{step_idx} #{client.id} switch_identity #{current.inspect} -> #{next_id.inspect}")
311
+ end
312
+
313
+ def step_arm_bootstrap_abort(step_idx, client)
314
+ mode = %i[network_drop server_503 truncated_body][@rng.rand(3)]
315
+ @network.arm_bootstrap_abort(client.id, mode)
316
+ @stats[:bootstrap_aborts] += 1
317
+ record_trace("step=#{step_idx} #{client.id} arm_bootstrap_abort mode=#{mode}")
318
+ end
319
+
320
+ def step_int32_boundary_event(step_idx)
321
+ id = "int32-chaos-#{@seed}-#{step_idx}"
322
+ @boundary_ids[id] = true
323
+ @server.seed_boundary_record(
324
+ model_name: "Issue",
325
+ id: id,
326
+ title: "int32 #{INT32_MIN}..#{INT32_MAX} step #{step_idx}",
327
+ server_version: INT32_MAX
328
+ )
329
+ @stats[:int32_boundaries] += 1
330
+ record_trace("step=#{step_idx} server seed_boundary_record id=#{id} server_version=#{INT32_MAX}")
331
+ end
332
+
333
+ def verify_step_invariants!(step_idx, client)
334
+ state = client.sync_state
335
+ if state[:pending] < 0
336
+ raise ConvergenceError, "step=#{step_idx} #{client.id} reported negative pending=#{state[:pending]}"
337
+ end
338
+ if state[:cursor] < 0
339
+ raise ConvergenceError, "step=#{step_idx} #{client.id} reported negative cursor=#{state[:cursor]}"
340
+ end
341
+ end
342
+
343
+ def heal_and_verify_convergence!
344
+ @network.heal_all!
345
+ @clients.each { |c| @network.set_clock_skew(c.id, 0.0) }
346
+ record_trace("heal_all: all partitions online, clock_skew=0")
347
+
348
+ # Drain every client's outbox and catch up all clients until quiescent.
349
+ 8.times do
350
+ @clients.each { |c| c.sync(ENDPOINT) }
351
+ all_ready = @clients.all? do |c|
352
+ st = c.sync_state
353
+ st[:bootstrapped] && st[:pending] == 0
354
+ end
355
+ if all_ready
356
+ # One final catch-up pass ensures every client sees writes drained by peers
357
+ # earlier in the same round.
358
+ @clients.each { |c| c.sync(ENDPOINT) }
359
+ break
360
+ end
361
+ end
362
+
363
+ snapshots_by_identity = Hash.new { |h, k| h[k] = [] }
364
+
365
+ @clients.each do |client|
366
+ identity = @network.policy(client.id).identity
367
+ snap = client.snapshot_state(model_names: MODELS)
368
+
369
+ unless snap[:bootstrapped]
370
+ raise ConvergenceError, "#{client.id} failed to bootstrap during heal phase"
371
+ end
372
+ unless snap[:pending] == 0
373
+ raise ConvergenceError, "#{client.id} still has pending=#{snap[:pending]} after heal phase"
374
+ end
375
+
376
+ snap[:sync_states].each do |model, rows|
377
+ unsynced = rows.reject { |r| r["sync_state"] == "synced" }
378
+ unless unsynced.empty?
379
+ raise ConvergenceError, "#{client.id} still has unsynced #{model} rows after heal: #{unsynced.inspect}"
380
+ end
381
+ end
382
+
383
+ # Under extreme forward clock skew (> HLC::DEFAULT_MAX_DRIFT), the server
384
+ # intentionally clamps updated_at to server UTC while keeping HLC-anchored
385
+ # ordering, so chaos convergence compares every domain column, created_at,
386
+ # and server_version bit-for-bit across all clients and the server.
387
+ expected = @server.visible_state(identity: identity).transform_values do |rows|
388
+ InstantRecord::Testing.canonical_rows(rows, exclude_columns: %w[sync_state updated_at])
389
+ end
390
+ actual = snap[:tables].transform_values do |rows|
391
+ InstantRecord::Testing.canonical_rows(rows, exclude_columns: %w[sync_state updated_at])
392
+ end
393
+ expected_json = InstantRecord::Testing.canonical_json(expected)
394
+ actual_json = InstantRecord::Testing.canonical_json(actual)
395
+
396
+ unless actual_json == expected_json
397
+ raise ConvergenceError,
398
+ "#{client.id} (#{client.runtime_name}, identity=#{identity.inspect}) diverged from server (#{@server.backend_label}):\n" \
399
+ "--- server ---\n#{expected_json}\n--- #{client.id} ---\n#{actual_json}"
400
+ end
401
+
402
+ snapshots_by_identity[identity] << [client, actual_json]
403
+ end
404
+
405
+ # Verify bit-for-bit agreement among peer clients sharing an identity.
406
+ snapshots_by_identity.each do |identity, list|
407
+ next if list.size < 2
408
+
409
+ ref_client, ref_json = list.first
410
+ list[1..].each do |other_client, other_json|
411
+ unless other_json == ref_json
412
+ raise ParityMismatch,
413
+ "Clients #{ref_client.id} and #{other_client.id} (identity=#{identity.inspect}) diverged bit-for-bit!"
414
+ end
415
+ end
416
+ end
417
+ end
418
+
419
+ def record_trace(line)
420
+ @trace << line
421
+ end
422
+
423
+ def format_failure(error)
424
+ tail = @trace.last(40).map { |l| " #{l}" }.join("\n")
425
+ "#{error.message}\n\nReproduce with:\n bundle exec rake instant_record:chaos SEED=#{@seed} STEPS=#{@steps} CLIENTS=#{@client_count} RUNTIMES=#{@runtime_names.join(',')}\n\nRecent trace (#{@trace.size} total events):\n#{tail}"
426
+ end
427
+ end
428
+ end
429
+ end