paper_trail_diff 0.17.1 → 0.18.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 (215) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +648 -0
  3. data/QUICKSTART.md +12 -14
  4. data/README.md +32 -30
  5. data/docs/architecture.md +65 -29
  6. data/docs/performance.md +161 -46
  7. data/docs/reference.md +495 -394
  8. data/docs/testing.md +9 -15
  9. data/lib/paper_trail_diff/activity_belongs_to_event_applier.rb +42 -9
  10. data/lib/paper_trail_diff/activity_boundary.rb +15 -6
  11. data/lib/paper_trail_diff/activity_child_candidate_loader.rb +91 -18
  12. data/lib/paper_trail_diff/activity_collection_event_applier.rb +14 -15
  13. data/lib/paper_trail_diff/activity_collection_record_updater.rb +18 -8
  14. data/lib/paper_trail_diff/activity_collection_route_updater.rb +12 -25
  15. data/lib/paper_trail_diff/activity_event.rb +53 -34
  16. data/lib/paper_trail_diff/activity_event_record_normalizer.rb +12 -26
  17. data/lib/paper_trail_diff/activity_event_record_resolver.rb +45 -32
  18. data/lib/paper_trail_diff/activity_event_snapshot_refresher.rb +26 -33
  19. data/lib/paper_trail_diff/activity_history.rb +28 -34
  20. data/lib/paper_trail_diff/activity_relationship.rb +3 -26
  21. data/lib/paper_trail_diff/activity_root_snapshot_refresher.rb +14 -8
  22. data/lib/paper_trail_diff/activity_snapshot_delta.rb +2 -3
  23. data/lib/paper_trail_diff/activity_snapshot_sequence.rb +92 -25
  24. data/lib/paper_trail_diff/activity_timeline_builder.rb +128 -77
  25. data/lib/paper_trail_diff/activity_transaction_applier.rb +49 -0
  26. data/lib/paper_trail_diff/activity_tree_filter.rb +70 -57
  27. data/lib/paper_trail_diff/activity_tree_places.rb +76 -0
  28. data/lib/paper_trail_diff/activity_version_collector.rb +45 -32
  29. data/lib/paper_trail_diff/activity_view.rb +2 -0
  30. data/lib/paper_trail_diff/analysis.rb +6 -5
  31. data/lib/paper_trail_diff/analysis_batch.rb +21 -17
  32. data/lib/paper_trail_diff/association_activity_edge.rb +99 -85
  33. data/lib/paper_trail_diff/association_activity_selection.rb +46 -14
  34. data/lib/paper_trail_diff/association_discovery.rb +4 -4
  35. data/lib/paper_trail_diff/association_key.rb +10 -18
  36. data/lib/paper_trail_diff/association_traversal.rb +72 -92
  37. data/lib/paper_trail_diff/batch_boundary_resolver.rb +1 -7
  38. data/lib/paper_trail_diff/batch_preload.rb +2 -3
  39. data/lib/paper_trail_diff/batched_root_analyses.rb +60 -25
  40. data/lib/paper_trail_diff/batched_root_analyzer.rb +5 -5
  41. data/lib/paper_trail_diff/batched_root_versions.rb +7 -30
  42. data/lib/paper_trail_diff/branch_snapshot_refresher.rb +19 -14
  43. data/lib/paper_trail_diff/candidate_table.rb +160 -0
  44. data/lib/paper_trail_diff/change_attribution.rb +15 -23
  45. data/lib/paper_trail_diff/collection_identity_index.rb +68 -24
  46. data/lib/paper_trail_diff/collection_transition.rb +3 -3
  47. data/lib/paper_trail_diff/comparison_batch.rb +13 -6
  48. data/lib/paper_trail_diff/database_time.rb +85 -0
  49. data/lib/paper_trail_diff/deleted_analysis_batch.rb +22 -23
  50. data/lib/paper_trail_diff/deleted_root_filter.rb +10 -6
  51. data/lib/paper_trail_diff/diagnostics.rb +26 -86
  52. data/lib/paper_trail_diff/endpoint.rb +37 -5
  53. data/lib/paper_trail_diff/engine.rb +1 -1
  54. data/lib/paper_trail_diff/errors.rb +0 -6
  55. data/lib/paper_trail_diff/exact_column_type.rb +96 -0
  56. data/lib/paper_trail_diff/historical_snapshot_store.rb +88 -83
  57. data/lib/paper_trail_diff/instrumentation.rb +0 -8
  58. data/lib/paper_trail_diff/live_endpoint_batch_loader.rb +1 -4
  59. data/lib/paper_trail_diff/live_graph_collector.rb +1 -3
  60. data/lib/paper_trail_diff/nested_comparator.rb +42 -10
  61. data/lib/paper_trail_diff/paper_trail_adapter.rb +55 -98
  62. data/lib/paper_trail_diff/prepared_activity_index.rb +214 -182
  63. data/lib/paper_trail_diff/prepared_child_candidates.rb +13 -3
  64. data/lib/paper_trail_diff/prepared_edge_loader.rb +11 -49
  65. data/lib/paper_trail_diff/prepared_history.rb +27 -177
  66. data/lib/paper_trail_diff/prepared_history_loader.rb +39 -57
  67. data/lib/paper_trail_diff/prepared_record_index.rb +221 -147
  68. data/lib/paper_trail_diff/prepared_snapshot_builder.rb +47 -42
  69. data/lib/paper_trail_diff/prepared_state_association_reader.rb +85 -62
  70. data/lib/paper_trail_diff/recorded_changes.rb +34 -10
  71. data/lib/paper_trail_diff/recorded_owner.rb +67 -0
  72. data/lib/paper_trail_diff/root_version_selection.rb +6 -2
  73. data/lib/paper_trail_diff/scope_condition.rb +120 -80
  74. data/lib/paper_trail_diff/scope_ranking.rb +14 -32
  75. data/lib/paper_trail_diff/scoped_analysis.rb +11 -6
  76. data/lib/paper_trail_diff/scoped_analysis_builder.rb +17 -11
  77. data/lib/paper_trail_diff/scoped_root_selection.rb +91 -85
  78. data/lib/paper_trail_diff/selection_window.rb +31 -0
  79. data/lib/paper_trail_diff/snapshot.rb +60 -58
  80. data/lib/paper_trail_diff/snapshot_members.rb +115 -0
  81. data/lib/paper_trail_diff/snapshot_normalizer.rb +0 -11
  82. data/lib/paper_trail_diff/step.rb +1 -5
  83. data/lib/paper_trail_diff/stored_form.rb +146 -0
  84. data/lib/paper_trail_diff/stored_json_values.rb +8 -5
  85. data/lib/paper_trail_diff/stored_time_precision.rb +67 -33
  86. data/lib/paper_trail_diff/stored_values.rb +35 -3
  87. data/lib/paper_trail_diff/support.rb +185 -35
  88. data/lib/paper_trail_diff/time_of_day.rb +13 -2
  89. data/lib/paper_trail_diff/time_range.rb +85 -11
  90. data/lib/paper_trail_diff/time_version_range.rb +5 -1
  91. data/lib/paper_trail_diff/timeline_builder.rb +5 -11
  92. data/lib/paper_trail_diff/timeline_range.rb +56 -19
  93. data/lib/paper_trail_diff/timeline_snapshot_provider.rb +31 -7
  94. data/lib/paper_trail_diff/total_order.rb +19 -5
  95. data/lib/paper_trail_diff/transaction_anchors.rb +138 -0
  96. data/lib/paper_trail_diff/transaction_cut.rb +67 -327
  97. data/lib/paper_trail_diff/transaction_ends.rb +194 -0
  98. data/lib/paper_trail_diff/traversal_preparer.rb +12 -24
  99. data/lib/paper_trail_diff/{approximate_paths.rb → unreadable_paths.rb} +8 -9
  100. data/lib/paper_trail_diff/value_objects.rb +8 -6
  101. data/lib/paper_trail_diff/version.rb +1 -1
  102. data/lib/paper_trail_diff/version_association_candidate_scope.rb +12 -10
  103. data/lib/paper_trail_diff/version_boundary.rb +0 -29
  104. data/lib/paper_trail_diff/version_query.rb +49 -1
  105. data/lib/paper_trail_diff/version_scope_filter.rb +74 -5
  106. data/lib/paper_trail_diff/version_sequence_diagnostics.rb +4 -31
  107. data/lib/paper_trail_diff/version_table.rb +8 -1
  108. data/lib/paper_trail_diff.rb +56 -110
  109. data/sig/generated/paper_trail_diff/activity_belongs_to_event_applier.rbs +24 -2
  110. data/sig/generated/paper_trail_diff/activity_boundary.rbs +6 -0
  111. data/sig/generated/paper_trail_diff/activity_child_candidate_loader.rbs +46 -5
  112. data/sig/generated/paper_trail_diff/activity_collection_event_applier.rbs +7 -4
  113. data/sig/generated/paper_trail_diff/activity_collection_record_updater.rbs +11 -2
  114. data/sig/generated/paper_trail_diff/activity_collection_route_updater.rbs +8 -6
  115. data/sig/generated/paper_trail_diff/activity_event.rbs +27 -18
  116. data/sig/generated/paper_trail_diff/activity_event_record_normalizer.rbs +7 -11
  117. data/sig/generated/paper_trail_diff/activity_event_record_resolver.rbs +26 -8
  118. data/sig/generated/paper_trail_diff/activity_event_snapshot_refresher.rbs +10 -2
  119. data/sig/generated/paper_trail_diff/activity_history.rbs +23 -26
  120. data/sig/generated/paper_trail_diff/activity_relationship.rbs +0 -6
  121. data/sig/generated/paper_trail_diff/activity_root_snapshot_refresher.rbs +5 -0
  122. data/sig/generated/paper_trail_diff/activity_snapshot_sequence.rbs +53 -10
  123. data/sig/generated/paper_trail_diff/activity_timeline_builder.rbs +64 -38
  124. data/sig/generated/paper_trail_diff/activity_transaction_applier.rbs +28 -0
  125. data/sig/generated/paper_trail_diff/activity_tree_filter.rbs +46 -38
  126. data/sig/generated/paper_trail_diff/activity_tree_places.rbs +45 -0
  127. data/sig/generated/paper_trail_diff/activity_version_collector.rbs +21 -11
  128. data/sig/generated/paper_trail_diff/analysis.rbs +6 -5
  129. data/sig/generated/paper_trail_diff/analysis_batch.rbs +8 -6
  130. data/sig/generated/paper_trail_diff/association_activity_edge.rbs +58 -45
  131. data/sig/generated/paper_trail_diff/association_activity_selection.rbs +20 -3
  132. data/sig/generated/paper_trail_diff/association_discovery.rbs +2 -2
  133. data/sig/generated/paper_trail_diff/association_key.rbs +2 -11
  134. data/sig/generated/paper_trail_diff/association_traversal.rbs +43 -44
  135. data/sig/generated/paper_trail_diff/batch_boundary_resolver.rbs +0 -2
  136. data/sig/generated/paper_trail_diff/batched_root_analyses.rbs +40 -17
  137. data/sig/generated/paper_trail_diff/batched_root_analyzer.rbs +2 -2
  138. data/sig/generated/paper_trail_diff/batched_root_versions.rbs +2 -11
  139. data/sig/generated/paper_trail_diff/branch_snapshot_refresher.rbs +12 -8
  140. data/sig/generated/paper_trail_diff/candidate_table.rbs +97 -0
  141. data/sig/generated/paper_trail_diff/change_attribution.rbs +9 -16
  142. data/sig/generated/paper_trail_diff/collection_identity_index.rbs +33 -13
  143. data/sig/generated/paper_trail_diff/collection_transition.rbs +2 -2
  144. data/sig/generated/paper_trail_diff/comparison_batch.rbs +5 -0
  145. data/sig/generated/paper_trail_diff/database_time.rbs +48 -0
  146. data/sig/generated/paper_trail_diff/deleted_analysis_batch.rbs +13 -15
  147. data/sig/generated/paper_trail_diff/deleted_root_filter.rbs +4 -0
  148. data/sig/generated/paper_trail_diff/diagnostics.rbs +13 -31
  149. data/sig/generated/paper_trail_diff/endpoint.rbs +14 -1
  150. data/sig/generated/paper_trail_diff/errors.rbs +0 -8
  151. data/sig/generated/paper_trail_diff/exact_column_type.rbs +51 -0
  152. data/sig/generated/paper_trail_diff/historical_snapshot_store.rbs +51 -31
  153. data/sig/generated/paper_trail_diff/instrumentation.rbs +0 -5
  154. data/sig/generated/paper_trail_diff/nested_comparator.rbs +21 -0
  155. data/sig/generated/paper_trail_diff/paper_trail_adapter.rbs +18 -29
  156. data/sig/generated/paper_trail_diff/prepared_activity_index.rbs +138 -94
  157. data/sig/generated/paper_trail_diff/prepared_child_candidates.rbs +10 -2
  158. data/sig/generated/paper_trail_diff/prepared_edge_loader.rbs +4 -21
  159. data/sig/generated/paper_trail_diff/prepared_history.rbs +22 -79
  160. data/sig/generated/paper_trail_diff/prepared_history_loader.rbs +24 -32
  161. data/sig/generated/paper_trail_diff/prepared_record_index.rbs +137 -63
  162. data/sig/generated/paper_trail_diff/prepared_snapshot_builder.rbs +22 -13
  163. data/sig/generated/paper_trail_diff/prepared_state_association_reader.rbs +41 -28
  164. data/sig/generated/paper_trail_diff/recorded_changes.rbs +19 -3
  165. data/sig/generated/paper_trail_diff/recorded_owner.rbs +39 -0
  166. data/sig/generated/paper_trail_diff/root_version_selection.rbs +4 -1
  167. data/sig/generated/paper_trail_diff/scope_condition.rbs +65 -52
  168. data/sig/generated/paper_trail_diff/scope_ranking.rbs +10 -23
  169. data/sig/generated/paper_trail_diff/scoped_analysis.rbs +11 -6
  170. data/sig/generated/paper_trail_diff/scoped_analysis_builder.rbs +7 -2
  171. data/sig/generated/paper_trail_diff/scoped_root_selection.rbs +49 -43
  172. data/sig/generated/paper_trail_diff/selection_window.rbs +19 -0
  173. data/sig/generated/paper_trail_diff/snapshot.rbs +37 -38
  174. data/sig/generated/paper_trail_diff/snapshot_members.rbs +58 -0
  175. data/sig/generated/paper_trail_diff/snapshot_normalizer.rbs +0 -4
  176. data/sig/generated/paper_trail_diff/stored_form.rbs +63 -0
  177. data/sig/generated/paper_trail_diff/stored_json_values.rbs +0 -2
  178. data/sig/generated/paper_trail_diff/stored_time_precision.rbs +33 -20
  179. data/sig/generated/paper_trail_diff/stored_values.rbs +18 -2
  180. data/sig/generated/paper_trail_diff/support.rbs +96 -16
  181. data/sig/generated/paper_trail_diff/time_of_day.rbs +4 -0
  182. data/sig/generated/paper_trail_diff/time_range.rbs +49 -4
  183. data/sig/generated/paper_trail_diff/time_version_range.rbs +3 -0
  184. data/sig/generated/paper_trail_diff/timeline_builder.rbs +3 -6
  185. data/sig/generated/paper_trail_diff/timeline_range.rbs +29 -8
  186. data/sig/generated/paper_trail_diff/timeline_snapshot_provider.rbs +17 -4
  187. data/sig/generated/paper_trail_diff/total_order.rbs +9 -3
  188. data/sig/generated/paper_trail_diff/transaction_anchors.rbs +80 -0
  189. data/sig/generated/paper_trail_diff/transaction_cut.rbs +43 -176
  190. data/sig/generated/paper_trail_diff/transaction_ends.rbs +124 -0
  191. data/sig/generated/paper_trail_diff/traversal_preparer.rbs +6 -11
  192. data/sig/generated/paper_trail_diff/{approximate_paths.rbs → unreadable_paths.rbs} +6 -7
  193. data/sig/generated/paper_trail_diff/value_objects.rbs +4 -2
  194. data/sig/generated/paper_trail_diff/version_association_candidate_scope.rbs +11 -5
  195. data/sig/generated/paper_trail_diff/version_boundary.rbs +0 -14
  196. data/sig/generated/paper_trail_diff/version_query.rbs +26 -0
  197. data/sig/generated/paper_trail_diff/version_scope_filter.rbs +28 -2
  198. data/sig/generated/paper_trail_diff/version_sequence_diagnostics.rbs +4 -15
  199. data/sig/generated/paper_trail_diff/version_table.rbs +4 -0
  200. data/sig/generated/paper_trail_diff.rbs +22 -23
  201. metadata +28 -20
  202. data/lib/paper_trail_diff/activity_target_candidate_loader.rb +0 -123
  203. data/lib/paper_trail_diff/fallback_paths.rb +0 -35
  204. data/lib/paper_trail_diff/habtm_transaction_owners.rb +0 -70
  205. data/lib/paper_trail_diff/historical_association_reifier.rb +0 -161
  206. data/lib/paper_trail_diff/historical_filter.rb +0 -210
  207. data/lib/paper_trail_diff/own_window.rb +0 -35
  208. data/lib/paper_trail_diff/prepared_association_reifier.rb +0 -51
  209. data/sig/generated/paper_trail_diff/activity_target_candidate_loader.rbs +0 -74
  210. data/sig/generated/paper_trail_diff/fallback_paths.rbs +0 -22
  211. data/sig/generated/paper_trail_diff/habtm_transaction_owners.rbs +0 -41
  212. data/sig/generated/paper_trail_diff/historical_association_reifier.rbs +0 -58
  213. data/sig/generated/paper_trail_diff/historical_filter.rbs +0 -96
  214. data/sig/generated/paper_trail_diff/own_window.rbs +0 -22
  215. data/sig/generated/paper_trail_diff/prepared_association_reifier.rbs +0 -27
