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,30 +1,77 @@
1
+ require "json"
2
+ require "instant_record/outbox_upcaster"
3
+
1
4
  module InstantRecord
2
5
  # Applies one client mutation authoritatively: record write, version bump,
3
6
  # change-log row, and idempotency-ledger row, in one transaction. This is
4
7
  # the server half of the sync protocol; the HTTP layer above it is thin.
8
+ #
9
+ # Conflict resolution uses server-anchored string-encoded HLCs (with extreme
10
+ # forward clock skew clamped to server UTC) and 3-way column-level merging:
11
+ # inspecting Change rows since `base_version` lets disjoint concurrent column
12
+ # edits merge cleanly, while same-column collisions honor declarative
13
+ # `sync_merge :col, :lww | :union | :server_wins` policies.
5
14
  class MutationApplier
6
- def self.apply(mutation)
7
- new(mutation).apply
15
+ # A write the sender may not make. Raised inside the transaction, so
16
+ # whatever the write did is rolled back with it.
17
+ NotPermitted = Class.new(StandardError)
18
+
19
+ # Columns that carry bookkeeping/timestamps rather than user-edited fields.
20
+ NON_DATA_COLUMNS = %w[id server_version sync_state created_at updated_at].freeze
21
+
22
+ # `identity` is the sender (SyncScope.identity). `partition` is the active
23
+ # multi-tenant partition (SyncScope.partition), required by models that
24
+ # declare `sync_partition`.
25
+ def self.apply(mutation, identity = nil, partition = nil)
26
+ new(mutation, identity, partition).apply
8
27
  end
9
28
 
10
- def initialize(mutation)
11
- @mutation = mutation
12
- @changes = (mutation[:changes] || {}).to_h
29
+ def initialize(mutation, identity = nil, partition = nil)
30
+ @mutation = normalize_mutation(mutation)
31
+ @mutation_id = @mutation[:mutation_id] || @mutation[:id]
32
+ @changes = (@mutation[:changes] || {}).to_h
33
+ @identity = identity
34
+ @scope = SyncScope.token(identity)
35
+ @partition = partition
13
36
  end
14
37
 
15
38
  # Replayed mutation ids return their original result without re-applying.
16
39
  def apply
17
- if (existing = AppliedMutation.find_by(mutation_id: @mutation[:id]))
18
- return existing.result_payload.symbolize_keys
19
- end
40
+ return apply_mutator if mutator_intent?
41
+
42
+ @mutation, @changes = OutboxUpcaster.apply_global(@mutation, @changes)
20
43
 
21
44
  model = InstantRecord.synced_model(@mutation[:record_type])
45
+ if model && (part = model.instant_record_sync_partition)
46
+ part_value = part.extract(@partition)
47
+ return { mutation_id: @mutation_id, status: "rejected", reason: "a partition is required" } unless part_value
48
+
49
+ col = part.column
50
+ if @changes.key?(col) && @changes[col].present? && @changes[col].to_s != part_value
51
+ return { mutation_id: @mutation_id, status: "rejected", reason: "record not in active partition" }
52
+ end
53
+ existing_row = model.find_by(id: @mutation[:record_id])
54
+ if existing_row && existing_row[col].to_s != part_value
55
+ return { mutation_id: @mutation_id, status: "rejected", reason: "record not found" }
56
+ end
57
+ end
58
+
59
+ if (existing = AppliedMutation.find_by(mutation_id: @mutation_id))
60
+ return replayed(existing.result_payload.symbolize_keys)
61
+ end
62
+
22
63
  return record_result(status: "rejected", reason: "unknown record type") unless model
23
64
 
24
- result = ActiveRecord::Base.transaction do
65
+ @changes = OutboxUpcaster.apply_for_model(model, @changes, @mutation)
66
+
67
+ # Its own savepoint when a caller holds a transaction open, so a write
68
+ # that is refused after it was made is undone either way.
69
+ result = ActiveRecord::Base.transaction(requires_new: true) do
25
70
  InstantRecord.applying_client_mutation { perform(model) }
26
71
  end
27
72
  record_result(**result)
73
+ rescue NotPermitted
74
+ record_result(status: "rejected", reason: "not permitted", server_attributes: server_attributes_for(model))
28
75
  rescue ActiveRecord::RecordInvalid => e
29
76
  record_result(status: "rejected", reason: e.record.errors.full_messages.to_sentence,
30
77
  server_attributes: server_attributes_for(model))
