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
@@ -1,50 +1,294 @@
1
+ require "json"
1
2
  require "uri"
2
3
  require "time"
4
+ require "active_support/notifications"
3
5
  require "instant_record/client/transport"
4
6
  require "instant_record/client/notifier"
7
+ require "instant_record/client/rebaser"
5
8
 
6
9
  module InstantRecord
7
- # Browser-side sync client. Ruby owns the whole sync loop — transport
8
- # included — via JS fetch interop; the service worker shim only schedules
9
- # `InstantRecord.tick` (wasm Ruby cannot sleep without blocking the VM).
10
+ # Ruby reconciles local records and queued mutations. The worker handles network I/O.
10
11
  module Client
11
12
  # Columns the gem keeps for its own bookkeeping. A remote value that differs
12
13
  # in these alone is not a change to the row, it is our own write being
13
14
  # acknowledged twice.
14
15
  BOOKKEEPING_COLUMNS = %w[server_version sync_state].freeze
15
16
 
17
+ # More changes than this in one notice are not listed one by one.
18
+ MAX_LISTED_CHANGES = 200
19
+
20
+ # Cap buffered ActiveSupport::Notifications per host call so a runaway loop
21
+ # cannot exhaust the browser VM's heap.
22
+ MAX_RECORDED_EVENTS = 200
23
+
24
+ # SyncMetadata key prefixes for durable history tracking. Windowed models
25
+ # store per-partition contiguity low-water marks under HISTORY_WINDOW_PREFIX;
26
+ # non-windowed / opaque bridge keys live directly under HISTORY_KEY_PREFIX.
27
+ HISTORY_KEY_PREFIX = "history:".freeze
28
+ HISTORY_WINDOW_PREFIX = "history:window:".freeze
29
+
30
+ # Upper bound on bounded batches drained in a single synchronous pass.
31
+ MAX_DRAIN_CHUNKS_PER_PASS = 50
32
+
33
+ DRAIN_BATCH_LIMIT_KEY = "drain_batch_limit".freeze
34
+ RETRY_PREFIX = "outbox_5xx:".freeze
35
+ QUARANTINE_PREFIX = "quarantined:".freeze
36
+
37
+ # Individual attribute values larger than this are omitted from delta attrs
38
+ # (their column stays in changed_columns so UI patchers know to reload).
39
+ MAX_ATTR_BYTES = 4096
40
+
41
+ # Cap total serialized notice size so a huge batch degrades to a wildcard.
42
+ MAX_NOTICE_BYTES = 65_536
43
+
44
+ # Cap next_release_ms to 24 hours so it always fits safely inside a signed
45
+ # 32-bit integer on wasm32 Spinel builds.
46
+ MAX_RELEASE_DELAY_MS = 86_400_000
47
+
16
48
  class << self
17
49
  # Applying remote state must never enqueue new outbox mutations.
18
50
  def applying_remote? = @applying_remote
19
51
  def applying_remote(&block)
52
+ previous = @applying_remote
20
53
  @applying_remote = true
21
54
  block.call
22
55
  ensure
23
- @applying_remote = false
56
+ @applying_remote = previous
57
+ end
58
+
59
+ def current_hold_for = @hold_for
60
+
61
+ def enter_hold(seconds)
62
+ if seconds.nil?
63
+ normalized = nil
64
+ else
65
+ normalized = seconds.to_f
66
+ raise ArgumentError, "hold_for must be non-negative" if normalized < 0.0
67
+ normalized = nil if normalized == 0.0
68
+ end
69
+
70
+ previous = @hold_for
71
+ @hold_for = normalized
72
+ previous
73
+ end
74
+
75
+ def leave_hold(previous)
76
+ @hold_for = previous
77
+ end
78
+
79
+ # Hold local outbox writes created inside the block for `seconds` before
80
+ # they mature for drain. Nested calls restore the outer hold window.
81
+ def with_hold(seconds)
82
+ previous = enter_hold(seconds)
83
+ yield
84
+ ensure
85
+ leave_hold(previous)
24
86
  end
25
87
 
26
- # Seams: real implementations are JS-interop-backed and browser-only;
88
+ # Seams: real implementations are worker-backed and browser-only;
27
89
  # tests inject doubles so the loop runs under CRuby.
28
90
  attr_writer :transport, :notifier
29
91
 
30
92
  def transport
31
- @transport ||= Transport::JsFetch.new
93
+ @transport ||= Transport::WorkerFetch.new
32
94
  end
33
95
 
34
96
  def notifier
35
- @notifier ||= Notifier::JsClients.new
97
+ @notifier ||= Notifier::Worker.new
98
+ end
99
+
100
+ # Pluggable client-side headers sent on every outbound sync request
101
+ # (bootstrap, mutations, events, history). Merges:
102
+ # 1. X-Instant-Record-Scope (from config.sync_scope)
103
+ # 2. X-Instant-Record-Partition (from config.sync_partition)
104
+ # 3. Authorization (from config.auth_token)
105
+ # 4. Custom headers (from config.headers — Hash or callable)
106
+ def request_headers
107
+ result = {}
108
+ config = InstantRecord.config
109
+ scope = config.sync_scope
110
+ result["X-Instant-Record-Scope"] = scope.to_s if scope && !scope.to_s.empty?
111
+
112
+ partition = config.sync_partition
113
+ formatted = format_partition_header(partition)
114
+ result["X-Instant-Record-Partition"] = formatted if formatted
115
+
116
+ token = config.auth_token
117
+ if token && !token.to_s.empty?
118
+ str = token.to_s
119
+ result["Authorization"] = str.include?(" ") ? str : "Bearer #{str}"
120
+ end
121
+
122
+ extra = config.headers.respond_to?(:call) ? config.headers.call : config.headers
123
+ if extra.is_a?(Hash)
124
+ extra.each do |name, value|
125
+ result[name.to_s] = value.to_s if value && !value.to_s.empty?
126
+ end
127
+ end
128
+ result
36
129
  end
37
130
 
38
- # One full pass: outbox up, changes down, tabs notified when anything
131
+ # Background history-fill targets declared by the server's bootstrap response.
132
+ def fill_targets
133
+ raw = SyncMetadata.get("history_fill_targets")
134
+ raw ? JSON.parse(raw) : []
135
+ rescue JSON::ParserError
136
+ []
137
+ end
138
+
139
+ # One full pass: outbox up, changes down, tabs notified when visible rows
39
140
  # moved. Called under InstantRecord.tick's single-flight guard. A client
40
141
  # that has never synced hydrates from the bootstrap snapshot instead of
41
142
  # replaying the whole change log from cursor 0.
143
+ #
144
+ # Returns whether local SQLite state changed (including pure outbox acks,
145
+ # so the worker persists the drained outbox), while `notify_changed` only
146
+ # fires when visible record data changed (evictions, reconciliations,
147
+ # remote deltas, resets, or bootstrap).
42
148
  def sync_pass
43
- changed = evict_beyond_windows
44
- changed = drain || changed
45
- changed = (bootstrapped? ? poll_changes : bootstrap) || changed
46
- notifier.records_changed if changed
47
- changed
149
+ return false if InstantRecord.branched?
150
+
151
+ evicted = evict_beyond_windows
152
+ drained, reconciled = drain_outbox
153
+ pulled = bootstrapped? ? poll_changes : bootstrap
154
+ notify_changed if evicted || reconciled || pulled || recorded_notices.any?
155
+ evicted || drained || pulled
156
+ end
157
+
158
+ # Which records changed since the page was last told: "records_changed"
159
+ # followed by one compact JSON delta per line:
160
+ # {"type":"MailEntry","id":"a-1","op":"update","changed_columns":[...],"attrs":{...}}
161
+ # plus any quarantined sync notices as "sync_notice:<json>" lines. The
162
+ # notice alone means anything may have changed (bootstrap, eviction,
163
+ # reset, or a batch past the listing or byte budget).
164
+ def changes_notice
165
+ lines = ["records_changed"]
166
+ unless @unlisted_changes || changed_records.empty?
167
+ delta_lines = changed_records.map { |delta| JSON.generate(delta) }
168
+ delta_payload = "records_changed\n" + delta_lines.join("\n")
169
+ lines.concat(delta_lines) if delta_payload.bytesize <= MAX_NOTICE_BYTES
170
+ end
171
+ recorded_notices.each { |notice| lines << "sync_notice:#{JSON.generate(notice)}" }
172
+ lines.join("\n")
173
+ end
174
+
175
+ def changed_records
176
+ @changed_records ||= []
177
+ end
178
+
179
+ def recorded_notices
180
+ @recorded_notices ||= []
181
+ end
182
+
183
+ def unlisted_changes
184
+ @unlisted_changes = true
185
+ end
186
+
187
+ def capturing_changes?
188
+ !!@capturing_changes
189
+ end
190
+
191
+ # Capture local Syncable writes during a request or native action and
192
+ # flush them to the notifier when the block completes normally.
193
+ def capture_local_changes
194
+ nested = @capturing_changes
195
+ @capturing_changes = true
196
+ unless nested
197
+ changed_records.clear
198
+ changed_index.clear
199
+ @unlisted_changes = false
200
+ end
201
+ result = yield
202
+ if !nested && (@unlisted_changes || !changed_records.empty?)
203
+ notify_changed
204
+ end
205
+ result
206
+ rescue StandardError
207
+ unless nested
208
+ changed_records.clear
209
+ changed_index.clear
210
+ @unlisted_changes = false
211
+ end
212
+ raise
213
+ ensure
214
+ @capturing_changes = nested
215
+ end
216
+
217
+ def note_change(type, id, op: "update", changed_columns: [], attrs: {})
218
+ return if @unlisted_changes
219
+
220
+ changed_index.clear if changed_records.empty?
221
+ key = "#{type}\0#{id}"
222
+ delta = {
223
+ "type" => type.to_s,
224
+ "id" => id.to_s,
225
+ "op" => op.to_s,
226
+ "changed_columns" => Array(changed_columns).map(&:to_s).uniq,
227
+ "attrs" => compact_attrs(attrs)
228
+ }
229
+
230
+ if (existing_idx = changed_index[key])
231
+ changed_records[existing_idx] = merge_delta(changed_records[existing_idx], delta)
232
+ elsif changed_records.size >= MAX_LISTED_CHANGES
233
+ unlisted_changes
234
+ else
235
+ changed_index[key] = changed_records.size
236
+ changed_records << delta
237
+ end
238
+ end
239
+
240
+ def note_record_change(record, op, changed_columns: nil)
241
+ return if @unlisted_changes
242
+
243
+ model = record.class
244
+ raw = record.attributes
245
+ op_s = op.to_s
246
+ case op_s
247
+ when "create"
248
+ cols = raw.keys.map(&:to_s)
249
+ note_change(model.name, record.id, op: "create", changed_columns: cols, attrs: compact_attrs(raw))
250
+ when "update"
251
+ cols = Array(changed_columns).map(&:to_s).uniq
252
+ selected = {}
253
+ cols.each { |col| selected[col] = raw[col] if raw.key?(col) }
254
+ context_columns_for(model, raw).each { |col| selected[col] = raw[col] if raw.key?(col) }
255
+ note_change(model.name, record.id, op: "update", changed_columns: cols, attrs: compact_attrs(selected))
256
+ when "destroy"
257
+ selected = {}
258
+ context_columns_for(model, raw).each { |col| selected[col] = raw[col] if raw.key?(col) }
259
+ note_change(model.name, record.id, op: "destroy", changed_columns: [], attrs: compact_attrs(selected))
260
+ else
261
+ note_change(model.name, record.id, op: op_s)
262
+ end
263
+ end
264
+
265
+ def notify_changed
266
+ notifier.records_changed
267
+ changed_records.clear
268
+ changed_index.clear
269
+ recorded_notices.clear
270
+ @unlisted_changes = false
271
+ end
272
+
273
+ # Bridged notifications captured during the current host call so the JS
274
+ # worker receives ActiveSupport::Notifications across the WASI boundary.
275
+ def recorded_events
276
+ @recorded_events ||= []
277
+ end
278
+
279
+ def clear_events
280
+ recorded_events.clear
281
+ nil
282
+ end
283
+
284
+ def events_notice
285
+ JSON.generate(recorded_events)
286
+ end
287
+
288
+ def drain_events
289
+ snapshot = recorded_events.dup
290
+ recorded_events.clear
291
+ snapshot
48
292
  end