data/docs/testing.md CHANGED
@@ -57,7 +57,7 @@ leave it out there.
57
57
  build seeded, generated histories: root edits, checkpoints, and child creates,
58
58
  edits, and deletes. For each one they check that every route to the same answer
59
59
  agrees: `analyze`, `analyze_many`, and `analyze_scope`; checkpoint and activity
60
- modes; `compare` and `timeline` against `analyze`; and that activity steps
60
+ modes; `compare` against `analyze`; and that activity steps
61
61
  chain into the final state. They run over random windows as well as the whole
62
62
  history, with integer and string `versions.item_id`, YAML and JSON history, and
63
63
  a `has_paper_trail skip:` column. When one fails, its seed reproduces it, and
@@ -96,7 +96,7 @@ share passes. `spec/oracle` compares them with the truth instead:
96
96
  not), and windows through `analyze`, `analyze_many`, and `analyze_scope`
97
97
  are compared with the recorded states. Two windows that meet between
98
98
  transactions, or inside one, must report each step once, as the window
99
- spanning both does, through both `activity_timeline` and `analyze_many`.
99
+ spanning both does, through both `analyze` and `analyze_many`.
100
100
  The transactions take turns between no author, `alice`, and `bob`, and
101
101
  the same windows filtered to alice's versions must report exactly the