@@ -38,93 +85,629 @@ module InstantRecord
38
85
  rescue ActiveModel::UnknownAttributeError => e
39
86
  # Schema skew: this client is a migration ahead of this server and sent a
40
87
  # column that does not exist here. Rejecting is the only outcome that
41
- # cannot jam the queue. Raising 500s the entire batch, and because the
42
- # client keeps the row on a transport error it would retry the same
43
- # poisoned mutation forever, blocking every write queued behind it.
44
- # Slicing the unknown column off instead would answer "applied" for a
45
- # write the server only partly stored — silent data loss the client has no
46
- # way to notice. A surfaced rejection loses the same write loudly, rolls
47
- # the local record back to what the server actually holds, and leaves the
48
- # queue draining. Deploy order (server first) remains the real defence.
88
+ # cannot jam the queue.
49
89
  record_result(status: "rejected", reason: e.message,
50
90
  server_attributes: server_attributes_for(model))
51
91
  end
52
92
 
53
93
  private
54
94
 
95
+ def normalize_mutation(mutation)
96
+ hash = mutation.respond_to?(:to_unsafe_h) ? mutation.to_unsafe_h : mutation.to_h
97
+ hash.symbolize_keys
98
+ end
99
+
100
+ def mutator_intent?
101
+ @mutation[:mutator].present? || @mutation[:operation].to_s == "mutator"
102
+ end
103
+
104
+ # Authoritatively replay a custom sync_action inside one transaction with
105
+ # AppliedMutation idempotency, unified auth, commit-guarded ActiveJob
106
+ # enqueueing, and visible post-rollback server records on rejection.
107
+ def apply_mutator
108
+ if (existing = AppliedMutation.find_by(mutation_id: @mutation_id))
109
+ return replayed_mutator(existing.result_payload.symbolize_keys)
110
+ end
111
+
112
+ mutator_name = @mutation[:mutator].to_s
113
+ entry = SyncActions.resolve(mutator_name)
114
+ unless entry && mutator_allowed?(entry[:klass])
115
+ return record_result(status: "rejected", reason: "unknown mutator", records: [])
116
+ end
117
+
118
+ SyncActions.install_active_job_guard!
119
+ frame = SyncActions::ServerFrame.new(
120
+ mutation_id: @mutation_id.to_s,
121
+ identity: @identity,
122
+ scope: @scope,
123
+ partition: @partition,
124
+ enforcing: true
125
+ )
126
+ args = SyncActions.normalize_args(@mutation[:args] || {})
127
+
128
+ ActiveRecord::Base.transaction(requires_new: true) do
129
+ InstantRecord.applying_client_mutation do
130
+ SyncActions.with_server_frame(frame) do
131
+ authorize_action!(entry, args)
132
+ SyncActions.dispatch(mutator_name, args)
133
+ end
134
+ end
135
+ record_applied_mutator!(status: "applied", records: frame.applied_records)
136
+ end
137
+ rescue NotPermitted => e
138
+ reason = (e.message.nil? || e.message == e.class.name) ? "not permitted" : e.message
139
+ record_result(status: "rejected", reason: reason, records: visible_records_for(frame&.touched_refs || []))
140
+ rescue MutationRejected => e
141
+ record_result(status: "rejected", reason: e.message, records: visible_records_for(frame&.touched_refs || []))
142
+ rescue ActiveRecord::RecordInvalid => e
143
+ refs = (frame&.touched_refs || []).dup
144
+ if e.record&.class&.respond_to?(:instant_record_syncable?) && e.record.class.instant_record_syncable? && e.record.id.present?
145
+ refs << [e.record.class.name, e.record.id]
146
+ end
147
+ record_result(status: "rejected", reason: e.record.errors.full_messages.to_sentence,
148
+ records: visible_records_for(refs))
149
+ rescue ActiveRecord::RecordNotFound => e
150
+ refs = (frame&.touched_refs || []).dup
151
+ refs << [e.model, e.id] if e.respond_to?(:model) && e.model.present? && e.respond_to?(:id) && e.id.present?
152
+ record_result(status: "rejected", reason: e.message, records: visible_records_for(refs))
153
+ rescue ActiveRecord::RecordNotUnique
154
+ if (existing = AppliedMutation.find_by(mutation_id: @mutation_id))
155
+ return replayed_mutator(existing.result_payload.symbolize_keys)
156
+ end
157
+
158
+ record_result(status: "rejected", reason: "id already exists", records: visible_records_for(frame&.touched_refs || []))
159
+ rescue ArgumentError, ActiveModel::UnknownAttributeError => e
160
+ record_result(status: "rejected", reason: e.message, records: visible_records_for(frame&.touched_refs || []))
161
+ end
162
+
163
+ # Raises RecordNotUnique on concurrent duplicate mutation_id so the
164
+ # wrapping savepoint rolls back duplicate domain writes and jobs.
165
+ def record_applied_mutator!(**result)
166
+ payload = result.merge(mutation_id: @mutation_id)
167
+ record = AppliedMutation.create!(mutation_id: @mutation_id, result_payload: payload)
168
+ record.result_payload.symbolize_keys
169
+ end
170
+
171
+ def mutator_allowed?(klass)
172
+ return true unless InstantRecord.synced_models.any?
173
+ return true unless klass.respond_to?(:instant_record_syncable?) && klass.instant_record_syncable?
174
+
175
+ !InstantRecord.synced_model(klass.name).nil?
176
+ end
177
+
178
+ def authorize_action!(entry, args)
179
+ authorizer = entry[:klass].instant_record_action_authorizer(entry[:action])
180
+ return unless authorizer
181
+
182
+ permitted =
183
+ if authorizer.arity == 3 || authorizer.arity < -2
184
+ authorizer.call(entry[:action], @identity, args)
185
+ else
186
+ authorizer.call(@identity, args)
187
+ end
188
+ raise NotPermitted unless permitted
189
+ end
190
+
191
+ # Authoritative post-rollback rows visible to the requester, so a rejected
192
+ # mutator never leaks hidden records and gives the client exact server state.
193
+ def visible_records_for(refs)
194
+ seen = {}
195
+ records = []
196
+ refs.each do |type, id|
197
+ next if type.nil? || id.nil?
198
+
199
+ key = "#{type}:#{id}"
200
+ next if seen[key]
201
+
202
+ seen[key] = true
203
+ model = InstantRecord.synced_model(type.to_s)
204
+ next unless model
205
+
206
+ record = SyncScope.visible(model, @identity, partition: @partition).find_by(id: id)
207
+ records << InstantRecord.record_payload(record) if record
208
+ end
209
+ records
210
+ end
211
+
212
+ # Re-filter stored mutator result records through what this requester may
213
+ # see, matching row-level replay privacy guarantees.
214
+ def replayed_mutator(result)
215
+ stored = result[:records]
216
+ return result unless stored.is_a?(Array)
217
+
218
+ filtered = stored.filter_map do |entry|
219
+ rec = entry.stringify_keys
220
+ model = InstantRecord.synced_model(rec["type"])
221
+ next rec unless model && SyncScope.scoped?(model)
222
+
223
+ if rec["operation"] == "destroy"
224
+ nil
225
+ else
226
+ record = SyncScope.visible(model, @identity, partition: @partition).find_by(id: rec["id"])
227
+ next unless record
228
+
229
+ payload = InstantRecord.record_payload(record).deep_stringify_keys
230
+ payload["operation"] = rec["operation"] if rec["operation"]
231
+ payload
232
+ end
233
+ end
234
+
235
+ result.merge(records: filtered)
236
+ end
237
+
55
238
  def perform(model)