49
293
 
50
294
  # Arm the boot-time trim; InstantRecord.start sets this on cold boots
@@ -55,8 +299,11 @@ module InstantRecord
55
299
 
56
300
  # Trim every windowed model back to its declared window. delete_all
57
301
  # under applying_remote: no callbacks, no outbox rows. Pending rows are
58
- # excluded in the WHERE — an unsynced write is never evicted. Returns
59
- # true when anything was deleted.
302
+ # excluded before ranking — unsynced writes are never evicted and never
303
+ # push synced rows out of the window. Any partition whose rows were
304
+ # trimmed has its durable history mark invalidated in the same SQLite
305
+ # transaction so later pagination refetches instead of serving ghost empty
306
+ # pages. Returns true when anything was deleted.
60
307
  def evict_beyond_windows
61
308
  return false unless @eviction_pending
62
309
 
@@ -67,18 +314,156 @@ module InstantRecord
67
314
  next unless window
68
315
 
69
316
  applying_remote do
70
- evicted = true if window.beyond_window(model.where.not(sync_state: "pending")).delete_all.positive?
317
+ evicted = true if evict_model_window(model, window)
71
318
  end
72
319
  end
320
+ unlisted_changes if evicted
73
321
  evicted
74
322
  end
75
323
 
76
- def pending_count
77
- OutboxMutation.count
324
+ def pending_count(now = Time.now.utc)
325
+ return OutboxMutation.matured(now).count unless OutboxMutation.held(now).exists?
326
+
327
+ matured_outbox_rows(now).size
328
+ end
329
+
330
+ # Matured outbox rows ready to drain (release_at IS NULL OR release_at <= now).
331
+ # Preserves per-record causal order: a later write to a record with an earlier
332
+ # held mutation waits behind it, while independent records drain immediately.
333
+ def pending_mutations(now = Time.now.utc)
334
+ matured_outbox_rows(now).map(&:as_mutation)
335
+ end
336
+
337
+ # Snapshot the exact outgoing mutation batch for a two-phase host sync
338
+ # (sync_plan -> network fetch -> sync). Pinning the planned IDs prevents
339
+ # a held mutation that matures mid-fetch from altering the batch body
340
+ # between sync_plan and drain.
341
+ def plan_drain(now = Time.now.utc)
342
+ mutations = drain_batch(now: now)
343
+ @planned_drain_ids = mutations.map { |m| m[:id] }
344
+ mutations
345
+ end
346
+
347
+ def clear_planned_drain
348
+ @planned_drain_ids = nil
349
+ end
350
+
351
+ def held_mutations(now = Time.now.utc)
352
+ OutboxMutation.held(now).ordered
353
+ end
354
+
355
+ def held_count(now = Time.now.utc)
356
+ OutboxMutation.held(now).count
357
+ end
358
+
359
+ def next_release_at(now = Time.now.utc)
360
+ OutboxMutation.held(now).order(:release_at, :created_at, :id).first&.release_at
361
+ end
362
+
363
+ def next_release_ms(now = Time.now.utc)
364
+ release_at = next_release_at(now)
365
+ return nil unless release_at
366
+
367
+ seconds = release_at.to_f - now.to_f
368
+ return 0 if seconds <= 0.0
369
+ return MAX_RELEASE_DELAY_MS if seconds >= 86_400.0
370
+
371
+ (seconds * 1000.0).ceil
372
+ end
373
+
374
+ # Cancel a held outbox mutation before its release_at matures: restore the
375
+ # local SQLite row from its pre-mutation snapshot and delete the outbox row
376
+ # atomically. Returns true when cancelled, false when unknown, already
377
+ # released/matured, or superseded by a later outbox mutation on the same row.
378
+ def cancel_pending(mutation_id, now: Time.now.utc)
379
+ cancelled = nil
380
+
381
+ OutboxMutation.transaction do
382
+ mutation = OutboxMutation.find_by(id: mutation_id)
383
+ next unless mutation && mutation.held?(now)
384
+
385
+ later = OutboxMutation.where(record_type: mutation.record_type, record_id: mutation.record_id)
386
+ .where("created_at > :at OR (created_at = :at AND id > :id)", at: mutation.created_at, id: mutation.id)
387
+ .exists?
388
+ next if later
389
+
390
+ model = InstantRecord.synced_model(mutation.record_type)
391
+ next unless model
392
+
393
+ earlier_pending = OutboxMutation.where(record_type: mutation.record_type, record_id: mutation.record_id)
394
+ .where.not(id: mutation.id)
395
+ .exists?
396
+
397
+ restored = applying_remote do
398
+ if Rebaser.confirmed_snapshot(mutation.record_type, mutation.record_id) &&
399
+ (mutation.operation == "create" || mutation.rollback_payload.is_a?(Hash))
400
+ Rebaser.reconcile_quarantined_mutation(mutation)
401
+ true
402
+ else
403
+ case mutation.operation
404
+ when "create"
405
+ model.find_by(id: mutation.record_id)&.destroy!
406
+ mutation.destroy!
407
+ true
408
+ when "update", "destroy"
409
+ if mutation.rollback_payload.is_a?(Hash)
410
+ restore_record(model, mutation, earlier_pending: earlier_pending)
411
+ mutation.destroy!
412
+ true
413
+ else
414
+ false
415
+ end
416
+ else
417
+ false
418
+ end
419
+ end
420
+ end
421
+ next unless restored
422
+
423
+ Rebaser.clear_confirmed_snapshot(mutation.record_type, mutation.record_id) unless earlier_pending
424
+ cancelled = {
425
+ mutation_id: mutation.id,
426
+ record_type: mutation.record_type,
427
+ record_id: mutation.record_id,
428
+ operation: mutation.operation
429
+ }
430
+ end
431
+
432
+ return false unless cancelled
433
+
434
+ instrument("cancel_pending", cancelled)
435
+ true
436
+ end
437
+
438
+ # Next bounded chunk of matured outbox mutations to POST. Respects
439
+ # `config.drain_batch_size`, adaptive 5xx bisection limits, and per-record
440
+ # causal ordering behind held (`hold_for:`) mutations.
441
+ def drain_batch(limit: effective_drain_batch_size, now: Time.now.utc)
442
+ matured_outbox_rows(now).first(limit).map(&:as_mutation)
443
+ end
444
+
445
+ def effective_drain_batch_size
446
+ configured = [InstantRecord.config.drain_batch_size.to_i, 1].max
447
+ adaptive = SyncMetadata.get(DRAIN_BATCH_LIMIT_KEY)&.to_i
448
+ adaptive && adaptive.positive? ? [configured, adaptive].min : configured
449
+ end
450
+
451
+ def quarantined_mutations
452
+ entries = []
453
+ SyncMetadata.all.each do |entry|
454
+ next unless entry.key.start_with?(QUARANTINE_PREFIX)
455
+
456
+ entries << JSON.parse(entry.value)
457
+ rescue JSON::ParserError
458
+ next
459
+ end
460
+ entries.sort_by { |e| [e["quarantined_at"].to_s, e["mutation_id"].to_s] }
78
461
  end
79
462
 
80
- def pending_mutations
81
- OutboxMutation.ordered.map(&:as_mutation)
463
+ def clear_quarantined_mutations
464
+ SyncMetadata.all.each do |entry|
465
+ entry.destroy if entry.key.start_with?(QUARANTINE_PREFIX)
466
+ end
82
467
  end
83
468
 
84
469
  def cursor
@@ -96,35 +481,188 @@ module InstantRecord
96
481
  !SyncMetadata.get("cursor").nil?
97
482
  end
98
483
 
484
+ # The name the server gave the person this browser synced as, when the
485
+ # server tells people apart. It is sent back with every request so the
486
+ # server can say when that person has changed.
487
+ def identity_key
488
+ SyncMetadata.get("identity")
489
+ end
490
+
491
+ # The body of an outbox drain. The compiled worker prepares the same
492
+ # request ahead of the pass, so both build it here.
493
+ def mutations_payload(mutations)
494
+ key = identity_key
495
+ key.nil? ? { mutations: mutations } : { mutations: mutations, identity: key }
496
+ end
497
+
498
+ # The server says this browser synced as someone else. Everything it was
499
+ # sent for that person goes, with the writes they had queued to those
500
+ # models, and the next pass starts again from a bootstrap as whoever is
501
+ # here now. Models every client may see keep their queued writes.
502
+ def reset(event)
503
+ types = Array(event["types"])
504
+ applying_remote do
505
+ types.each do |type|
506
+ model = InstantRecord.synced_model(type)
507
+ model.delete_all if model
508
+ end
509
+ end
510
+ destroyed_ids = []
511
+ OutboxMutation.all.each do |mutation|
512
+ drop = types.include?(mutation.record_type)
513
+ if !drop && mutation.mutator?
514
+ mutation.touched_records.each do |entry|
515
+ if types.include?(entry["type"])
516
+ drop = true
517
+ break
518
+ end
519
+ end
520
+ end
521
+ if drop
522
+ destroyed_ids << mutation.id
523
+ mutation.destroy
524
+ end
525
+ end
526
+ Rebaser.reset_types(types)
527
+ SyncNotice.all.each do |notice|
528
+ notice.destroy if types.include?(notice.record_type)
529
+ end
530
+ # The rows that stay were last brought up to date at this cursor. The
531
+ # bootstrap to come only adds and changes rows, so the poll after it
532
+ # starts here again and a destroy made in between is not missed.
533
+ SyncMetadata.set("replay_from", cursor) if bootstrapped? && SyncMetadata.get("replay_from").nil?
534
+ SyncMetadata.all.each do |entry|
535
+ if entry.key == "cursor" || entry.key == "identity" || entry.key == DRAIN_BATCH_LIMIT_KEY ||
536
+ entry.key.start_with?(HISTORY_KEY_PREFIX) ||
537
+ types.any? { |type| entry.key.start_with?("#{HLC::ROW_PREFIX}#{type}:") } ||
538
+ (entry.key.start_with?(RETRY_PREFIX) && destroyed_ids.include?(entry.key[RETRY_PREFIX.length..]))
539
+ entry.destroy
540
+ elsif entry.key.start_with?(QUARANTINE_PREFIX)
541
+ parsed = begin JSON.parse(entry.value) rescue nil end
542
+ entry.destroy if parsed && types.include?(parsed["record_type"])
543
+ end
544
+ end
545
+ unlisted_changes
546
+ instrument("reset")
547
+ true
548
+ end
549
+
99
550
  # First-sync hydration: windowed current state + cursor in one response.