102
102
  unfiltered steps of the transactions she saved a version in.
@@ -110,12 +110,8 @@ serialized, enums stored as strings, custom types, decimals, and JSON.
110
110
  `through_history_spec.rb` edits two teams' join records and the records they
111
111
  reach, through every kind of `has_many :through`: to a `belongs_to`, through a
112
112
  scoped part, ranked with a limit, to a `has_many`, through another through, a
113
- `has_one` through, and with `source_type:`. `habtm_history_spec.rb` attaches,
114
- detaches, creates, renames, and destroys tags between checkpoints. HABTM
115
- membership is known only at root versions, so it expects what the
116
- [reference](reference.md#habtm-limitation) describes: at each point, the
117
- members the next root version recorded, as each was then, and only once it
118
- exists. `shapes_history_spec.rb` edits two boards and the records around them:
113
+ `has_one` through, and with `source_type:`. `shapes_history_spec.rb` edits two
114
+ boards and the records around them:
119
115
  a polymorphic owner, cards that use single-table inheritance and change type,
120
116
  comments that move between boards and cards (`as:`), labels with a default
121
117
  scope, and scoped and ranked associations to the cards. Its checks, in
@@ -285,8 +281,9 @@ passes is behavior nothing checks. `mutant.yml` lists the classes it mutates:
285
281
  `Endpoint` and `EndpointKind`;
286
282
  - which versions a range reads: `TimeRange`, `TimelineRange`, `VersionRange`,
287
283
  `TimeVersionRange`, `RootVersionSelection`, `RootVersionPlan`,
288
- `TransactionCut`, `OpeningTransactions`, `VersionBoundary`, and
289
- `VersionQuery`;
284
+ `TransactionCut`, `CrossingTransactions`, `TransactionEnds`,
285
+ `RecordedTransactionEnds`,
286
+ `VersionBoundary`, and `VersionQuery`;
290
287
  - which versions a batch or filter reads: `AnalysisBatch`,
291
288
  `BatchedRootVersions`, `BatchedRootAnalyses`, `BatchBoundaryResolver`,
292
289
  `DeletedAnalysisBatch`, `HistoricalFilter`, and `VersionScopeFilter`;
@@ -312,12 +309,9 @@ passes is behavior nothing checks. `mutant.yml` lists the classes it mutates:
312
309
  - where in a carried snapshot an event's record sits: `ActivityEventRouteFinder`;
313
310
  - which association paths a request accepts: `AssociationTraversal`,
314
311
  `AssociationKey`, and `VersionTable`;
315
- - whether a transaction's HABTM members are one record's:
316
- `HabtmTransactionOwners`;
317
- - which association paths history cannot read exactly, and whether a request
318
- reads one with PT-AT: `ApproximatePaths` and `FallbackPaths`;
312
+ - which association paths history cannot read: `UnreadablePaths`;
319
313
  - which records an association scope admits, and how it ranks them:
320
- `ScopeCondition` and `ScopeRanking`;
314
+ `ScopeCondition`, `ScopeRanking`, and `ExactColumnType`;
321
315
  - the helpers these share, which order versions, name records, and copy
322
316
  values: `Support`.
323
317
 
@@ -3,6 +3,8 @@
3
3
 
4
4
  module PaperTrailDiff
5
5
  # Applies selected non-polymorphic belongs-to target updates to a snapshot.
6
+ # A target created there changes nothing unless an owner already named it,
7
+ # as one can where no foreign key constraint forbids it (see #created).
6
8
  class ActivityBelongsToEventApplier
7
9
  #: (route_finder: ActivityEventRouteFinder, record_resolver: ActivityEventRecordResolver, record_normalizer: ActivityEventRecordNormalizer) -> void
8
10
  def initialize(route_finder:, record_resolver:, record_normalizer:)
@@ -20,18 +22,18 @@ module PaperTrailDiff
20
22
  normalizer,
21
23
  version
22
24
  )