239
+ # Partition ownership was verified before replay; stamp the column on
240
+ # create and prevent moving it on update.
241
+ if (part = model.instant_record_sync_partition)
242
+ part_value = part.extract(@partition)
243
+ col = part.column
244
+ if @mutation[:operation] == "create"
245
+ @changes = @changes.merge(col => part_value)
246
+ else
247
+ @changes = @changes.except(col)
248
+ end
249
+ end
250
+
251
+ # A scoped model's rows are the sender's own: the scope column is never
252
+ # taken from the client, and another scope's row is as good as absent.
253
+ if (column = model.instant_record_sync_scope)
254
+ return { status: "rejected", reason: "a scope is required" } unless @scope
255
+ @changes = @changes.except(column)
256
+ @changes[column] = @scope if @mutation[:operation] == "create"
257
+ existing = model.find_by(id: @mutation[:record_id])
258
+ return { status: "rejected", reason: "record not found" } if existing && existing[column] != @scope
259
+ end
260
+
261
+ # Enforce model-declared allowed mutation operations (e.g. append-only models).
262
+ if (allowed_ops = model.instant_record_writable_operations)
263
+ raise NotPermitted unless allowed_ops.include?(@mutation[:operation].to_s)
264
+ end
265
+
266
+ server_now = HLC.wall_now
267
+
56
268
  case @mutation[:operation]