100
551
  # The server captures the cursor BEFORE reading rows, so any overlap
101
552
  # with subsequent events re-applies idempotently. Returns true when the
102
553
  # snapshot applied.
103
554
  def bootstrap
104
- body = transport.get_json("/bootstrap")
105
- Array(body["records"]).each { |record| apply_change(record) }
555
+ return false if InstantRecord.branched?
106
556
 
107
- # Cursor written last: a crash mid-apply leaves it nil, so the next
108
- # tick re-bootstraps; upserts make the retry idempotent. A failure
109
- # never falls through to a cursor-0 poll of the full change log.
110
- self.cursor = body["cursor"]
111
- true
557
+ instrument("bootstrap") do |event|
558
+ body = transport_get_json("/bootstrap")
559
+ event[:records] = apply_bootstrap_body(body)
560
+ true
561
+ end
112
562
  rescue Transport::Error => e
113
563
  log_failure("bootstrap", e)
114
564
  false
115
565
  end
116
566
 
117
- # Outbox up. Returns true when anything was sent and applied.
567
+ # Outbox up in bounded batches. Halves batch size on multi-mutation 5xx
568
+ # responses and isolates a single poison pill after N 5xx retries so
569
+ # healthy mutations behind it keep draining. Returns true when anything
570
+ # was sent, applied, or quarantined.
118
571
  def drain
119
- mutations = pending_mutations
120
- return false if mutations.empty?
572
+ return false if InstantRecord.branched?
121
573
 
122
- body = transport.post_json("/mutations", { mutations: mutations })
123
- apply_results(body["results"])
124
- true
125
- rescue Transport::Error => e
126
- log_failure("drain", e)
127
- false
574
+ drain_outbox.first
575
+ end
576
+
577
+ # Merge pre-fetched push and/or bootstrap responses from an async worker
578
+ # into the current SQLite state by mutation_id, without discarding acks
579
+ # when newer local edits landed while the network call was in flight.
580
+ # Pure self-acks persist SQLite (`changed: true`) while staying quiet on
581
+ # `records_changed`; evictions, reconciliations, quarantines, and
582
+ # bootstrap still notify tabs.
583
+ def apply_prepared_sync(push: nil, bootstrap: nil)
584
+ return { changed: false, progressed: false, failed: false, quarantined: 0 } if InstantRecord.branched?
585
+
586
+ evicted = evict_beyond_windows
587
+ changed = evicted
588
+ reconciled = false
589
+ bootstrapped_now = false
590
+ progressed = false
591
+ failed = false
592
+ quarantined = 0
593
+
594
+ if push
595
+ push = push.deep_stringify_keys
596
+ status = push["status"].to_i
597
+ sent_ids = Array(push["mutation_ids"]).map(&:to_s)
598
+
599
+ if status >= 200 && status < 300
600
+ begin
601
+ body = JSON.parse(push["body"].to_s)
602
+ observe_server_time(body["server_time"])
603
+ instrument("drain") do |event|
604
+ results = Array(body["results"]).map { |r| r.deep_stringify_keys }
605
+ resolved, batch_reconciled = apply_results_with_counts(results)
606
+ clear_adaptive_batch_limit if pending_count == 0
607
+ changed = true if resolved.positive?
608
+ reconciled = true if batch_reconciled
609
+ progressed = true if resolved.positive? || sent_ids.none? { |id| OutboxMutation.find_by(id: id) }
610
+ event[:posted] = sent_ids.size
611
+ event[:rejected] = results.count { |r| r["status"] == "rejected" }
612
+ event[:reasons] = results.filter_map { |r| r["reason"] }.uniq.first(3)
613
+ event[:batches] = 1
614
+ event[:quarantined] = 0
615
+ end
616
+ rescue JSON::ParserError => e
617
+ log_failure("drain", Transport::Error.new("POST /mutations -> invalid JSON: #{e.message}", status: status))
618
+ failed = true
619
+ end
620
+ elsif status >= 500 && status < 600
621
+ outcome = handle_drain_failure(sent_ids, status: status, error: "POST /mutations -> #{status}")
622
+ if outcome[:quarantined].positive?
623
+ quarantined += outcome[:quarantined]
624
+ changed = true
625
+ reconciled = true if outcome[:reconciled]
626
+ progressed = true
627
+ else
628
+ log_failure("drain", Transport::Error.new("POST /mutations -> #{status}", status: status))
629
+ failed = true
630
+ end
631
+ else
632
+ log_failure("drain", Transport::Error.new("POST /mutations -> #{status}", status: status))
633
+ failed = true
634
+ end
635
+ end
636
+
637
+ if bootstrap && !bootstrapped?
638
+ bootstrap = bootstrap.deep_stringify_keys
639
+ status = bootstrap["status"].to_i
640
+ if status >= 200 && status < 300
641
+ begin
642
+ body = JSON.parse(bootstrap["body"].to_s)
643
+ instrument("bootstrap") do |event|
644
+ event[:records] = apply_bootstrap_body(body)
645
+ end
646
+ changed = true
647
+ bootstrapped_now = true
648
+ progressed = true
649
+ rescue JSON::ParserError => e
650
+ log_failure("bootstrap", Transport::Error.new("GET /bootstrap -> invalid JSON: #{e.message}", status: status))
651
+ failed = true
652
+ end
653
+ else
654
+ log_failure("bootstrap", Transport::Error.new("GET /bootstrap -> #{status}", status: status))
655
+ failed = true
656
+ end
657
+ end
658
+
659
+ notify_changed if evicted || reconciled || bootstrapped_now || recorded_notices.any?
660
+
661
+ { changed: changed, progressed: progressed, failed: failed, quarantined: quarantined }
662
+ end
663
+
664
+ def observe_server_time(server_time)
665
+ HLC.observe_server_time(server_time) if server_time
128
666
  end
129
667
 
130
668
  # Set while something outside the VM holds a tailing stream and feeds
@@ -158,6 +696,21 @@ module InstantRecord
158
696
  nil
159
697
  end
160
698
 
699
+ # A native host opened another database file: drop what was held in
700
+ # memory about the one before.
701
+ def forget_database
702
+ reset_stream
703
+ changed_records.clear
704
+ recorded_events.clear
705
+ changed_index.clear
706
+ recorded_notices.clear
707
+ @unlisted_changes = false
708
+ @capturing_changes = false
709
+ @eviction_pending = false
710
+ @planned_drain_ids = nil
711
+ nil
712
+ end
713
+
161
714
  # Applies events delivered from outside — a stream the worker is holding.
162
715
  # Idempotent by the same upsert + last-write-wins path a poll uses, so a
163
716
  # replayed or overlapping batch is harmless. Returns the number applied.
@@ -165,8 +718,20 @@ module InstantRecord
165
718
  applied = 0
166
719
  newest_cursor = nil
167
720
 
721
+ was_reset = false
722
+
168
723
  Array(events).each do |event|
724
+ # Nothing after a reset belongs to this client any more, and the
725
+ # cursor it would have advanced is gone.
726
+ next if was_reset
727
+
169
728
  event = event.deep_stringify_keys
729
+ observe_server_time(event["server_time"])
730
+ if event["operation"] == "reset"
731
+ was_reset = reset(event)
732
+ applied += 1
733
+ next
734
+ end
170
735
  applied += 1 if apply_change(event)
171
736
  # The cursor advances for every event, changed or not: an echo we chose
172
737
  # to ignore must not be handed to us again.
@@ -175,8 +740,9 @@ module InstantRecord
175
740
 
176
741
  # One cursor write per batch, as poll_changes does: a crash before this
177
742
  # re-applies the batch, which the upserts make safe.
178
- self.cursor = newest_cursor if newest_cursor
179
- notifier.records_changed if applied.positive?
743
+ self.cursor = newest_cursor if newest_cursor && !was_reset
744
+ notify_changed if applied.positive?
745
+ instrument("stream", applied: applied) if applied.positive?
180
746
  applied
181
747
  end
182
748
 
@@ -189,20 +755,38 @@ module InstantRecord
189
755
  # delivering, and re-polling would only re-fetch what it just applied.
190
756
  # Returns true when any remote change was applied.
191
757
  def poll_changes
192
- return false if streaming?
758
+ return false if streaming? || InstantRecord.branched?
193
759
 
194
760
  changed = false
761
+ applied = 0
195
762
  last_cursor = nil
763
+ was_reset = false
764
+ key = identity_key
765
+ path = "/events?after=#{cursor}&window=0"
766
+ path += "&identity=#{key}" unless key.nil?
767
+
768
+ instrument("poll") do |note|
769
+ transport_each_event(path) do |event|
770
+ event = event.deep_stringify_keys
771
+ next if was_reset
772
+ observe_server_time(event["server_time"])
773
+ if event["operation"] == "reset"
774
+ was_reset = reset(event)
775
+ changed = true
776
+ next
777
+ end
778
+ if apply_change(event)
779
+ changed = true
780
+ applied += 1
781
+ end
782
+ last_cursor = event["cursor"] || last_cursor
783
+ end
784
+ note[:applied] = applied
196
785
 
197
- transport.each_event("/events?after=#{cursor}&window=0") do |event|
198
- event = event.deep_stringify_keys
199
- changed = true if apply_change(event)
200
- last_cursor = event["cursor"] || last_cursor
786
+ # One cursor write per poll, not per event. A crash before this line
787
+ # re-applies the batch next poll; upserts + LWW make that idempotent.
788
+ self.cursor = last_cursor if last_cursor && !was_reset
201
789
  end