23
- return [false, nil] unless %w[update destroy].include?(version.event.to_s)
25
+ event = version.event.to_s
26
+ return [false, nil] unless %w[create update destroy].include?(event)
24
27
 
25
28
  routes = @route_finder.belongs_to_routes(
26
29
  RecordedClass.of_endpoint(root_endpoint), tree, version.item_type.to_s
27
30
  )
28
- return [false, nil] if routes.empty? || ActivityEventRouteFinder.scoped_route?(routes)
31
+ return [false, nil] if reread?(routes)
32
+ return created(previous, routes) if event == 'create'
29
33
 
30
34
  snapshot = previous
31
35
  routes.each do |route|
32
- replacement = normalized_route_record(
33
- route, version, normalizer, root_endpoint, context_endpoint
34
- )
36
+ replacement = normalized_route_record(route, version, normalizer, context_endpoint)
35
37
  snapshot, = replace_route(snapshot, route, version, replacement)
36
38
  end
37
39
  [true, snapshot]
@@ -43,9 +45,41 @@ module PaperTrailDiff
43
45
  # @rbs @record_resolver: ActivityEventRecordResolver
44
46
  # @rbs @record_normalizer: ActivityEventRecordNormalizer
45
47
 
46
- #: (Array[untyped], untyped, SnapshotNormalizer, untyped, untyped) -> RecordSnapshot?
47
- def normalized_route_record(route, version, normalizer, root_endpoint, context_endpoint)
48
- record = @record_resolver.record_after(version, direct: route.last.fetch(2).empty?)
48
+ # Whether the branch must be read again rather than patched. A target
49
+ # class that is an STI subclass holds a record only while its type names
50
+ # the subclass, so an update that retypes the record moves it in or out,
51
+ # which only the owner's key, read again, can tell.
52
+ #: (Array[Array[untyped]]) -> bool
53
+ def reread?(routes)
54
+ routes.empty? || ActivityEventRouteFinder.scoped_route?(routes) ||
55
+ routes.any? { |route| !route.last.fetch(1).klass.descends_from_active_record? }
56
+ end
57
+
58
+ # A created target is new to the snapshot unless an owner named it first.
59
+ # A snapshot leaves out an owner's key, but an owner that names a record
60
+ # holds one, and only an owner holding none can name a record that does
61
+ # not exist yet: the branch is read again only when there is such an
62
+ # owner.
63
+ #: (RecordSnapshot, Array[Array[untyped]]) -> [bool, RecordSnapshot?]
64
+ def created(previous, routes)
65
+ vacant = routes.any? { |route| vacant?(previous, route, 0) }
66
+ vacant ? [false, nil] : [true, previous]
67
+ end
68
+
69
+ # Whether a record along the route holds no target where it ends, or the
70
+ # snapshot does not say.
71
+ #: (RecordSnapshot, Array[untyped], Integer) -> bool
72
+ def vacant?(snapshot, route, depth)
73
+ association = snapshot.associations[route.fetch(depth).fetch(0)]
74
+ return true unless association
75
+ return association.records.empty? if depth == route.length - 1
76
+
77
+ association.records.any? { |record| vacant?(record, route, depth + 1) }
78
+ end
79
+
80
+ #: (Array[untyped], untyped, SnapshotNormalizer, untyped) -> RecordSnapshot?
81
+ def normalized_route_record(route, version, normalizer, context_endpoint)
82
+ record = @record_resolver.record_after(version)
49
83
  return unless record