57
269
  when "create"
58
- record = model.new(@changes.merge("id" => @mutation[:record_id]))
270
+ # An id that belongs to a record the sender cannot see is answered as
271
+ # any other create it may not make, before the database can say "id
272
+ # already exists" about a row the client was never shown.
273
+ raise NotPermitted if hidden?(model)
274
+
275
+ applied_hlc = resolve_incoming_hlc(server_now)
276
+ safe_changes = clamp_updated_at(@changes, server_now, applied_hlc)
277
+
278
+ record = model.new(safe_changes.merge("id" => @mutation[:record_id]))
59
279
  record.server_version = 1
60
280
  record.sync_state = "synced"
61
281
  record.save!
62
- log_change(record, "create")
63
- { status: "applied", version: record.server_version }
282
+ permit!(model)
283
+ HLC.receive(applied_hlc, now: server_now, node: HLC::SERVER_NODE)
284
+ log_change(record, "create", hlc: applied_hlc)
285
+ { status: "applied", version: record.server_version, hlc: applied_hlc }
64
286
  when "update"
65
287
  record = model.find_by(id: @mutation[:record_id])
66
- return { status: "rejected", reason: "record not found" } unless record
67
-
68
- if stale?(record)
69
- # Last-write-wins: an older concurrent write is acknowledged (there is
70
- # nothing to retry) but skipped. The row that won travels back with the
71
- # result, because a client told only "applied" badges the write it just
72
- # lost as synced. See Client#apply_results.
73
- { status: "applied", version: record.server_version, skipped: true,
74
- server_attributes: InstantRecord.wire_attributes(record.attributes) }
75
- else
76
- record.assign_attributes(@changes.except("id", "server_version"))
77
- record.server_version += 1
78
- record.sync_state = "synced"
79
- record.save!
80
- log_change(record, "update")
81
- { status: "applied", version: record.server_version }
82
- end
288
+ return { status: "rejected", reason: "record not found" } if record.nil? || hidden?(model)
289
+
290
+ permit!(model)
291
+ perform_update(model, record, server_now)
83
292
  when "destroy"
84
293
  record = model.find_by(id: @mutation[:record_id])
294
+ # A hidden record answers as a missing one does, and is left alone. No
295
+ # change is logged: a logged destroy would remove the record from the
296
+ # browsers of the people who may see it.
297
+ return { status: "applied" } if record && hidden?(model)
298
+
299
+ permit!(model) if record
300
+ applied_hlc = resolve_incoming_hlc(server_now)
85
301
  record&.destroy!
86
- log_destroy(model)
302
+ HLC.receive(applied_hlc, now: server_now, node: HLC::SERVER_NODE)
303
+ log_destroy(model, record, hlc: applied_hlc)
87
304
  { status: "applied" }
88
305
  else
89
306
  { status: "rejected", reason: "unknown operation" }
90
307
  end
91
308
  end
92
309
 
93
- def stale?(record)
94
- incoming = @changes["updated_at"]
95
- incoming.present? && record.updated_at.present? && Time.zone.parse(incoming.to_s) < record.updated_at
310
+ def perform_update(model, record, server_now)
311
+ # Reject schema skew loudly before conflict filtering can mask an unknown column.
312
+ candidate_attrs = @changes.except("id", "server_version")
313
+ unknown = candidate_attrs.keys.reject { |attr| record.respond_to?("#{attr}=") }
314
+ raise ActiveModel::UnknownAttributeError.new(record, unknown.first) if unknown.any?
315
+
316
+ incoming_hlc = resolve_incoming_hlc(server_now)
317
+ record_hlc = record_current_hlc(record)
318
+ base_version = mutation_base_version
319
+ user_columns = candidate_attrs.keys - NON_DATA_COLUMNS
320
+
321
+ # Concurrent edits exist on the server since the client's base_version:
322
+ # run 3-way column-level merging against the Change log.
323
+ if base_version && base_version < record.server_version && user_columns.any?
324
+ return perform_three_way_merge(model, record, user_columns, base_version, incoming_hlc, record_hlc, server_now)
325
+ end
326
+
327
+ # No concurrent version bump (or legacy caller with no base_version /
328
+ # metadata-only touch): compare clamped HLCs.
329
+ if record_hlc.present? && HLC.compare(incoming_hlc, record_hlc) < 0
330
+ return skipped_result(record, record_hlc)
331
+ end
332
+
333
+ safe_changes = clamp_updated_at(candidate_attrs, server_now, incoming_hlc)
334
+ record.assign_attributes(safe_changes)
335
+ record.server_version += 1
336
+ record.sync_state = "synced"
337
+ record.save!
338
+ # Again after the write: a change of owner or audience must leave the
339
+ # record somewhere the sender may still write.
340
+ permit!(model)
341
+ HLC.receive(incoming_hlc, now: server_now, node: HLC::SERVER_NODE)
342
+ log_change(record, "update", hlc: incoming_hlc)
343
+ { status: "applied", version: record.server_version, hlc: incoming_hlc }
96
344
  end