202
-
203
- # One cursor write per poll, not per event. A crash before this line
204
- # re-applies the batch next poll; upserts + LWW make that idempotent.
205
- self.cursor = last_cursor if last_cursor
206
790
  changed
207
791
  rescue Transport::Error => e
208
792
  log_failure("poll", e)
@@ -223,89 +807,354 @@ module InstantRecord
223
807
  raise ArgumentError, "#{model.name} windows by #{window.partition_by}; pass partition:" if window.partition_by && partition.nil?
224
808
 
225
809
  limit ||= window.limit
226
- before_at = Time.parse(before[:created_at].to_s)
810
+ before_at = parse_time(before[:created_at].to_s)
227
811
  before_id = before[:id].to_s
228
812
 
229
813
  unless InstantRecord.browser?
230
814
  return { ok: true, applied: 0, has_more: local_page(window, partition, before_at, before_id, limit + 1).size > limit }
231
815
  end
232
816
 
233
- if (mark = history_mark(model, partition)) && page_local?(mark, window, partition, before_at, before_id, limit)
234
- # has_more from the served page, not the partition-wide mark: rows
235
- # remain below this page when the local probe overflows `limit`, or
236
- # when the page reaches the contiguity frontier and the server still
237
- # has older rows (mark[:has_more]). Echoing the mark alone reports
238
- # "beginning reached" for any mid-history page after the true
239
- # beginning was loaded.
240
- local = local_page(window, partition, before_at, before_id, limit + 1)
241
- return { ok: true, applied: 0, has_more: local.size > limit || mark[:has_more] }
817
+ if (local = local_history_page(model, window, partition, before_at, before_id, limit))
818
+ return local
242
819
  end
243
820
 
244
- body = transport.get_json(history_path(model, partition, before_at, before_id, limit))
245
- records = Array(body["records"])
246
- records.each { |record| apply_change(record) }
247
- extend_history_mark(model, partition, records, has_more: !!body["has_more"])
248
- { ok: true, applied: records.size, has_more: !!body["has_more"] }
821
+ instrument("fetch_history") do |event|
822
+ body = transport_get_json(history_path(model, partition, before_at, before_id, limit))
823
+ observe_server_time(body["server_time"])
824
+ result = apply_history_page(model, partition, Array(body["records"]), has_more: !!body["has_more"])
825
+ event[:applied] = result[:applied]
826
+ event[:has_more] = result[:has_more]
827
+ result
828
+ end
249
829
  rescue Transport::Error => e
250
830
  log_failure("fetch_history", e)
251
831
  { ok: false, applied: 0, has_more: nil, error: e.message }
252
832
  end
253
833
 
834
+ # Unified history entry point for the compiled bridges (WasmBridge and
835
+ # NativeBridge). Windowed keyset queries share the durable SQLite
836
+ # contiguity ledger with fetch_history; non-windowed queries (search,
837
+ # thread lookups, and opaque Native screen keys) keep their per-key
838
+ # receipt in SyncMetadata in the same transaction as their records.
839
+ def handle_history(key:, response: "")
840
+ key = key.to_s
841
+ response = response.to_s
842
+
843
+ if (query = parse_windowed_history_key(key))
844
+ handle_windowed_history(query, response)
845
+ else
846
+ handle_opaque_history(key, response)
847
+ end
848
+ end
849
+
254
850
  # Server results for a posted batch. Every result drops the outbox row —
255
- # each one is a durable resolution, not a retry — and what happens to the
256
- # record depends on which resolution it is:
257
- # applied -> mark the record synced
258
- # applied + skipped -> the write lost last-write-wins; reconcile to the
259
- # value that won, because it did NOT land here
260
- # rejected -> reconcile to server state
851
+ # each one is a durable resolution, not a retry — and reconciles the row
852
+ # through GGPO dirty-row rebasing so newer unacked local edits on the same
853
+ # row are deterministically replayed over server truth instead of clobbered.
854
+ #
855
+ # Returns whether any result changed visible local record data (a rollback,
856
+ # removal, or rebase delta), as distinct from pure self-acknowledgements.
261
857
  def apply_results(results)
858
+ apply_results_with_counts(results).last
859
+ end
860
+
861
+ # Apply one remote change event (HLC-ordered, with updated_at fallback
862
+ # for legacy events) and note it for the next records_changed notice.
863
+ # Clean rows apply directly; dirty rows rewind to their server-confirmed
864
+ # snapshot, apply server truth, and deterministically replay remaining
865
+ # unacked mutations. Returns whether the visible row moved.
866
+ def apply_change(event)
867
+ apply_remote_event(event, record_delta: true)
868
+ end
869
+
870
+ # Apply one remote record payload without noting it for records_changed
871
+ # (used by bootstrap and history pages, which handle notification separately).
872
+ def apply_record(event)
873
+ apply_remote_event(event, record_delta: false)
874
+ end
875
+
876
+ private
877
+
878
+ def apply_remote_event(event, record_delta:)
879
+ event = event.deep_stringify_keys
880
+ model = InstantRecord.synced_model(event["type"])
881
+ return false unless model
882
+
883
+ record_id = event["id"] || (event["attributes"].is_a?(Hash) && event["attributes"]["id"])
884
+ applying_remote do
885
+ if record_id && Rebaser.dirty?(event["type"], record_id)
886
+ Rebaser.apply_server_delta(
887
+ model,
888
+ record_id,
889
+ operation: event["operation"],
890
+ attributes: event["attributes"],
891
+ version: event["version"],
892
+ hlc: event["hlc"],
893
+ record_delta: record_delta
894
+ )
895
+ elsif event["operation"] == "destroy"
896
+ HLC.receive(event["hlc"]) if HLC.valid?(event["hlc"])
897
+ HLC.delete_row_hlc(event["type"], record_id)
898
+ record = model.find_by(id: record_id)
899
+ return false unless record
900
+
901
+ destroy_attrs = record_delta ? destroy_context_attrs(model, record) : nil
902
+ record.destroy!
903
+ note_change(event["type"], record_id, op: "destroy", changed_columns: [], attrs: destroy_attrs) if record_delta
904
+ true
905
+ else
906
+ upsert_from_server(model, event["attributes"], event["version"], hlc: event["hlc"], record_delta: record_delta)
907
+ end
908
+ end
909
+ end
910
+
911
+ def changed_index
912
+ @changed_index ||= {}
913
+ end
914
+
915
+ def merge_delta(prev, incoming)
916
+ prev_op = prev["op"]
917
+ next_op = incoming["op"]
918
+ if next_op == "destroy"
919
+ {
920
+ "type" => incoming["type"],
921
+ "id" => incoming["id"],
922
+ "op" => "destroy",
923
+ "changed_columns" => [],
924
+ "attrs" => incoming["attrs"]
925
+ }
926
+ elsif prev_op == "destroy" && next_op == "create"
927
+ incoming
928
+ else
929
+ merged_op = prev_op == "create" ? "create" : next_op
930
+ {
931
+ "type" => incoming["type"],
932
+ "id" => incoming["id"],
933
+ "op" => merged_op,
934
+ "changed_columns" => (prev["changed_columns"] + incoming["changed_columns"]).uniq,
935
+ "attrs" => prev["attrs"].merge(incoming["attrs"])
936
+ }
937
+ end
938
+ end
939
+
940
+ def compact_attrs(attrs)
941
+ return {} unless attrs.is_a?(Hash)
942
+
943
+ out = {}
944
+ attrs.each do |key, value|
945
+ encoded = wire_value(value)
946
+ next if encoded.is_a?(String) && encoded.bytesize > MAX_ATTR_BYTES
947
+
948
+ out[key.to_s] = encoded
949
+ end
950
+ out
951
+ end
952
+
953
+ def wire_value(value)
954
+ value.respond_to?(:usec) ? value.iso8601(InstantRecord::TIME_PRECISION) : value
955
+ end
956
+
957
+ def context_columns_for(model, raw)
958
+ cols = ["id"]
959
+ window = model.respond_to?(:instant_record_sync_window) ? model.instant_record_sync_window : nil
960
+ cols << window.partition_by.to_s if window && window.partition_by
961
+ scope_col = model.respond_to?(:instant_record_sync_scope) ? model.instant_record_sync_scope : nil
962
+ cols << scope_col.to_s if scope_col
963
+ raw.each_key do |key|
964
+ name = key.to_s
965
+ cols << name if name.end_with?("_id")
966
+ end
967
+ cols.uniq
968
+ end
969
+
970
+ def destroy_context_attrs(model, record)
971
+ raw = record.attributes
972
+ selected = {}
973
+ context_columns_for(model, raw).each { |col| selected[col] = raw[col] if raw.key?(col) }
974
+ compact_attrs(selected)
975
+ end
976
+
977
+ def apply_results_with_counts(results)
978
+ resolved = 0
979
+ reconciled = false
262
980
  Array(results).each do |result|
263
981
  result = result.deep_stringify_keys
264
982
  mutation = OutboxMutation.find_by(id: result["mutation_id"])
265
983
  next unless mutation
266
984
 
267
- applying_remote do
268
- case result["status"]
269
- when "applied"
270
- # `skipped` is the server saying it threw this write away to
271
- # last-write-wins. It is resolved (nothing will retry it) but it
272
- # never landed, so marking the record synced would badge a
273
- # discarded write as delivered — the record does not hold what the
274
- # server holds. Reconcile to the winner, which rides along with the
275
- # result; the same value also arrives over the change stream, which
276
- # is what makes doing nothing here look fine until the stream is
277
- # behind.
278
- if result["skipped"]
279
- reconcile_to_server_state(mutation, result)
280
- else
281
- mark_synced(mutation, result["version"])
985
+ notice = nil
986
+ OutboxMutation.transaction do
987
+ SyncMetadata.delete("#{RETRY_PREFIX}#{mutation.id}")
988
+ if mutation.mutator?
989
+ changed_visible = applying_remote do
990
+ HLC.receive(result["hlc"]) if HLC.valid?(result["hlc"])
991
+ moved =
992
+ case result["status"]
993
+ when "applied"
994
+ reconcile_applied_mutator(mutation, result)
995
+ when "rejected"
996
+ notice = quarantine_mutation(
997
+ mutation,
998
+ kind: "rejected",
999
+ reason: result["reason"].to_s.presence || "Rejected by server",
1000
+ result: result
1001
+ )
1002
+ reconcile_rejected_mutator(mutation, result)
1003
+ else
1004
+ false
1005
+ end
1006
+ mutation.destroy!
1007
+ moved
1008
+ end
1009
+ reconciled = true if changed_visible
1010
+ else
1011
+ if result["status"] == "applied" && result["skipped"]
1012
+ notice = quarantine_mutation(
1013
+ mutation,
1014
+ kind: "conflict",
1015
+ reason: result["reason"].to_s.presence || "Overwritten by a newer server change",
1016
+ result: result
1017
+ )
1018
+ elsif result["status"] == "rejected"
1019
+ notice = quarantine_mutation(
1020
+ mutation,
1021
+ kind: "rejected",
1022
+ reason: result["reason"].to_s.presence || "Rejected by server",
1023
+ result: result
1024
+ )
282
1025
  end