50
84
 
51
85
  _name, reflection, subtree, path = route.last
@@ -55,7 +89,6 @@ module PaperTrailDiff
55
89
  subtree: subtree,
56
90
  path: path,
57
91
  normalizer: normalizer,
58
- root_endpoint: root_endpoint,
59
92
  context_endpoint: context_endpoint
60
93
  )
61
94
  end
@@ -22,7 +22,8 @@ module PaperTrailDiff
22
22
  # Stands for recorded changes nobody asked to read, which differs from a
23
23
  # version that recorded nothing (nil).
24
24
  NOT_READ = Object.new.freeze
25
- NOT_READ_MESSAGE = 'recorded changes were not read; pass recorded_changes: true'
25
+ NOT_READ_MESSAGE = 'recorded changes were not read; pass recorded_changes: true to the ' \
26
+ 'method that takes it, or call PaperTrailDiff.recorded_changes(version)'
26
27
  private_constant :NOT_READ, :NOT_READ_MESSAGE
27
28
 
28
29
  class << self
@@ -64,6 +65,18 @@ module PaperTrailDiff
64
65
  recorded_at: nil, recorded_changes: nil)
65
66
  end
66
67
 
68
+ # The `from`/`to`/`diff` hash that `Step#to_h` and `ActivityStep#to_h`
69
+ # share, so a consumer reads both step types alike.
70
+ # @api private
71
+ #: (ActivityBoundary, ActivityBoundary, Diff, metadata: bool) -> Hash[Symbol, untyped]
72
+ def transition_h(from, to, diff, metadata:)
73
+ {
74
+ from: from.to_h(metadata: metadata),
75
+ to: to.to_h(metadata: metadata),
76
+ diff: diff.to_h
77
+ }
78
+ end
79
+
67
80
  private
68
81
 
69
82
  #: (untyped, Symbol, RecordedChangesReader?) -> ActivityBoundary
@@ -249,11 +262,7 @@ module PaperTrailDiff
249
262
  # metadata as much as the source boundary's own author is.
250
263
  #: (?metadata: bool, ?snapshots: bool) -> Hash[Symbol, untyped]
251
264
  def to_h(metadata: false, snapshots: false)
252
- value = {
253
- from: from_boundary.to_h(metadata: metadata),
254
- to: to_boundary.to_h(metadata: metadata),
255
- diff: diff.to_h
256
- } #: Hash[Symbol, untyped]
265
+ value = ActivityBoundary.transition_h(from_boundary, to_boundary, diff, metadata: metadata)
257
266
  value[:sources] = sources.map { |source| source.to_h(metadata: true) } if metadata
258
267
  return value unless snapshots
259
268
 
@@ -4,16 +4,21 @@
4
4
  module PaperTrailDiff
5
5
  # Loads the children of a has_many or has_one that its owners had from a
6
6
  # start onward, from PT-AT's version associations and the live rows.
7
- # Prepared history and activity both read children through it. A composite
8
- # foreign key reads none, as loaded history cannot index it.
7
+ # Prepared history and activity both read children through it.
8
+ #
9
+ # A history that ends leaves out the children created after its end (see
10
+ # VersionQuery.created_after), which no state up to the end holds: read
11
+ # with the rest, each would bring its versions and its row, and a range
12
+ # long past would cost more with every child its owners have gained since.
9
13
  class ActivityChildCandidateLoader
10
- #: (untyped, Array[untyped], untyped, untyped) -> void
11
- def initialize(parent_class, parent_ids, reflection, start_at)
14
+ #: (untyped, Array[untyped], untyped, untyped, untyped) -> void
15
+ def initialize(parent_class, parent_ids, reflection, start_at, end_at)
12
16
  @parent_class = parent_class
13
17
  @parent_ids = parent_ids