97
345
 
98
- def log_change(record, operation)
99
- Change.create!(
346
+ def perform_three_way_merge(model, record, user_columns, base_version, incoming_hlc, record_hlc, server_now)
347
+ base_attrs, server_touched, has_base = inspect_changes_since(record, base_version, record_hlc)
348
+ live_attrs = InstantRecord.wire_attributes(record.attributes)
349
+ incoming_node = HLC.node(incoming_hlc)
350
+
351
+ winning = {}
352
+ user_columns.each do |col|
353
+ col_info =
354
+ if has_base
355
+ server_touched[col]
356
+ else
357
+ { value: live_attrs[col], hlc: record_hlc, nodes: [HLC.node(record_hlc)].compact }
358
+ end
359
+
360
+ if col_info.nil?
361
+ # Disjoint concurrent edit: server did not touch this column since base_version.
362
+ winning[col] = @changes[col]
363
+ next
364
+ end
365
+
366
+ # Same client node's sequential offline mutations share the same base_version
367
+ # until the first one lands; treat strictly newer writes from the same client
368
+ # node as sequential rather than a concurrent conflict.
369
+ if same_node_sequential?(incoming_node, incoming_hlc, col_info)
370
+ winning[col] = @changes[col]
371
+ next
372
+ end
373
+
374
+ policy = model.instant_record_merge_policy(col)
375
+ case policy
376
+ when :server_wins
377
+ # Server's already-committed value wins on same-column collision.
378
+ when :lww
379
+ if col_info[:hlc].nil? || HLC.compare(incoming_hlc, col_info[:hlc]) >= 0
380
+ winning[col] = @changes[col]
381
+ end
382
+ when :union
383
+ merged_val = merge_union(
384
+ has_base ? base_attrs[col] : nil,
385
+ record.public_send(col),
386
+ @changes[col],
387
+ incoming_wins: col_info[:hlc].nil? || HLC.compare(incoming_hlc, col_info[:hlc]) >= 0
388
+ )
389
+ winning[col] = merged_val if merged_val != record.public_send(col)
390
+ end
391
+ end
392
+
393
+ return skipped_result(record, record_hlc) if winning.empty?
394
+
395
+ applied_hlc = HLC.advance_past(record_hlc, incoming_hlc, now: server_now, node: HLC::SERVER_NODE)
396
+ applied_time = HLC.physical_time(applied_hlc) || server_now
397
+
398
+ record.assign_attributes(winning)
399
+ record.updated_at = [record.updated_at, applied_time].compact.max if record.respond_to?(:updated_at=)
400
+ record.server_version += 1
401
+ record.sync_state = "synced"
402
+ record.save!
403
+ permit!(model)
404
+ log_change(record, "update", hlc: applied_hlc)
405
+
406
+ {
407
+ status: "applied",
408
+ version: record.server_version,
409
+ merged: true,
410
+ hlc: applied_hlc,
411
+ server_attributes: InstantRecord.wire_attributes(record.attributes)
412
+ }
413
+ end
414
+
415
+ # Inspect Change rows since `base_version` to determine the base snapshot
416
+ # and every column modified on the server since that version, along with
417
+ # the HLC and contributing writer nodes for each modified column.
418
+ def inspect_changes_since(record, base_version, record_hlc)
419
+ base_change =
420
+ if base_version.positive?
421
+ Change
422
+ .where(record_type: record.class.name, record_id: record.id, version: base_version)
423
+ .order(:id)
424
+ .last
425
+ end
426
+
427
+ return [{}, {}, false] unless base_change
428
+
429
+ base_attrs = base_change.attributes_payload.is_a?(Hash) ? base_change.attributes_payload : {}
430
+ changes_since = Change
431
+ .where(record_type: record.class.name, record_id: record.id)
432
+ .where("version > ?", base_version)
433
+ .where.not(operation: "destroy")
434
+ .order(:version, :id)
435
+ .to_a
436
+
437
+ hlc_map = HLC.change_hlcs(changes_since.map(&:id))
438
+ server_touched = {}
439
+ prev_attrs = base_attrs
440
+
441
+ changes_since.each do |change|
442
+ curr_attrs = change.attributes_payload.is_a?(Hash) ? change.attributes_payload : {}
443
+ c_hlc = hlc_map[change.id] || HLC.from_time(curr_attrs["updated_at"] || change.created_at, node: HLC::SERVER_NODE)
444
+ c_node = HLC.node(c_hlc)
445
+
446
+ ((curr_attrs.keys | prev_attrs.keys) - NON_DATA_COLUMNS).each do |col|
447
+ next if curr_attrs[col] == prev_attrs[col]
448
+
449
+ entry = (server_touched[col] ||= { nodes: [] })
450
+ entry[:value] = curr_attrs[col]
451
+ entry[:hlc] = c_hlc
452
+ entry[:nodes] << c_node if c_node && !entry[:nodes].include?(c_node)
453
+ end
454
+
455
+ prev_attrs = curr_attrs
456
+ end
457
+
458
+ # Catch any unlogged direct server column update (e.g. update_columns).
459
+ live_attrs = InstantRecord.wire_attributes(record.attributes)
460
+ ((live_attrs.keys | prev_attrs.keys) - NON_DATA_COLUMNS).each do |col|
461
+ next if live_attrs[col] == prev_attrs[col]
462
+
463
+ entry = (server_touched[col] ||= { nodes: [] })
464
+ entry[:value] = live_attrs[col]
465
+ entry[:hlc] = record_hlc
466
+ entry[:nodes] << HLC::SERVER_NODE unless entry[:nodes].include?(HLC::SERVER_NODE)
467
+ end
468
+
469
+ [base_attrs, server_touched, true]
470
+ end
471
+
472
+ def same_node_sequential?(incoming_node, incoming_hlc, col_info)
473
+ return false if incoming_node.nil? || incoming_node == HLC::SERVER_NODE || incoming_node == HLC::LEGACY_NODE
474
+ return false if col_info[:nodes].empty?
475
+
476
+ col_info[:nodes].all? { |n| n == incoming_node } &&
477
+ col_info[:hlc].present? &&
478
+ HLC.compare(incoming_hlc, col_info[:hlc]) > 0
479
+ end
480
+
481
+ # 3-way collection union for `sync_merge :col, :union`:
482
+ # - Arrays (native Postgres arrays, JSON/serialized arrays)
483
+ # - JSON-encoded array strings (e.g. '["a","b"]' in SQLite text columns)
484
+ # - Hashes / JSON objects (3-way key merge; LWW on colliding keys)
485
+ # - Comma-separated strings (e.g. "bug, urgent")
486
+ def merge_union(base_val, server_val, client_val, incoming_wins:)
487
+ if server_val.is_a?(Array) || client_val.is_a?(Array)
488
+ return merge_array_union(base_val.is_a?(Array) ? base_val : nil, Array(server_val), Array(client_val))
489
+ end
490
+
491
+ if server_val.is_a?(Hash) || client_val.is_a?(Hash)
492
+ return merge_hash_union(
493
+ base_val.is_a?(Hash) ? base_val : nil,
494
+ server_val.is_a?(Hash) ? server_val : {},
495
+ client_val.is_a?(Hash) ? client_val : {},
496
+ incoming_wins: incoming_wins
497
+ )
498
+ end
499
+
500
+ if json_array_string?(server_val) || json_array_string?(client_val)
501
+ s_arr = parse_json_array(server_val)
502
+ c_arr = parse_json_array(client_val)
503
+ b_arr = parse_json_array(base_val, fallback: nil)
504
+ return JSON.generate(merge_array_union(b_arr, s_arr, c_arr))
505
+ end
506
+
507
+ if json_object_string?(server_val) || json_object_string?(client_val)
508
+ s_hash = parse_json_object(server_val)
509
+ c_hash = parse_json_object(client_val)
510
+ b_hash = parse_json_object(base_val, fallback: nil)
511
+ return JSON.generate(merge_hash_union(b_hash, s_hash, c_hash, incoming_wins: incoming_wins))
512
+ end
513
+
514
+ separator = server_val.to_s.include?(", ") || client_val.to_s.include?(", ") ? ", " : ","
515
+ b_list = base_val.nil? ? nil : split_csv(base_val)
516
+ merged = merge_array_union(b_list, split_csv(server_val), split_csv(client_val))
517
+ merged.join(separator)
518
+ end
519
+
520
+ def merge_array_union(base_arr, server_arr, client_arr)
521
+ if base_arr.nil?
522
+ (server_arr | client_arr)
523
+ else
524
+ client_added = client_arr - base_arr
525
+ client_removed = base_arr - client_arr
526
+ ((server_arr - client_removed) | client_added)
527
+ end
528
+ end
529
+
530
+ def merge_hash_union(base_hash, server_hash, client_hash, incoming_wins:)
531
+ merged = server_hash.dup
532
+ if base_hash.nil?
533
+ client_hash.each do |k, v|
534
+ merged[k] = v if !merged.key?(k) || incoming_wins
535
+ end
536
+ else
537
+ (base_hash.keys | client_hash.keys).each do |k|
538
+ c_present = client_hash.key?(k)
539
+ b_present = base_hash.key?(k)
540
+ next if c_present == b_present && client_hash[k] == base_hash[k]
541
+
542
+ s_changed = server_hash.key?(k) != b_present || server_hash[k] != base_hash[k]
543
+ if !s_changed || incoming_wins
544
+ c_present ? merged[k] = client_hash[k] : merged.delete(k)
545
+ end
546
+ end
547
+ end
548
+ merged
549
+ end
550
+
551
+ def json_array_string?(value)
552
+ value.is_a?(String) && value.lstrip.start_with?("[") && JSON.parse(value).is_a?(Array)
553
+ rescue JSON::ParserError
554
+ false
555
+ end
556
+
557
+ def parse_json_array(value, fallback: [])
558
+ return fallback if value.nil? || value == ""
559
+ return value if value.is_a?(Array)
560
+
561
+ parsed = JSON.parse(value.to_s)
562
+ parsed.is_a?(Array) ? parsed : fallback
563
+ rescue JSON::ParserError
564
+ fallback
565
+ end
566
+
567
+ def json_object_string?(value)
568
+ value.is_a?(String) && value.lstrip.start_with?("{") && JSON.parse(value).is_a?(Hash)
569
+ rescue JSON::ParserError
570
+ false
571
+ end
572
+
573
+ def parse_json_object(value, fallback: {})
574
+ return fallback if value.nil? || value == ""
575
+ return value if value.is_a?(Hash)
576
+
577
+ parsed = JSON.parse(value.to_s)
578
+ parsed.is_a?(Hash) ? parsed : fallback
579
+ rescue JSON::ParserError
580
+ fallback
581
+ end
582
+
583
+ def split_csv(value)
584
+ value.to_s.split(",").map(&:strip).reject(&:empty?)
585
+ end
586
+
587
+ def skipped_result(record, record_hlc)
588
+ result = {
589
+ status: "applied",
590
+ version: record.server_version,
591
+ skipped: true,
592
+ server_attributes: InstantRecord.wire_attributes(record.attributes)
593
+ }
594
+ result[:hlc] = record_hlc if HLC.valid?(record_hlc)
595
+ result
596
+ end
597
+
598
+ def mutation_base_version
599
+ raw = @mutation[:base_version]
600
+ return nil if raw.nil? || raw == ""
601
+
602
+ raw.to_i
603
+ end
604
+
605
+ def resolve_incoming_hlc(server_now)
606
+ if HLC.valid?(@mutation[:hlc])
607
+ HLC.clamp(@mutation[:hlc], now: server_now)
608
+ elsif @changes["updated_at"].present?
609
+ parsed = parse_timestamp(@changes["updated_at"])
610
+ if parsed
611
+ HLC.clamp(HLC.from_time(parsed, node: HLC::LEGACY_NODE), now: server_now)
612
+ else
613
+ HLC.tick(now: server_now, node: HLC::SERVER_NODE)
614
+ end
615
+ else
616
+ HLC.tick(now: server_now, node: HLC::SERVER_NODE)
617
+ end
618
+ end
619
+
620
+ def record_current_hlc(record)
621
+ stored = HLC.record_hlc(record.class.name, record.id)
622
+ return stored if HLC.valid?(stored)
623
+
624
+ HLC.from_time(record.updated_at, node: HLC::SERVER_NODE) if record.updated_at.present?
625
+ end
626
+
627
+ def clamp_updated_at(changes, server_now, reference_hlc)
628
+ return changes unless changes["updated_at"].present?
629
+
630
+ parsed = parse_timestamp(changes["updated_at"])
631
+ return changes unless parsed
632
+
633
+ if (parsed.utc - server_now) > HLC.max_drift
634
+ clamped_time = HLC.physical_time(reference_hlc) || server_now
635
+ changes.merge("updated_at" => clamped_time.utc.iso8601(InstantRecord::TIME_PRECISION))
636
+ else
637
+ changes
638
+ end
639
+ end
640
+
641
+ def parse_timestamp(value)
642
+ Time.zone.parse(value.to_s)
643
+ rescue ArgumentError
644
+ nil
645
+ end
646
+
647
+ def log_change(record, operation, hlc:)
648
+ change = Change.create!(
100
649
  record_type: record.class.name,
101
650
  record_id: record.id,
102
651
  operation: operation,
103
652
  version: record.server_version,
104
- attributes_payload: InstantRecord.wire_attributes(record.attributes)
653
+ attributes_payload: InstantRecord.wire_attributes(record.attributes),
654
+ scope: InstantRecord.scope_of(record),
655
+ partition: InstantRecord.partition_of(record)
105
656
  )
657
+ HLC.set_change_hlc(change.id, hlc)
658
+ HLC.set_record_hlc(record.class.name, record.id, hlc)
106
659
  end
107
660
 
108
- def log_destroy(model)
109
- Change.create!(
661
+ def log_destroy(model, record, hlc:)
662
+ change = Change.create!(
110
663
  record_type: model.name,
111
664
  record_id: @mutation[:record_id],
112
665
  operation: "destroy",
113
666
  version: 0,
114
- attributes_payload: {}
667
+ attributes_payload: {},
668
+ scope: record && InstantRecord.scope_of(record),
669
+ partition: record && InstantRecord.partition_of(record)
115
670
  )
671
+ HLC.set_change_hlc(change.id, hlc)
672
+ HLC.delete_record_hlc(model.name, @mutation[:record_id])
116
673
  end
117
674
 
675
+ # The server's row as the sender may see it, for a client to roll back to.
676
+ # Every rejection reads through here, so none carries a hidden record.
118
677
  def server_attributes_for(model)
119
- record = model&.find_by(id: @mutation[:record_id])
678
+ record = model && SyncScope.visible(model, @identity, partition: @partition).find_by(id: @mutation[:record_id])
120
679
  InstantRecord.wire_attributes(record.attributes) if record
121
680
  end
122
681
 
682
+ # A stored answer, for whoever is asking now. The ledger knows a mutation
683
+ # by its id alone, so a row it kept for the first sender is read again
684
+ # through what this one may see.
685
+ def replayed(result)
686
+ model = InstantRecord.synced_model(@mutation[:record_type])
687
+ return result unless result[:server_attributes] && model && SyncScope.scoped?(model)
688
+
689
+ result.merge(server_attributes: server_attributes_for(model))
690
+ end
691
+
692
+ # The record exists and a `syncable_to` rule keeps it from the sender.
693
+ def hidden?(model)
694
+ model.instant_record_visibility && model.exists?(id: @mutation[:record_id]) &&
695
+ !SyncScope.visible(model, @identity, partition: @partition).exists?(id: @mutation[:record_id])
696
+ end
697
+
698
+ # The record, as it stands inside this transaction, is one the sender may
699
+ # write. A `sync_scope` / `sync_partition` column is settled before the write (see perform).
700
+ def permit!(model)
701
+ return unless model.instant_record_writability
702
+
703
+ raise NotPermitted unless SyncScope.writable(model, @identity, partition: @partition).exists?(id: @mutation[:record_id])
704
+ end
705
+
123
706
  # create_or_find_by leans on the unique index: a concurrent duplicate
124
707
  # returns the already-recorded result instead of applying twice.
125
708
  def record_result(**result)
126
- payload = result.merge(mutation_id: @mutation[:id])
127
- record = AppliedMutation.create_or_find_by(mutation_id: @mutation[:id]) do |applied|
709
+ payload = result.merge(mutation_id: @mutation_id)
710
+ record = AppliedMutation.create_or_find_by(mutation_id: @mutation_id) do |applied|
128
711
  applied.result_payload = payload
129
712
  end
130
713
  record.result_payload.symbolize_keys