283
- when "rejected"
284
- reconcile_rejection(mutation, result)
1026
+ changed_visible = applying_remote do
1027
+ Rebaser.reconcile_mutation_result(mutation, result, record_delta: true)
1028
+ end
1029
+ reconciled = true if changed_visible
285
1030
  end
286
- mutation.destroy!
287
1031
  end
1032
+ announce_notice(notice) if notice
1033
+ resolved += 1
288
1034
  end
289
- nil
1035
+ [resolved, reconciled]
290
1036
  end
291
1037
 
292
- # Apply one remote change event (last-write-wins). Returns whether it
293
- # actually changed anything here — see upsert_from_server.
294
- def apply_change(event)
295
- event = event.deep_stringify_keys
296
- model = InstantRecord.synced_model(event["type"])
297
- return false unless model
1038
+ def apply_bootstrap_body(body)
1039
+ observe_server_time(body["server_time"])
1040
+ records = Array(body["records"])
1041
+ records.each { |record| apply_record(record) }
298
1042
 
299
- applying_remote do
300
- if event["operation"] == "destroy"
301
- !!model.find_by(id: event["id"])&.destroy!
1043
+ # Cursor written last: a crash mid-apply leaves it nil, so the next
1044
+ # tick re-bootstraps; upserts make the retry idempotent. A failure
1045
+ # never falls through to a cursor-0 poll of the full change log.
1046
+ SyncMetadata.set("identity", body["identity"]) if body["identity"]
1047
+ if body["fill"].is_a?(Array) && body["fill"].any?
1048
+ SyncMetadata.set("history_fill_targets", JSON.generate(body["fill"]))
1049
+ end
1050
+ replay = SyncMetadata.get("replay_from")
1051
+ if replay.nil? || replay.to_i > body["cursor"].to_i
1052
+ self.cursor = body["cursor"]
1053
+ else
1054
+ self.cursor = replay.to_i
1055
+ end
1056
+ SyncMetadata.all.each { |entry| entry.destroy if entry.key == "replay_from" } unless replay.nil?
1057
+ unlisted_changes
1058
+ records.size
1059
+ end
1060
+
1061
+ def clear_adaptive_batch_limit
1062
+ SyncMetadata.delete(DRAIN_BATCH_LIMIT_KEY)
1063
+ end
1064
+
1065
+ def handle_drain_failure(sent_ids, status:, error:)
1066
+ return { quarantined: 0, reconciled: false, bisected: false } unless status.is_a?(Integer) && status >= 500 && status < 600
1067
+
1068
+ live_mutations = sent_ids.filter_map { |id| OutboxMutation.find_by(id: id) }
1069
+ return { quarantined: 0, reconciled: false, bisected: false } if live_mutations.empty?
1070
+
1071
+ if live_mutations.size > 1
1072
+ next_limit = [live_mutations.size / 2, 1].max
1073
+ SyncMetadata.set(DRAIN_BATCH_LIMIT_KEY, next_limit)
1074
+ return { quarantined: 0, reconciled: false, bisected: true }
1075
+ end
1076
+
1077
+ mutation = live_mutations.first
1078
+ retry_key = "#{RETRY_PREFIX}#{mutation.id}"
1079
+ attempts = SyncMetadata.get(retry_key).to_i + 1
1080
+ threshold = [InstantRecord.config.max_server_error_retries.to_i, 1].max
1081
+
1082
+ if attempts >= threshold
1083
+ reconciled = isolate_poison_pill(mutation, status: status, error: error, attempts: attempts)
1084
+ SyncMetadata.delete(retry_key)
1085
+ clear_adaptive_batch_limit
1086
+ { quarantined: 1, reconciled: reconciled, bisected: false }
1087
+ else
1088
+ SyncMetadata.set(retry_key, attempts)
1089
+ { quarantined: 0, reconciled: false, bisected: false }
1090
+ end
1091
+ end
1092
+
1093
+ def isolate_poison_pill(mutation, status:, error:, attempts:)
1094
+ # Interpolated, not `error.to_s`: the browser's compiler writes C that
1095
+ # does not build for `to_s` on a String among keyword arguments.
1096
+ reason = "#{error}"
1097
+ payload = {
1098
+ "mutation_id" => mutation.id,
1099
+ "record_type" => mutation.record_type,
1100
+ "record_id" => mutation.record_id,
1101
+ "operation" => mutation.operation,
1102
+ "changes" => mutation.changes_payload,
1103
+ "base_version" => mutation.base_version,
1104
+ "status" => status,
1105
+ "error" => reason,
1106
+ "attempts" => attempts,
1107
+ "quarantined_at" => Time.now.utc.iso8601(InstantRecord::TIME_PRECISION)
1108
+ }
1109
+ SyncMetadata.set("#{QUARANTINE_PREFIX}#{mutation.id}", JSON.generate(payload))
1110
+ changed_visible = applying_remote do
1111
+ if mutation.mutator?
1112
+ moved = reconcile_rejected_mutator(mutation, {})
1113
+ mutation.destroy!
1114
+ moved
302
1115
  else
303
- upsert_from_server(model, event["attributes"], event["version"])
1116
+ Rebaser.reconcile_quarantined_mutation(mutation, record_delta: true)
304
1117
  end
305
1118
  end
1119
+ instrument("poison_pill",
1120
+ mutation_id: mutation.id,
1121
+ record_type: mutation.record_type,
1122
+ record_id: mutation.record_id,
1123
+ operation: mutation.operation,
1124
+ status: status,
1125
+ attempts: attempts,
1126
+ error: reason)
1127
+ changed_visible
306
1128
  end
307
1129
 
308
- private
1130
+ def transport_get_json(path)
1131
+ headers = request_headers
1132
+ headers.empty? ? transport.get_json(path) : transport.get_json(path, headers: headers)
1133
+ end
1134
+
1135
+ def transport_post_json(path, payload)
1136
+ headers = request_headers
1137
+ headers.empty? ? transport.post_json(path, payload) : transport.post_json(path, payload, headers: headers)
1138
+ end
1139
+
1140
+ def transport_each_event(path, &block)
1141
+ headers = request_headers
1142
+ headers.empty? ? transport.each_event(path, &block) : transport.each_event(path, headers: headers, &block)
1143
+ end
1144
+
1145
+ def format_partition_header(partition)
1146
+ return nil if partition.nil?
1147
+
1148
+ if partition.is_a?(Hash)
1149
+ partition.each do |key, value|
1150
+ text = value.to_s
1151
+ return "#{key}:#{text}" unless text.empty?
1152
+ end
1153
+ return nil
1154
+ end
1155
+ text = partition.to_s.strip
1156
+ text.empty? ? nil : text
1157
+ end
309
1158
 
310
1159
  # Where the parser drops finished events, drained by consume_stream.
311
1160
  def stream_events
@@ -316,38 +1165,303 @@ module InstantRecord
316
1165
  @stream_parser ||= Transport::SseParser.new { |event| stream_events << event }
317
1166
  end
318
1167
 
319
- # Contiguity low-water marks, one per (model, partition), held in
320
- # VM-session memory only. Row count alone cannot prove a local page has
321
- # no holes (live updates re-create evicted rows as strays); the mark
322
- # tracks the oldest boundary of contiguously fetched history plus the
323
- # server's last has_more answer.
324
- def history_marks
325
- @history_marks ||= {}
1168
+ # Durable contiguity low-water marks, one per (model, partition), stored
1169
+ # in SyncMetadata so CRuby, WASM, and Native share one SQLite-backed
1170
+ # ledger. Row count alone cannot prove a local page has no holes (live
1171
+ # updates re-create evicted rows as strays); each mark tracks the oldest
1172
+ # boundary of contiguously fetched history plus the server's last
1173
+ # has_more answer.
1174
+ def history_mark_key(model, partition)
1175
+ partition.nil? ? "#{HISTORY_WINDOW_PREFIX}#{model.name}" : "#{HISTORY_WINDOW_PREFIX}#{model.name}/#{partition}"
326
1176
  end
327
1177
 
328
1178
  def history_mark(model, partition)
329
- history_marks[[model.name, partition]]
1179
+ raw = SyncMetadata.get(history_mark_key(model, partition))
1180
+ return nil if raw.nil? || raw.empty?
1181
+
1182
+ data = JSON.parse(raw)
1183
+ return nil unless data.is_a?(Hash) && (data["has_more"] == true || data["has_more"] == false)
1184
+
1185
+ oldest_at = data["oldest_at"]
1186
+ oldest_id = data["oldest_id"]
1187
+ {
1188
+ oldest_at: oldest_at ? parse_time(oldest_at.to_s) : nil,
1189
+ oldest_id: oldest_id.nil? ? nil : oldest_id.to_s,
1190
+ has_more: data["has_more"]
1191
+ }
1192
+ rescue JSON::ParserError, ArgumentError
1193
+ nil
1194
+ end
1195
+
1196
+ def write_history_mark(model, partition, mark)
1197
+ payload = {
1198
+ "oldest_at" => mark[:oldest_at] ? mark[:oldest_at].utc.iso8601(InstantRecord::TIME_PRECISION) : nil,
1199
+ "oldest_id" => mark[:oldest_id],
1200
+ "has_more" => !!mark[:has_more]
1201
+ }
1202
+ SyncMetadata.set(history_mark_key(model, partition), JSON.generate(payload))
1203
+ end
1204
+
1205
+ def apply_history_page(model, partition, records, has_more:)
1206
+ SyncMetadata.transaction do
1207
+ records.each { |record| apply_record(record) }
1208
+ extend_history_mark(model, partition, records, has_more: has_more)
1209
+ end
1210
+ { ok: true, applied: records.size, has_more: has_more }
330
1211
  end
331
1212
 
332
1213
  def extend_history_mark(model, partition, records, has_more:)