14
18
  @reflection = reflection
15
19
  @start_at = start_at
16
- @foreign_key = AssociationKey.scalar_foreign_key(reflection)
20
+ @end_at = end_at
21
+ @foreign_key = reflection.foreign_key
17
22
  end
18
23
 
19
24
  # Queries shared by a batch's roots keep the owner and timestamp needed to
@@ -21,27 +26,21 @@ module PaperTrailDiff
21
26
  #: () -> Array[Array[untyped]]
22
27
  def historical_rows
23
28
  foreign_key = @foreign_key
24
- return [] unless foreign_key
25
-
26
29
  version_class = @parent_class.paper_trail.version_class
27
30
  scope = VersionAssociationCandidateScope.new(version_class, @start_at)
28
- owner_slices.flat_map do |owners|
31
+ recorded = owner_slices.flat_map do |owners|
29
32
  relation = scope.call(historical_relation(version_class, foreign_key, owners))
30
- typed_rows(pluck_rows(relation, version_class))
33
+ relation = relation.where(there_by_end(version_class)) if @end_at
34
+ pluck_rows(relation, version_class)
31
35
  end
36
+ typed_rows((recorded + first_owner_rows(foreign_key)).uniq)
32
37
  end
33
38
 
34
39
  #: () -> Array[Array[untyped]]
35
40
  def current_pairs
36
41
  foreign_key = @foreign_key
37
- return [] unless foreign_key
38
-
39
- # Every row of the table, as history reads them: an STI subclass's
40
- # siblings are left out where children are resolved.
41
42
  owner_slices.flat_map do |owners|
42
- relation = @reflection.klass.base_class.unscoped.where(foreign_key => owners)
43
- relation = relation.where(@reflection.type => parent_types) if @reflection.type
44
- relation.pluck(foreign_key, @reflection.klass.primary_key)
43
+ live_relation(foreign_key, owners).pluck(foreign_key, @reflection.klass.primary_key)
45
44
  end
46
45
  end
47
46
 
@@ -51,7 +50,47 @@ module PaperTrailDiff
51
50
  # @rbs @parent_ids: Array[untyped]
52
51
  # @rbs @reflection: untyped
53
52
  # @rbs @start_at: untyped
54
- # @rbs @foreign_key: String?
53
+ # @rbs @end_at: untyped
54
+ # @rbs @foreign_key: String
55
+
56
+ # Every row of the table, as history reads them: an STI subclass's
57
+ # siblings are left out where children are resolved.
58
+ #: (String, Array[untyped]) -> untyped
59
+ def live_relation(foreign_key, owners)
60
+ relation = @reflection.klass.base_class.unscoped.where(foreign_key => owners)
61
+ relation = relation.where(@reflection.type => parent_types) if @reflection.type
62
+ comparable_keys? ? relation.where(live_by_end) : relation
63
+ end
64
+
65
+ # Any version of a child that was not created after the end. A version
66
+ # saved by the end precedes any create after it, so it is always kept.
67
+ #: (untyped) -> untyped
68
+ def there_by_end(version_class)
69
+ versions = version_class.arel_table
70
+ VersionQuery.created_after(versions, versions[:item_type], versions[:item_id], @end_at).not
71
+ end
72
+
73
+ # The child class is quoted as its name, which its versions record.
74
+ #: () -> untyped
75
+ def live_by_end
76
+ children = @reflection.klass.base_class
77
+ VersionQuery.created_after(
78
+ @parent_class.paper_trail.version_class.arel_table,
79
+ children, children.arel_table[children.primary_key], @end_at
80
+ ).not
81
+ end
82
+
83
+ # A live row is matched to its versions in the database only where it
84
+ # compares an item_id with a key held as the same type; elsewhere every
85
+ # live child is read, as without an end.
86
+ #: () -> bool
87
+ def comparable_keys?
88
+ return false unless @end_at
89
+
90
+ children = @reflection.klass
91
+ item_ids = @parent_class.paper_trail.version_class.type_for_attribute('item_id')
92
+ children.type_for_attribute(children.primary_key).type == item_ids.type
93
+ end
55
94
 
56
95
  #: (Array[Array[untyped]]) -> Array[Array[untyped]]
57
96
  def typed_rows(rows)
@@ -76,6 +115,40 @@ module PaperTrailDiff
76
115
  ).where(version_class.table_name => { item_type: @reflection.klass.base_class.name })
77
116
  end
78
117
 
118
+ # PT-AT stores the keys a version saved, so the owner a child held before
119
+ # its first version is in no row when that version is not a create: the
120
+ # child was made without one, and its first version's state, which holds
121
+ # that owner, is read instead.
122
+ #: (String) -> Array[Array[untyped]]
123
+ def first_owner_rows(foreign_key)
124
+ held = @parent_ids.to_set(&:to_s)
125
+ first_versions.filter_map do |version|
126
+ state = version.object && version.object_deserialized
127
+ owner = state[foreign_key] if state
128
+ # An `as:` child's type column must name one of the owner's types,
129
+ # which take a child with no type, as any plain child has.
130
+ next unless held.include?(owner.to_s) && parent_types.include?(state[@reflection.type])
131
+
132
+ [owner, version.item_id, version.created_at, version.event]
133
+ end
134
+ end
135
+
136
+ # The first version of each child since the start, unless it created its
137
+ # child: a create holds no state, and every child created after the
138
+ # range would be read for nothing. One saved after the end holds the
139
+ # state the child had there too. A model PaperTrail does not version has
140
+ # none.
141
+ #: () -> untyped
142
+ def first_versions
143
+ return [] unless Support.versioned?(@reflection.klass)
144
+
145
+ relation = VersionQuery.for_model(@reflection.klass).where.not(event: 'create')
146
+ versions = relation.arel_table
147
+ relation = relation.where(VersionQuery.no_earlier_version(versions))
148
+ relation = relation.where(versions[:created_at].gteq(@start_at)) if @start_at
149
+ relation
150
+ end
151
+
79
152
  #: (untyped, untyped) -> Array[Array[untyped]]
80
153
  def pluck_rows(relation, version_class)
81
154
  versions = version_class.arel_table