333
- key = [model.name, partition]
334
- oldest = records.map { |r| [Time.parse(r.dig("attributes", "created_at").to_s), r["id"].to_s] }.min
335
- mark = history_marks[key] ||= { oldest_at: nil, oldest_id: nil }
336
- mark[:has_more] = has_more
337
- return unless oldest
338
- return if mark[:oldest_at] && ([mark[:oldest_at], mark[:oldest_id]] <=> oldest) <= 0
1214
+ oldest = oldest_record_boundary(model, records)
1215
+ mark = history_mark(model, partition)
1216
+
1217
+ if mark.nil?
1218
+ write_history_mark(model, partition, {
1219
+ oldest_at: oldest ? oldest[0] : nil,
1220
+ oldest_id: oldest ? oldest[1] : nil,
1221
+ has_more: has_more
1222
+ })
1223
+ return
1224
+ end
1225
+
1226
+ if oldest && (mark[:oldest_at].nil? || compare_boundary(oldest, [mark[:oldest_at], mark[:oldest_id]]) < 0)
1227
+ mark[:oldest_at] = oldest[0]
1228
+ mark[:oldest_id] = oldest[1]
1229
+ mark[:has_more] = has_more
1230
+ write_history_mark(model, partition, mark)
1231
+ elsif !has_more && mark[:has_more]
1232
+ mark[:has_more] = false
1233
+ write_history_mark(model, partition, mark)
1234
+ end
1235
+ end
1236
+
1237
+ def handle_windowed_history(query, response)
1238
+ if response.empty?
1239
+ return local_history_page(
1240
+ query[:model], query[:window], query[:partition],
1241
+ query[:before_at], query[:before_id], query[:limit]
1242
+ ) || { ok: false, applied: 0, has_more: false }
1243
+ end
1244
+
1245
+ page = JSON.parse(response)
1246
+ observe_server_time(page["server_time"])
1247
+ apply_history_page(
1248
+ query[:model], query[:partition],
1249
+ Array(page["records"]),
1250
+ has_more: page["has_more"] == true
1251
+ )
1252
+ end
1253
+
1254
+ def handle_opaque_history(key, response)
1255
+ meta_key = HISTORY_KEY_PREFIX + key
1256
+ if response.empty?
1257
+ mark = SyncMetadata.get(meta_key)
1258
+ return { ok: !mark.nil?, applied: 0, has_more: mark == "more" }
1259
+ end
1260
+
1261
+ page = JSON.parse(response)
1262
+ observe_server_time(page["server_time"])
1263
+ records = Array(page["records"])
1264
+ more = page["has_more"] == true
1265
+ SyncMetadata.transaction do
1266
+ records.each { |record| apply_record(record) }
1267
+ SyncMetadata.set(meta_key, more ? "more" : "end")
1268
+ end
1269
+ { ok: true, applied: records.size, has_more: more }
1270
+ end
1271
+
1272
+ def oldest_record_boundary(model, records)
1273
+ oldest = nil
1274
+ records.each do |raw|
1275
+ record = raw.is_a?(Hash) ? raw.deep_stringify_keys : nil
1276
+ next unless record
1277
+ next if record["type"] && record["type"] != model.name
339
1278
 
340
- mark[:oldest_at], mark[:oldest_id] = oldest
1279
+ attrs = record["attributes"]
1280
+ next unless attrs.is_a?(Hash) && attrs["created_at"]
1281
+
1282
+ id = record["id"] || attrs["id"]
1283
+ next if id.nil?
1284
+
1285
+ candidate = [parse_time(attrs["created_at"].to_s), id.to_s]
1286
+ oldest = candidate if oldest.nil? || compare_boundary(candidate, oldest) < 0
1287
+ end
1288
+ oldest
341
1289
  end
342
1290
 
343
- # A page is fully local when the beginning of history was already
344
- # reached, or when `limit` rows older than `before` exist locally within
345
- # the contiguous region above the mark.
346
- def page_local?(mark, window, partition, before_at, before_id, limit)
347
- return true if mark[:has_more] == false
1291
+ # Serve a page from SQLite when the durable mark proves contiguity: either
1292
+ # the beginning of history was already reached (has_more == false), or
1293
+ # `limit` local rows below `before` sit at or above the low-water mark.
1294
+ def local_history_page(model, window, partition, before_at, before_id, limit)
1295
+ mark = history_mark(model, partition)
1296
+ return nil unless mark
348
1297
 
1298
+ if mark[:has_more] == false
1299
+ # has_more from the served page, not the partition-wide mark: rows
1300
+ # remain below this page when the local probe overflows `limit`.
1301
+ # Echoing the mark alone reports "beginning reached" for any
1302
+ # mid-history page after the true beginning was loaded.
1303
+ rows = local_page(window, partition, before_at, before_id, limit + 1)
1304
+ return { ok: true, applied: 0, has_more: rows.size > limit }
1305
+ end
1306
+
1307
+ return nil if mark[:oldest_at].nil?
1308
+
1309
+ boundary = [mark[:oldest_at], mark[:oldest_id]]
349
1310
  rows = local_page(window, partition, before_at, before_id, limit)
350
- rows.size >= limit && rows.all? { |at, id| ([at, id] <=> [mark[:oldest_at], mark[:oldest_id]]) >= 0 }
1311
+ return nil unless rows.size >= limit && rows.all? { |row| compare_boundary(row, boundary) >= 0 }
1312
+
1313
+ { ok: true, applied: 0, has_more: true }
1314
+ end
1315
+
1316
+ def evict_model_window(model, window)
1317
+ evicted = false
1318
+ SyncMetadata.transaction do
1319
+ scope = window.beyond_window(model.where.not(sync_state: "pending"))
1320
+ if window.partition_by
1321
+ affected = scope.pluck(window.partition_by).uniq
1322
+ if affected.any? && scope.delete_all.positive?
1323
+ evicted = true
1324
+ invalidate_history_marks(model, partitions: affected)
1325
+ end
1326
+ elsif scope.delete_all.positive?
1327
+ evicted = true
1328
+ invalidate_history_marks(model)
1329
+ end
1330
+ end
1331
+ evicted
1332
+ end
1333
+
1334
+ def invalidate_history_marks(model, partitions: nil)
1335
+ partition_set = partitions ? partitions.map(&:to_s) : nil
1336
+ window_prefix = "#{HISTORY_WINDOW_PREFIX}#{model.name}"
1337
+
1338
+ SyncMetadata.all.each do |entry|
1339
+ key = entry.key
1340
+ next unless key.start_with?(HISTORY_KEY_PREFIX)
1341
+
1342
+ if key == window_prefix
1343
+ entry.destroy if partition_set.nil?
1344
+ elsif key.start_with?("#{window_prefix}/")
1345
+ partition = key.delete_prefix("#{window_prefix}/")
1346
+ entry.destroy if partition_set.nil? || partition_set.include?(partition)
1347
+ elsif legacy_model_history_key?(key, model.name, partition_set)
1348
+ entry.destroy
1349
+ end
1350
+ end
1351
+ end
1352
+
1353
+ def legacy_model_history_key?(key, model_name, partition_set)
1354
+ raw = key.delete_prefix(HISTORY_KEY_PREFIX)
1355
+ return false unless raw.include?("=")
1356
+
1357
+ params = decode_query_params(raw)
1358
+ return false unless params && params["type"] == model_name
1359
+ return true if partition_set.nil?
1360
+
1361
+ partition = params["partition"]
1362
+ partition.nil? || partition_set.include?(partition)
1363
+ end
1364
+
1365
+ def parse_windowed_history_key(key)
1366
+ return nil unless key.include?("=")
1367
+
1368
+ params = decode_query_params(key)
1369
+ return nil unless params
1370
+ return nil if params["search"] || params["thread"]
1371
+
1372
+ type = params["type"]
1373
+ return nil if type.nil? || type.empty?
1374
+
1375
+ model = InstantRecord.synced_model(type)
1376
+ window = model&.instant_record_sync_window
1377
+ return nil unless window
1378
+
1379
+ before_created_at = params["before_created_at"]
1380
+ before_id = params["before_id"]
1381
+ return nil if before_created_at.nil? || before_created_at.empty? || before_id.nil? || before_id.empty?
1382
+
1383
+ partition = params["partition"]
1384
+ return nil if window.partition_by && (partition.nil? || partition.empty?)
1385
+
1386
+ raw_limit = params["limit"].to_i
1387
+ {
1388
+ model: model,
1389
+ window: window,
1390
+ partition: window.partition_by ? partition.to_s : nil,
1391
+ before_at: parse_time(before_created_at),
1392
+ before_id: before_id.to_s,
1393
+ limit: raw_limit.positive? ? raw_limit : window.limit
1394
+ }
1395
+ rescue ArgumentError
1396
+ nil
1397
+ end
1398
+
1399
+ # Pure-Ruby application/x-www-form-urlencoded parser so WASM and Native
1400
+ # builds do not pull in Ruby's URI package on the WasmBridge.history path.
1401
+ def decode_query_params(raw)
1402
+ params = {}
1403
+ raw.split("&").each do |pair|
1404
+ next if pair.empty?
1405
+
1406
+ eq = pair.index("=")
1407
+ return nil unless eq
1408
+
1409
+ key = decode_query_component(pair[0...eq])
1410
+ val = decode_query_component(pair[(eq + 1)..] || "")
1411
+ params[key] = val
1412
+ end
1413
+ params
1414
+ end
1415
+
1416
+ def decode_query_component(str)
1417
+ text = str.tr("+", " ")
1418
+ return text unless text.include?("%")
1419
+
1420
+ bytes = text.b
1421
+ out = +"".b
1422
+ i = 0
1423
+ len = bytes.bytesize
1424
+ while i < len
1425
+ byte = bytes.getbyte(i)
1426
+ if byte == 37 && i + 2 < len
1427
+ hex = bytes.byteslice(i + 1, 2)
1428
+ if hex.match?(/\A[0-9A-Fa-f]{2}\z/)
1429
+ out << hex.to_i(16)
1430
+ i += 3
1431
+ next
1432
+ end
1433
+ end
1434
+ out << byte
1435
+ i += 1
1436
+ end
1437
+ out.force_encoding(Encoding::UTF_8)
1438
+ end
1439
+
1440
+ # Returns -1, 0, or 1 (never nil) so Spinel AOT can compare directly with 0.
1441
+ def compare_boundary(a, b)
1442
+ return -1 if a[0] < b[0]
1443
+ return 1 if a[0] > b[0]
1444
+ return -1 if a[1] < b[1]
1445
+ return 1 if a[1] > b[1]
1446
+
1447
+ 0
1448
+ end
1449
+
1450
+ # Normalize Ruby Time, ActiveSupport::TimeWithZone, ISO 8601 strings, and
1451
+ # bare SQLite UTC datetime strings ("YYYY-MM-DD HH:MM:SS.ffffff") to UTC
1452
+ # so boundary comparisons never drift on non-UTC host machines.
1453
+ def parse_time(value)
1454
+ return value.utc if value.is_a?(Time)
1455
+ return value.to_time.utc if !value.is_a?(String) && value.respond_to?(:to_time)
1456
+
1457
+ text = value.to_s.strip
1458
+ raise ArgumentError, "blank timestamp" if text.empty?
1459
+
1460
+ if text.match?(/(?:Z|[+-]\d{2}:?\d{2}|UTC)\z/i)
1461
+ Time.parse(text).utc
1462
+ else
1463
+ Time.parse("#{text} UTC").utc
1464
+ end
351
1465
  end
352
1466
 
353
1467
  # Keyset page below (before_at, before_id), newest first, as
@@ -357,7 +1471,7 @@ module InstantRecord
357
1471
  .keyset_below(at: before_at, id: before_id, partition: partition)
358
1472
  .limit(limit)
359
1473
  .pluck(:created_at, window.model.primary_key)
360
- .map { |at, id| [at.to_time, id.to_s] }
1474
+ .map { |at, id| [parse_time(at), id.to_s] }
361
1475
  end
362
1476
 
363
1477
  def history_path(model, partition, before_at, before_id, limit)
@@ -366,81 +1480,265 @@ module InstantRecord
366
1480
  "/records?#{URI.encode_www_form(params)}"
367
1481
  end
368
1482
 
369
- def mark_synced(mutation, version)
370
- model = InstantRecord.synced_model(mutation.record_type)
371
- record = model&.find_by(id: mutation.record_id)
372
- return unless record
1483
+ def drain_outbox
1484
+ if InstantRecord.branched?
1485
+ @planned_drain_ids = nil
1486
+ return [false, false]
1487
+ end
1488
+
1489
+ planned_ids = @planned_drain_ids
1490
+ @planned_drain_ids = nil
1491
+ first_batch = planned_ids.nil? ? drain_batch : planned_mutations(planned_ids)
1492
+ return [false, false] if first_batch.empty?
1493
+
1494
+ instrument("drain") do |event|
1495
+ total_posted = 0
1496
+ total_rejected = 0
1497
+ reasons = []
1498
+ batches = 0
1499
+ quarantined = 0
1500
+ did_work = false
1501
+ reconciled = false
1502
+
1503
+ max_chunks = planned_ids.nil? ? MAX_DRAIN_CHUNKS_PER_PASS : 1
1504
+ max_chunks.times do |chunk_index|
1505
+ mutations = chunk_index == 0 ? first_batch : drain_batch
1506
+ break if mutations.empty?
1507
+
1508
+ begin
1509
+ body = transport_post_json("/mutations", mutations_payload(mutations))
1510
+ observe_server_time(body["server_time"])
1511
+ results = Array(body["results"]).map { |r| r.deep_stringify_keys }
1512
+ resolved, batch_reconciled = apply_results_with_counts(results)
1513
+
1514
+ batches += 1
1515
+ total_posted += mutations.size
1516
+ total_rejected += results.count { |r| r["status"] == "rejected" }
1517
+ results.each do |r|
1518
+ reason = r["reason"]
1519
+ reasons << reason if reason && !reasons.include?(reason)
1520
+ end
1521
+ did_work = true
1522
+ reconciled = true if batch_reconciled
1523
+ clear_adaptive_batch_limit if pending_count == 0
1524
+ break if resolved == 0
1525
+ rescue Transport::Error => e
1526
+ outcome = handle_drain_failure(mutations.map { |m| m[:id] }, status: e.status, error: e.message)
1527
+ if outcome[:quarantined].positive?
1528
+ quarantined += outcome[:quarantined]
1529
+ did_work = true
1530
+ reconciled = true if outcome[:reconciled]
1531
+ next
1532
+ else
1533
+ log_failure("drain", e)
1534
+ break
1535
+ end
1536
+ end
1537
+ end
1538
+
1539
+ event[:posted] = total_posted
1540
+ event[:rejected] = total_rejected
1541
+ event[:reasons] = reasons.first(3)
1542
+ event[:batches] = batches
1543
+ event[:quarantined] = quarantined
1544
+ [did_work, reconciled]
1545
+ end
1546
+ end
373
1547
 
374
- record.update_columns(sync_state: "synced", server_version: version || record.server_version)
1548
+ def matured_outbox_rows(now)
1549
+ return OutboxMutation.matured(now).ordered.to_a unless OutboxMutation.held(now).exists?
1550
+
1551
+ blocked = {}
1552
+ ready = []
1553
+ OutboxMutation.ordered.each do |mutation|
1554
+ key = "#{mutation.record_type}:#{mutation.record_id}"
1555
+ if mutation.held?(now)
1556
+ blocked[key] = true
1557
+ elsif !blocked[key]
1558
+ ready << mutation
1559
+ end
1560
+ end
1561
+ ready
375
1562
  end
376
1563
 
377
- def reconcile_rejection(mutation, result)
378
- return if reconcile_to_server_state(mutation, result)
1564
+ def planned_mutations(ids)
1565
+ return [] if ids.empty?
379
1566
 
380
- # The server never accepted this record (rejected create): remove it.
381
- InstantRecord.synced_model(mutation.record_type)&.find_by(id: mutation.record_id)&.destroy!
1567
+ by_id = {}
1568
+ OutboxMutation.where(id: ids).each { |mutation| by_id[mutation.id] = mutation }
1569
+ ids.filter_map { |id| by_id[id]&.as_mutation }
382
1570
  end
383
1571
 
384
- # Roll the local record onto the server's own copy of the row, when the
385
- # result carries one. Returns whether it did — the caller distinguishes
386
- # "the server has no such row" from "the server has this row".
387
- #
388
- # Authoritative: the server told us what it holds in answer to a write of
389
- # ours it would not take, so its row wins here regardless of timestamps.
390
- def reconcile_to_server_state(mutation, result)
391
- model = InstantRecord.synced_model(mutation.record_type)
392
- return false unless model && result["server_attributes"].present?
1572
+ def restore_record(model, mutation, earlier_pending:)
1573
+ snapshot = mutation.rollback_payload
1574
+ attrs = snapshot.slice(*model.column_names)
1575
+ existing = model.find_by(id: mutation.record_id)
393
1576
 
394
- upsert_from_server(model, result["server_attributes"], result["version"], authoritative: true)
395
- true
1577
+ # A remote destroy (or rejected earlier create) already removed this row;
1578
+ # undoing an update must not resurrect it.
1579
+ return if mutation.operation == "update" && existing.nil?
1580
+
1581
+ # Rebaser keeps sync_state == "pending" while this held mutation is
1582
+ # still in the outbox, so a persisted row at sync_state == "synced" means
1583
+ # a newer remote change (or server reconciliation) already replaced it.
1584
+ return if existing && existing.sync_state == "synced"
1585
+
1586
+ record = existing || model.new
1587
+ current_version = existing ? existing.server_version.to_i : 0
1588
+
1589
+ record.assign_attributes(attrs.except("id"))
1590
+ record.id = mutation.record_id
1591
+
1592
+ if earlier_pending
1593
+ record.sync_state = "pending"
1594
+ elsif attrs["sync_state"] == "pending"
1595
+ record.sync_state = "synced"
1596
+ record.server_version = current_version if current_version > record.server_version.to_i
1597
+ end
1598
+
1599
+ if record.respond_to?(:record_timestamps=)
1600
+ previous = record.record_timestamps
1601
+ record.record_timestamps = false
1602
+ begin
1603
+ record.save!(validate: false)
1604
+ ensure
1605
+ record.record_timestamps = previous
1606
+ end
1607
+ else
1608
+ record.save!(validate: false)
1609
+ end
396
1610
  end
1611
+ def reconcile_applied_mutator(mutation, result)
1612
+ seen = {}
1613
+ changed = false
1614
+ Array(result["records"]).each do |rec|
1615
+ rec = rec.deep_stringify_keys
1616
+ model = InstantRecord.synced_model(rec["type"])
1617
+ next unless model
1618
+
1619
+ seen["#{rec["type"]}:#{rec["id"]}"] = true
1620
+ moved =
1621
+ if rec["operation"] == "destroy"
1622
+ record = model.find_by(id: rec["id"])
1623
+ if record
1624
+ destroy_attrs = destroy_context_attrs(model, record)
1625
+ record.destroy!
1626
+ note_change(rec["type"], rec["id"], op: "destroy", changed_columns: [], attrs: destroy_attrs)
1627
+ true
1628
+ else
1629
+ false
1630
+ end
1631
+ else
1632
+ upsert_from_server(model, rec["attributes"], rec["version"], authoritative: true)
1633
+ end
1634
+ changed = true if moved
1635
+ end
397
1636
 
1637
+ mutation.touched_records.each do |entry|
1638
+ key = "#{entry["type"]}:#{entry["id"]}"
1639
+ next if seen[key]
1640
+
1641
+ model = InstantRecord.synced_model(entry["type"])
1642
+ record = model&.find_by(id: entry["id"])
1643
+ record.update_columns(sync_state: "synced") if record
1644
+ end
1645
+ changed
1646
+ end
1647
+
1648
+ def reconcile_rejected_mutator(mutation, result)
1649
+ reconciled = {}
1650
+ changed = false
1651
+ Array(result["records"]).each do |rec|
1652
+ rec = rec.deep_stringify_keys
1653
+ model = InstantRecord.synced_model(rec["type"])
1654
+ next unless model && rec["attributes"].present?
1655
+
1656
+ if upsert_from_server(model, rec["attributes"], rec["version"], authoritative: true)
1657
+ changed = true
1658
+ end
1659
+ reconciled["#{rec["type"]}:#{rec["id"]}"] = true
1660
+ end
1661
+
1662
+ mutation.touched_records.each do |entry|
1663
+ key = "#{entry["type"]}:#{entry["id"]}"
1664
+ next if reconciled[key]
1665
+
1666
+ model = InstantRecord.synced_model(entry["type"])
1667
+ next unless model
1668
+
1669
+ moved =
1670
+ if entry["op"] == "create"
1671
+ record = model.find_by(id: entry["id"])
1672
+ if record
1673
+ destroy_attrs = destroy_context_attrs(model, record)
1674
+ record.destroy!
1675
+ note_change(entry["type"], entry["id"], op: "destroy", changed_columns: [], attrs: destroy_attrs)
1676
+ true
1677
+ else
1678
+ false
1679
+ end
1680
+ elsif entry["before"].is_a?(Hash)
1681
+ restore_local_snapshot(model, entry["before"])
1682
+ else
1683
+ false
1684
+ end
1685
+ changed = true if moved
1686
+ end
1687
+ changed
1688
+ end
1689
+
1690
+ def restore_local_snapshot(model, attributes)
1691
+ sliced = attributes.slice(*model.column_names)
1692
+ return false unless sliced["id"]
1693
+
1694
+ record = model.find_or_initialize_by(id: sliced["id"])
1695
+ record.assign_attributes(sliced.except("id"))
1696
+ was_new = !record.persisted?
1697
+ changed_cols = record.changed.map(&:to_s)
1698
+ record.save!(validate: false)
1699
+ if sliced["updated_at"]
1700
+ record.update_columns(updated_at: Time.parse(sliced["updated_at"].to_s))
1701
+ changed_cols << "updated_at" unless changed_cols.include?("updated_at")
1702
+ end
1703
+ note_record_change(record, was_new ? "create" : "update", changed_columns: changed_cols)
1704
+ true
1705
+ end
398
1706
  # Returns whether the row actually moved. Every accepted write comes back