@@ -86,7 +159,7 @@ module PaperTrailDiff
86
159
 
87
160
  #: () -> Array[String?]
88
161
  def parent_types
89
- [nil, '', @parent_class.name, @parent_class.base_class.name]
162
+ RecordedOwner.types(@reflection, @parent_class)
90
163
  end
91
164
  end
92
165
  end
@@ -32,11 +32,8 @@ module PaperTrailDiff
32
32
  )
33
33
  fallback_record = [] #: Array[untyped]
34
34
  endpoints = [root_endpoint, context_endpoint]
35
- direct = routes.all? { |route| route.last.fetch(2).empty? }
36
35
  snapshot = routes.reduce(previous) do |current, route|
37
- apply_route(
38
- current, route, version, delta, fallback_record, normalizer, endpoints, direct: direct
39
- )
36
+ apply_route(current, route, version, delta, fallback_record, normalizer, endpoints)
40
37
  end
41
38
  [true, snapshot]
42
39
  end
@@ -48,12 +45,12 @@ module PaperTrailDiff
48
45
  # @rbs @route_updater: ActivityCollectionRouteUpdater
49
46
  # @rbs @relationship: ActivityRelationship
50
47
 
51
- #: (RecordSnapshot, Array[untyped], untyped, ActivitySnapshotDelta?, Array[untyped], SnapshotNormalizer, Array[untyped], ?direct: bool) -> RecordSnapshot
48
+ #: (RecordSnapshot, Array[untyped], untyped, ActivitySnapshotDelta?, Array[untyped], SnapshotNormalizer, Array[untyped]) -> RecordSnapshot
52
49
  def apply_route( # rubocop:disable Metrics/ParameterLists
53
- snapshot, route, version, delta, fallback_record, normalizer, endpoints, direct: false
50
+ snapshot, route, version, delta, fallback_record, normalizer, endpoints
54
51
  )
55
52
  record, replacement = route_event_state(
56
- snapshot, route, version, delta, fallback_record, normalizer, endpoints, direct: direct
53
+ snapshot, route, version, delta, fallback_record, normalizer, endpoints
57
54
  )
58
55
  change = ActivityCollectionRouteChange.new(
59
56
  route: route,
@@ -110,36 +107,38 @@ module PaperTrailDiff
110
107
  return owned_keys(reflection.through_reflection) if reflection.through_reflection?
111
108
  return [] unless reflection.belongs_to?
112
109
 
113
- keys = Array(reflection.foreign_key)
114
- reflection.polymorphic? ? [*keys, reflection.foreign_type] : keys
110
+ key = reflection.foreign_key
111
+ reflection.polymorphic? ? [key, reflection.foreign_type] : [key]
115
112
  end
116
113
 
117
- #: (RecordSnapshot, Array[untyped], untyped, ActivitySnapshotDelta?, Array[untyped], SnapshotNormalizer, Array[untyped], ?direct: bool) -> [untyped, RecordSnapshot?]
114
+ #: (RecordSnapshot, Array[untyped], untyped, ActivitySnapshotDelta?, Array[untyped], SnapshotNormalizer, Array[untyped]) -> [untyped, RecordSnapshot?]
118
115
  def route_event_state( # rubocop:disable Metrics/ParameterLists
119
- snapshot, route, version, delta, fallback_record, normalizer, endpoints, direct: false
116
+ snapshot, route, version, delta, fallback_record, normalizer, endpoints
120
117
  )
121
118
  existing = existing_delta_record(snapshot, route, version, delta) if delta
122
119
  return [delta, delta.apply(existing)] if delta && existing
123
120
 
124
- if fallback_record.empty?
125
- fallback_record << @record_resolver.record_after(version, direct: direct)
126
- end
121
+ fallback_record << @record_resolver.record_after(version) if fallback_record.empty?
127
122
  record = fallback_record.first
128
123
  return [record, nil] unless record
129
124
 
130
125
  [record, normalized_event_record(record, route, normalizer, endpoints)]
131
126
  end
132
127
 
128
+ # A record the event took out of the association's class, such as an
129
+ # STI row retyped to its base class, is no member to read a subtree for:
130
+ # the subtree can name associations only that class has.
133
131
  #: (untyped, Array[untyped], SnapshotNormalizer, Array[untyped]) -> RecordSnapshot?
134
132
  def normalized_event_record(record, route, normalizer, endpoints)
135
133
  _name, reflection, subtree, path = route.last
134
+ return unless AssociationTraversal.sti_member?(reflection.klass, record.attributes)
135
+
136
136
  @record_normalizer.call(
137
137
  record,
138
138
  reflection: reflection,
139
139
  subtree: subtree,
140
140
  path: path,
141
141
  normalizer: normalizer,
142
- root_endpoint: endpoints.fetch(0),
143
142
  context_endpoint: endpoints.fetch(1)
144
143
  )
145
144
  end
@@ -30,16 +30,17 @@ module PaperTrailDiff
30
30
  replacement if @relationship.member_of_owner?(record, reflection, owner)
31
31
  end
32
32
 
33
- #: (AssociationSnapshot, untyped, RecordSnapshot?) -> [Array[RecordSnapshot], RecordSnapshot?, RecordSnapshot?, bool]
33
+ # The collection's records after the event, with the record it took out
34
+ # and the one it put in.
35
+ #: (AssociationSnapshot, untyped, RecordSnapshot?) -> [Array[RecordSnapshot], RecordSnapshot?, RecordSnapshot?]
34
36
  def call(association, version, replacement)
35
37
  records = association.records
36
38
  position = association.position(replacement_type(version, replacement), version.item_id) ||
37
39
  retyped_position(association, version)
38
- return [records, nil, nil, true] unless replacement || position
40
+ return [records, nil, nil] unless replacement || position
39
41
 
40
42
  before = records.fetch(position) if position
41
- updated = replacement_records(records, position, replacement)
42
- [updated, before, replacement, !!before && before.identity == replacement&.identity]
43
+ [replacement_records(records, position, replacement), before, replacement]
43
44
  end
44
45
 
45
46
  #: (untyped, RecordSnapshot?) -> String
@@ -66,16 +67,25 @@ module PaperTrailDiff
66
67
  nil
67
68
  end
68
69
 
70
+ # A record that keeps its identity keeps its place. Any other, one that
71
+ # joined or a row whose type changed, goes where its identity sorts, so
72
+ # the records stay in the order a snapshot holds them in without being
73
+ # sorted again for each event.
69
74
  #: (Array[RecordSnapshot], Integer?, RecordSnapshot?) -> Array[RecordSnapshot]
70
75
  def replacement_records(records, position, replacement)
71
76
  updated = records.dup
72
- if replacement
73
- position ? updated[position] = replacement : updated << replacement
77
+ if replacement && position && updated.fetch(position).identity == replacement.identity
78
+ updated[position] = replacement
74
79
  else
75
- position ||= raise(ConfigurationError, 'missing collection event identity')
76
- updated.delete_at(position)
80
+ updated.delete_at(position) if position
81
+ insert(updated, replacement) if replacement
77
82
  end
78
83
  updated.freeze
79
84
  end
85
+
86
+ #: (Array[RecordSnapshot], RecordSnapshot) -> void
87
+ def insert(records, record)
88
+ records.insert(CollectionIdentityIndex.new(records).insertion(record.type, record.id), record)
89
+ end
80
90
  end
81
91
  end
@@ -12,21 +12,14 @@ module PaperTrailDiff
12
12
  end
13
13
 
14
14
  #: (RecordSnapshot, ActivityCollectionRouteChange, ?depth: Integer) -> [RecordSnapshot, bool]
15
- def call(snapshot, change, depth: 0) # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
15
+ def call(snapshot, change, depth: 0) # rubocop:disable Metrics/AbcSize
16
16
  name, _reflection, _subtree, path = change.route.fetch(depth)
17
17
  association = snapshot.associations.fetch(name)
18
- transition = updated_records(association, snapshot, change, depth)
19
- records, before, after, membership_preserved, changed = transition
18
+ records, before, after, changed = updated_records(association, snapshot, change, depth)
20
19
  return [snapshot, false] unless changed
21
20
 
22
21
  updated_association = @pool.association(
23
- path,
24
- association.transition_to(
25
- records,
26
- before: before,
27
- after: after,
28
- membership_preserved: membership_preserved
29
- )
22
+ path, association.transition_to(records, before: before, after: after)
30
23
  )
31
24
  updated_snapshot = snapshot.with_association(name, updated_association)
32
25
  parent_path = depth.zero? ? '' : change.route.fetch(depth - 1).fetch(3)
@@ -40,27 +33,21 @@ module PaperTrailDiff
40
33
  # @rbs @relationship: ActivityRelationship
41
34
  # @rbs @record_updater: ActivityCollectionRecordUpdater
42
35
 
43
- #: (AssociationSnapshot, RecordSnapshot, ActivityCollectionRouteChange, Integer) -> [Array[RecordSnapshot], RecordSnapshot?, RecordSnapshot?, bool, bool]
36
+ # The association's records after the change, the record it took out and
37
+ # the one it put in, and whether anything changed.
38
+ #: (AssociationSnapshot, RecordSnapshot, ActivityCollectionRouteChange, Integer) -> [Array[RecordSnapshot], RecordSnapshot?, RecordSnapshot?, bool]
44
39
  def updated_records(association, owner, change, depth)
45
40
  return leaf_records(association, owner, change) if depth == change.route.length - 1
46
41
 
47
- targeted = targeted_parent(association, change, depth)
48
- if targeted
49
- records, before, after, changed = targeted
50
- return [records, before, after, true, changed]
51
- end
52
-
53
- recursive_records(association, change, depth)
42
+ targeted_parent(association, change, depth) || recursive_records(association, change, depth)
54
43
  end
55
44
 
56
- #: (AssociationSnapshot, RecordSnapshot, ActivityCollectionRouteChange) -> [Array[RecordSnapshot], RecordSnapshot?, RecordSnapshot?, bool, bool]
45
+ #: (AssociationSnapshot, RecordSnapshot, ActivityCollectionRouteChange) -> [Array[RecordSnapshot], RecordSnapshot?, RecordSnapshot?, bool]
57
46
  def leaf_records(association, owner, change)
58
47
  reflection = change.route.last.fetch(1)
59
48
  child = @record_updater.event_child(association, change, reflection, owner)
60
- records, before, after, preserved = @record_updater.call(
61
- association, change.version, child
62
- )
63
- [records, before, after, preserved, !records.equal?(association.records)]
49
+ records, before, after = @record_updater.call(association, change.version, child)
50
+ [records, before, after, !records.equal?(association.records)]
64
51
  end
65
52
 
66
53
  #: (AssociationSnapshot, ActivityCollectionRouteChange, Integer) -> [Array[RecordSnapshot], RecordSnapshot?, RecordSnapshot?, bool]?
@@ -76,7 +63,7 @@ module PaperTrailDiff
76
63
  targeted_parent_replacement(association.records, position, before, after, changed)
77
64
  end
78
65
 
79
- #: (AssociationSnapshot, ActivityCollectionRouteChange, Integer) -> [Array[RecordSnapshot], RecordSnapshot?, RecordSnapshot?, bool, bool]
66
+ #: (AssociationSnapshot, ActivityCollectionRouteChange, Integer) -> [Array[RecordSnapshot], RecordSnapshot?, RecordSnapshot?, bool]
80
67
  def recursive_records(association, change, depth)
81
68
  state = [nil, nil, false] #: [RecordSnapshot?, RecordSnapshot?, bool]
82
69
  records = association.records.map do |child|
@@ -84,7 +71,7 @@ module PaperTrailDiff
84
71
  state = recursive_transition(state, child, updated, child_changed)
85
72
  updated
86
73
  end.freeze
87
- [records, state.fetch(0), state.fetch(1), true, state.fetch(2)]
74
+ [records, state.fetch(0), state.fetch(1), state.fetch(2)]
88
75
  end
89
76
 
90
77
  #: ([RecordSnapshot?, RecordSnapshot?, bool], RecordSnapshot, RecordSnapshot, bool) -> [RecordSnapshot?, RecordSnapshot?, bool]