399
1707
  # down the change stream, so a client is constantly re-applying its own
400
1708
  # rows; treating those as changes would announce them, and an announcement
401
1709
  # reloads any page without an in-place refresh.
402
1710
  #
403
- # Client-side last-write-wins, with the tie-break stated on purpose: a
404
- # remote value must be strictly NEWER to replace a local one, so equal
405
- # stamps leave the row alone. Equal stamps are the ordinary case, not the
406
- # exotic one — every write we make comes back with the timestamp we sent —
407
- # and applying those echoes would re-save the row, announce a change to
408
- # every tab, and fire the host app's after_save callbacks for a value that
409
- # never moved. Until both paths carried microseconds, rounding hid this by
410
- # making an echo look older than its own row; the rule has to be explicit
411
- # instead of an artifact of truncation.
1711
+ # Client-side convergence compares server-anchored string-encoded HLCs
1712
+ # (falling back to microsecond updated_at only for legacy events without
1713
+ # an HLC): a remote value must be strictly NEWER to replace a local one,
1714
+ # so equal stamps (such as echoes of our own writes) leave the row alone.
1715
+ # Because HLC physical time is anchored to authoritative server UTC and
1716
+ # extreme forward skew is clamped on the server, a client whose wall clock
1717
+ # runs ahead no longer wins writes it should lose.
412
1718
  #
413
- # The two sides break ties in opposite directions deliberately:
414
- # MutationApplier#stale? is strict too, so the server ACCEPTS an
415
- # equal-stamped client mutation. A tie is therefore settled once, on the
416
- # server, and never has to be settled again here. (Both sides still compare
417
- # two machines' wall clocks with no logical clock. Microsecond stamps make
418
- # a coincidental tie far less likely than millisecond ones did, so the
419
- # tie-break matters less than it used to — but a client whose clock runs
420
- # ahead still wins writes it should lose, and that is unchanged.)
421
- # `authoritative` skips the comparison entirely, for the one case where the
422
- # server's row is the answer no matter what the clocks say: reconciling a
423
- # rejection. A rejected update is the ordinary case here, and the server's
424
- # un-updated row is necessarily OLDER than the optimistic local row that it
425
- # refused — so last-write-wins would drop it, the outbox row would still be
426
- # destroyed, and the record would keep the value the server just refused
427
- # and sit at `pending` forever. Nothing was discarded remotely in that
428
- # case, so the discard seam does not fire either.
429
- def upsert_from_server(model, attributes, version, authoritative: false)
1719
+ # `authoritative` skips the comparison entirely for reconciling rejections,
1720
+ # skipped writes, and 3-way merged rows from the server.
1721
+ def upsert_from_server(model, attributes, version, hlc: nil, authoritative: false, record_delta: true)
430
1722
  return false unless attributes
431
1723
 
1724
+ HLC.receive(hlc) if HLC.valid?(hlc)
1725
+
432
1726
  # Schema skew must not raise here either: a client behind the server is
433
1727
  # sent columns it has not migrated yet. They are the server's to keep;
434
1728
  # this runtime converges on the columns it actually has.
435
1729
  attributes = attributes.slice(*model.column_names)
436
1730
  record = model.find_or_initialize_by(id: attributes["id"])
437
1731
 
1732
+ incoming_hlc = HLC.valid?(hlc) ? hlc : nil
1733
+ local_hlc = record.persisted? ? HLC.row_hlc(model.name, record.id) : nil
438
1734
  incoming_at = attributes["updated_at"] && Time.parse(attributes["updated_at"].to_s)
439
1735
  local_at = record.persisted? ? record.updated_at : nil
1736
+ prior_pending = !authoritative && record.persisted? && record.sync_state == "pending"
1737
+ prior_attributes = prior_pending ? InstantRecord.wire_attributes(record.attributes) : nil
440
1738
 
441
1739
  record.assign_attributes(attributes.except("id", "server_version"))
442
1740
 
443
- if !authoritative && incoming_at && local_at && incoming_at <= local_at
1741
+ if !authoritative && record.persisted? && stale_remote?(incoming_hlc, local_hlc, incoming_at, local_at)
444
1742
  # The remote value lost. This is the last moment it exists in this
445
1743
  # runtime — nothing downstream sees it, which is why models get a seam.
446
1744
  if (record.changed - BOOKKEEPING_COLUMNS).any?
@@ -449,17 +1747,150 @@ module InstantRecord
449
1747
  return false
450
1748
  end
451
1749
 
1750
+ inbound_conflict = prior_pending && (record.changed - BOOKKEEPING_COLUMNS).any? &&
1751
+ OutboxMutation.find_by(record_type: model.name, record_id: record.id).nil?
1752
+
452
1753
  record.server_version = version || attributes["server_version"] || 0
453
1754
  record.sync_state = "synced"
1755
+ HLC.set_row_hlc(model.name, record.id, incoming_hlc, force: authoritative) if incoming_hlc
454
1756
  return false unless record.changed?
455
1757
 
456
- record.save!(validate: false)
457
- true
1758
+ was_new = !record.persisted?
1759
+ changed_cols = record.changed.map(&:to_s)
1760
+ data_changed = was_new || (changed_cols - BOOKKEEPING_COLUMNS).any?
1761
+ quarantined = nil
1762
+ if inbound_conflict && data_changed
1763
+ OutboxMutation.transaction do
1764
+ quarantined = SyncNotice.record!(
1765
+ kind: "conflict",
1766
+ record_type: model.name,
1767
+ record_id: record.id,
1768
+ operation: "update",
1769
+ reason: "Overwritten by a newer server change",
1770
+ attempted_changes: prior_attributes,
1771
+ server_attributes: InstantRecord.wire_attributes(attributes),
1772
+ server_version: record.server_version
1773
+ )
1774
+ record.save!(validate: false)
1775
+ end
1776
+ note_record_change(record, was_new ? "create" : "update", changed_columns: changed_cols) if record_delta
1777
+ announce_notice(quarantined) if quarantined
1778
+ elsif data_changed
1779
+ record.save!(validate: false)
1780
+ note_record_change(record, was_new ? "create" : "update", changed_columns: changed_cols) if record_delta
1781
+ else
1782
+ record.update_columns(sync_state: record.sync_state, server_version: record.server_version)
1783
+ end
1784
+ data_changed
1785
+ end
1786
+
1787
+ def stale_remote?(incoming_hlc, local_hlc, incoming_at, local_at)
1788
+ if incoming_hlc && HLC.valid?(local_hlc)
1789
+ HLC.compare(incoming_hlc, local_hlc) <= 0
1790
+ elsif incoming_hlc && local_at
1791
+ incoming_pt = HLC.physical_time(incoming_hlc)
1792
+ incoming_pt ? incoming_pt <= local_at : false
1793
+ elsif incoming_at && local_at
1794
+ incoming_at <= local_at
1795
+ else
1796
+ false
1797
+ end
1798
+ end
1799
+
1800
+ def quarantine_mutation(mutation, kind:, reason:, result:)
1801
+ return nil if SyncNotice.find_by(mutation_id: mutation.id)
1802
+
1803
+ SyncNotice.record!(
1804
+ mutation_id: mutation.id,
1805
+ kind: kind,
1806
+ record_type: mutation.record_type,
1807
+ record_id: mutation.record_id,
1808
+ operation: mutation.operation,
1809
+ reason: reason,
1810
+ attempted_changes: mutation.changes_payload || {},
1811
+ server_attributes: result["server_attributes"] || {},
1812
+ server_version: result["version"].to_i
1813
+ )
1814
+ end
1815
+
1816
+ def announce_notice(notice)
1817
+ recorded_notices << notice.as_notice
1818
+ instrument("notice",
1819
+ id: notice.id,
1820
+ kind: notice.kind,
1821
+ record_type: notice.record_type,
1822
+ record_id: notice.record_id,
1823
+ operation: notice.operation,
1824
+ reason: notice.reason)
458
1825
  end
459
1826
 
460
1827
  def log_failure(phase, error)
1828
+ instrument("offline", phase: phase, error: error.message)
461
1829
  warn "[instant_record] #{phase} failed (offline?): #{error.message}"
462
1830
  end
1831
+
1832
+ # Every meaningful sync outcome is announced through
1833
+ # ActiveSupport::Notifications — the seam a host app subscribes to for
1834
+ # logging or metrics, and the one the browser runtime bridges to the JS
1835
+ # worker through /host/events. Ruby is what knows: the worker can only say
1836
+ # it made a request; this side knows what the pass actually did.
1837
+ def instrument(name, payload = {}, &block)
1838
+ full_name = "#{name}.instant_record"
1839
+ started = Time.now.to_f
1840
+ raised = nil
1841
+ begin
1842
+ ActiveSupport::Notifications.instrument(full_name, payload, &block)
1843
+ rescue StandardError => e
1844
+ raised = e
1845
+ raise
1846
+ ensure
1847
+ if InstantRecord.browser?
1848
+ duration_ms = (Time.now.to_f - started) * 1000.0
1849
+ record_bridged_event(full_name, payload, duration_ms, raised)
1850
+ end
1851
+ end
1852
+ end
1853
+
1854
+ def record_bridged_event(name, payload, duration_ms, error = nil)
1855
+ clean = normalize_event_payload(payload)
1856
+ clean["exception"] = [error.class.name, error.message.to_s] if error
1857
+ recorded_events.shift if recorded_events.size >= MAX_RECORDED_EVENTS
1858
+ recorded_events << {
1859
+ "name" => name,
1860
+ "payload" => clean,
1861
+ "duration_ms" => duration_ms
1862
+ }
1863
+ notifier.events_emitted(events_notice) if notifier.respond_to?(:events_emitted)
1864
+ nil
1865
+ end
1866
+
1867
+ def normalize_event_payload(payload)
1868
+ result = {}
1869
+ return result unless payload.is_a?(Hash)
1870
+
1871
+ payload.each do |key, value|
1872
+ name = key.to_s
1873
+ next if name == "exception_object"
1874
+
1875
+ result[name] = normalize_event_value(value)
1876
+ end
1877
+ result
1878
+ end
1879
+
1880
+ def normalize_event_value(value)
1881
+ case value
1882
+ when String, Integer, Float, TrueClass, FalseClass, NilClass
1883
+ value
1884
+ when Symbol
1885
+ value.to_s
1886
+ when Array
1887
+ value.map { |item| normalize_event_value(item) }
1888
+ when Hash
1889
+ normalize_event_payload(value)
1890
+ else
1891
+ value.to_s
1892
+ end
1893
+ end
463
1894
  end
464
1895
  end
465
1896
  end