paper_trail_diff 0.13.1 → 0.15.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 (181) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +630 -0
  3. data/QUICKSTART.md +30 -10
  4. data/README.md +91 -13
  5. data/docs/architecture.md +62 -18
  6. data/docs/performance.md +116 -298
  7. data/docs/reference.md +554 -102
  8. data/docs/testing.md +93 -14
  9. data/lib/paper_trail_diff/activity_belongs_to_event_applier.rb +19 -9
  10. data/lib/paper_trail_diff/activity_boundary.rb +83 -26
  11. data/lib/paper_trail_diff/activity_child_candidate_loader.rb +2 -1
  12. data/lib/paper_trail_diff/activity_collection_event_applier.rb +11 -1
  13. data/lib/paper_trail_diff/activity_collection_record_updater.rb +16 -2
  14. data/lib/paper_trail_diff/activity_event.rb +41 -10
  15. data/lib/paper_trail_diff/activity_event_record_resolver.rb +20 -1
  16. data/lib/paper_trail_diff/activity_event_route_finder.rb +2 -1
  17. data/lib/paper_trail_diff/activity_event_snapshot_refresher.rb +1 -1
  18. data/lib/paper_trail_diff/activity_history.rb +34 -9
  19. data/lib/paper_trail_diff/activity_range.rb +32 -5
  20. data/lib/paper_trail_diff/activity_relationship.rb +12 -0
  21. data/lib/paper_trail_diff/activity_root_snapshot_refresher.rb +5 -2
  22. data/lib/paper_trail_diff/activity_snapshot_sequence.rb +76 -37
  23. data/lib/paper_trail_diff/activity_target_candidate_loader.rb +131 -0
  24. data/lib/paper_trail_diff/activity_timeline_builder.rb +281 -120
  25. data/lib/paper_trail_diff/activity_transaction_grouper.rb +2 -1
  26. data/lib/paper_trail_diff/activity_tree_filter.rb +114 -0
  27. data/lib/paper_trail_diff/activity_version_collector.rb +37 -24
  28. data/lib/paper_trail_diff/activity_view.rb +69 -0
  29. data/lib/paper_trail_diff/analysis.rb +13 -1
  30. data/lib/paper_trail_diff/analysis_batch.rb +24 -30
  31. data/lib/paper_trail_diff/approximate_paths.rb +48 -0
  32. data/lib/paper_trail_diff/association_activity_edge.rb +236 -0
  33. data/lib/paper_trail_diff/association_activity_selection.rb +197 -0
  34. data/lib/paper_trail_diff/association_discovery.rb +14 -11
  35. data/lib/paper_trail_diff/association_key.rb +56 -0
  36. data/lib/paper_trail_diff/association_traversal.rb +180 -47
  37. data/lib/paper_trail_diff/batch_boundary_resolver.rb +3 -4
  38. data/lib/paper_trail_diff/batch_preload.rb +53 -0
  39. data/lib/paper_trail_diff/batched_root_analyzer.rb +12 -14
  40. data/lib/paper_trail_diff/batched_root_versions.rb +53 -47
  41. data/lib/paper_trail_diff/change_row.rb +133 -0
  42. data/lib/paper_trail_diff/collection_comparator.rb +5 -32
  43. data/lib/paper_trail_diff/comparison_batch.rb +37 -10
  44. data/lib/paper_trail_diff/configuration.rb +35 -12
  45. data/lib/paper_trail_diff/deleted_analysis_batch.rb +45 -27
  46. data/lib/paper_trail_diff/deleted_root_filter.rb +79 -0
  47. data/lib/paper_trail_diff/deprecation.rb +61 -0
  48. data/lib/paper_trail_diff/diagnostics.rb +105 -102
  49. data/lib/paper_trail_diff/direct_record_state_loader.rb +10 -1
  50. data/lib/paper_trail_diff/endpoint.rb +26 -3
  51. data/lib/paper_trail_diff/errors.rb +5 -2
  52. data/lib/paper_trail_diff/fallback_paths.rb +38 -0
  53. data/lib/paper_trail_diff/habtm_transaction_owners.rb +68 -0
  54. data/lib/paper_trail_diff/historical_association_reifier.rb +34 -6
  55. data/lib/paper_trail_diff/historical_filter.rb +19 -10
  56. data/lib/paper_trail_diff/historical_snapshot_store.rb +63 -76
  57. data/lib/paper_trail_diff/live_endpoint_batch_loader.rb +12 -13
  58. data/lib/paper_trail_diff/live_graph_collector.rb +1 -1
  59. data/lib/paper_trail_diff/nested_comparator.rb +19 -18
  60. data/lib/paper_trail_diff/paper_trail_adapter.rb +136 -125
  61. data/lib/paper_trail_diff/preloaded_endpoint_batch_loader.rb +14 -2
  62. data/lib/paper_trail_diff/prepared_activity_index.rb +110 -36
  63. data/lib/paper_trail_diff/prepared_edge_loader.rb +31 -46
  64. data/lib/paper_trail_diff/prepared_history.rb +70 -53
  65. data/lib/paper_trail_diff/prepared_history_loader.rb +34 -43
  66. data/lib/paper_trail_diff/prepared_record_index.rb +64 -7
  67. data/lib/paper_trail_diff/prepared_snapshot_builder.rb +1 -1
  68. data/lib/paper_trail_diff/prepared_state_association_reader.rb +119 -29
  69. data/lib/paper_trail_diff/recorded_changes.rb +83 -0
  70. data/lib/paper_trail_diff/recorded_class.rb +53 -0
  71. data/lib/paper_trail_diff/root_version_selection.rb +4 -2
  72. data/lib/paper_trail_diff/scope_condition.rb +386 -0
  73. data/lib/paper_trail_diff/scope_ranking.rb +206 -0
  74. data/lib/paper_trail_diff/scoped_analysis.rb +11 -0
  75. data/lib/paper_trail_diff/scoped_analysis_builder.rb +20 -11
  76. data/lib/paper_trail_diff/scoped_root_selection.rb +105 -49
  77. data/lib/paper_trail_diff/snapshot.rb +16 -1
  78. data/lib/paper_trail_diff/snapshot_normalizer.rb +10 -3
  79. data/lib/paper_trail_diff/support.rb +38 -6
  80. data/lib/paper_trail_diff/time_range.rb +37 -18
  81. data/lib/paper_trail_diff/time_version_range.rb +5 -5
  82. data/lib/paper_trail_diff/timeline_builder.rb +7 -7
  83. data/lib/paper_trail_diff/timeline_range.rb +9 -1
  84. data/lib/paper_trail_diff/timeline_snapshot_provider.rb +24 -17
  85. data/lib/paper_trail_diff/transaction_cut.rb +181 -0
  86. data/lib/paper_trail_diff/traversal_preparer.rb +134 -29
  87. data/lib/paper_trail_diff/version.rb +1 -1
  88. data/lib/paper_trail_diff/version_association_candidate_scope.rb +13 -3
  89. data/lib/paper_trail_diff/version_boundary.rb +37 -8
  90. data/lib/paper_trail_diff/version_query.rb +34 -10
  91. data/lib/paper_trail_diff/version_range.rb +8 -15
  92. data/lib/paper_trail_diff/version_scope_filter.rb +20 -13
  93. data/lib/paper_trail_diff/version_sequence_diagnostics.rb +31 -16
  94. data/lib/paper_trail_diff/version_table.rb +60 -0
  95. data/lib/paper_trail_diff.rb +126 -55
  96. data/sig/generated/paper_trail_diff/activity_belongs_to_event_applier.rbs +10 -2
  97. data/sig/generated/paper_trail_diff/activity_boundary.rbs +54 -19
  98. data/sig/generated/paper_trail_diff/activity_collection_event_applier.rbs +5 -0
  99. data/sig/generated/paper_trail_diff/activity_collection_record_updater.rbs +5 -0
  100. data/sig/generated/paper_trail_diff/activity_event.rbs +25 -4
  101. data/sig/generated/paper_trail_diff/activity_event_record_resolver.rbs +7 -0
  102. data/sig/generated/paper_trail_diff/activity_history.rbs +21 -6
  103. data/sig/generated/paper_trail_diff/activity_range.rbs +14 -3
  104. data/sig/generated/paper_trail_diff/activity_relationship.rbs +3 -0
  105. data/sig/generated/paper_trail_diff/activity_root_snapshot_refresher.rbs +2 -0
  106. data/sig/generated/paper_trail_diff/activity_snapshot_sequence.rbs +48 -9
  107. data/sig/generated/paper_trail_diff/activity_target_candidate_loader.rbs +79 -0
  108. data/sig/generated/paper_trail_diff/activity_timeline_builder.rbs +138 -28
  109. data/sig/generated/paper_trail_diff/activity_tree_filter.rbs +73 -0
  110. data/sig/generated/paper_trail_diff/activity_version_collector.rbs +12 -4
  111. data/sig/generated/paper_trail_diff/activity_view.rbs +42 -0
  112. data/sig/generated/paper_trail_diff/analysis.rbs +8 -1
  113. data/sig/generated/paper_trail_diff/analysis_batch.rbs +8 -15
  114. data/sig/generated/paper_trail_diff/approximate_paths.rbs +23 -0
  115. data/sig/generated/paper_trail_diff/association_activity_edge.rbs +148 -0
  116. data/sig/generated/paper_trail_diff/association_activity_selection.rbs +112 -0
  117. data/sig/generated/paper_trail_diff/association_discovery.rbs +8 -5
  118. data/sig/generated/paper_trail_diff/association_key.rbs +29 -0
  119. data/sig/generated/paper_trail_diff/association_traversal.rbs +88 -9
  120. data/sig/generated/paper_trail_diff/batch_preload.rbs +29 -0
  121. data/sig/generated/paper_trail_diff/batched_root_analyzer.rbs +9 -10
  122. data/sig/generated/paper_trail_diff/batched_root_versions.rbs +14 -10
  123. data/sig/generated/paper_trail_diff/change_row.rbs +86 -0
  124. data/sig/generated/paper_trail_diff/collection_comparator.rbs +2 -16
  125. data/sig/generated/paper_trail_diff/comparison_batch.rbs +22 -4
  126. data/sig/generated/paper_trail_diff/configuration.rbs +19 -3
  127. data/sig/generated/paper_trail_diff/deleted_analysis_batch.rbs +20 -8
  128. data/sig/generated/paper_trail_diff/deleted_root_filter.rbs +48 -0
  129. data/sig/generated/paper_trail_diff/deprecation.rbs +35 -0
  130. data/sig/generated/paper_trail_diff/diagnostics.rbs +44 -32
  131. data/sig/generated/paper_trail_diff/direct_record_state_loader.rbs +6 -0
  132. data/sig/generated/paper_trail_diff/endpoint.rbs +11 -2
  133. data/sig/generated/paper_trail_diff/errors.rbs +5 -2
  134. data/sig/generated/paper_trail_diff/fallback_paths.rbs +22 -0
  135. data/sig/generated/paper_trail_diff/habtm_transaction_owners.rbs +40 -0
  136. data/sig/generated/paper_trail_diff/historical_association_reifier.rbs +13 -0
  137. data/sig/generated/paper_trail_diff/historical_filter.rbs +12 -2
  138. data/sig/generated/paper_trail_diff/historical_snapshot_store.rbs +36 -30
  139. data/sig/generated/paper_trail_diff/live_endpoint_batch_loader.rbs +5 -3
  140. data/sig/generated/paper_trail_diff/nested_comparator.rbs +10 -7
  141. data/sig/generated/paper_trail_diff/paper_trail_adapter.rbs +55 -48
  142. data/sig/generated/paper_trail_diff/preloaded_endpoint_batch_loader.rbs +9 -1
  143. data/sig/generated/paper_trail_diff/prepared_activity_index.rbs +52 -10
  144. data/sig/generated/paper_trail_diff/prepared_edge_loader.rbs +4 -12
  145. data/sig/generated/paper_trail_diff/prepared_history.rbs +40 -24
  146. data/sig/generated/paper_trail_diff/prepared_history_loader.rbs +15 -13
  147. data/sig/generated/paper_trail_diff/prepared_record_index.rbs +34 -2
  148. data/sig/generated/paper_trail_diff/prepared_state_association_reader.rbs +56 -11
  149. data/sig/generated/paper_trail_diff/recorded_changes.rbs +47 -0
  150. data/sig/generated/paper_trail_diff/recorded_class.rbs +22 -0
  151. data/sig/generated/paper_trail_diff/root_version_selection.rbs +2 -0
  152. data/sig/generated/paper_trail_diff/scope_condition.rbs +219 -0
  153. data/sig/generated/paper_trail_diff/scope_ranking.rbs +125 -0
  154. data/sig/generated/paper_trail_diff/scoped_analysis.rbs +6 -0
  155. data/sig/generated/paper_trail_diff/scoped_analysis_builder.rbs +8 -3
  156. data/sig/generated/paper_trail_diff/scoped_root_selection.rbs +49 -11
  157. data/sig/generated/paper_trail_diff/snapshot.rbs +8 -0
  158. data/sig/generated/paper_trail_diff/snapshot_normalizer.rbs +6 -0
  159. data/sig/generated/paper_trail_diff/support.rbs +20 -2
  160. data/sig/generated/paper_trail_diff/time_range.rbs +20 -2
  161. data/sig/generated/paper_trail_diff/time_version_range.rbs +4 -4
  162. data/sig/generated/paper_trail_diff/timeline_builder.rbs +2 -2
  163. data/sig/generated/paper_trail_diff/timeline_range.rbs +2 -0
  164. data/sig/generated/paper_trail_diff/timeline_snapshot_provider.rbs +17 -7
  165. data/sig/generated/paper_trail_diff/transaction_cut.rbs +94 -0
  166. data/sig/generated/paper_trail_diff/traversal_preparer.rbs +66 -8
  167. data/sig/generated/paper_trail_diff/version_association_candidate_scope.rbs +7 -0
  168. data/sig/generated/paper_trail_diff/version_boundary.rbs +20 -3
  169. data/sig/generated/paper_trail_diff/version_query.rbs +18 -2
  170. data/sig/generated/paper_trail_diff/version_range.rbs +4 -2
  171. data/sig/generated/paper_trail_diff/version_scope_filter.rbs +7 -4
  172. data/sig/generated/paper_trail_diff/version_sequence_diagnostics.rbs +16 -9
  173. data/sig/generated/paper_trail_diff/version_table.rbs +30 -0
  174. data/sig/generated/paper_trail_diff.rbs +47 -25
  175. metadata +62 -10
  176. data/lib/paper_trail_diff/activity_grouping.rb +0 -38
  177. data/lib/paper_trail_diff/batch_safety.rb +0 -55
  178. data/lib/paper_trail_diff/time_activity_timeline_builder.rb +0 -224
  179. data/sig/generated/paper_trail_diff/activity_grouping.rbs +0 -22
  180. data/sig/generated/paper_trail_diff/batch_safety.rbs +0 -24
  181. data/sig/generated/paper_trail_diff/time_activity_timeline_builder.rbs +0 -92
@@ -4,12 +4,11 @@
4
4
  module PaperTrailDiff
5
5
  # Collects root and selected-descendant versions relevant to one root history range.
6
6
  class ActivityVersionCollector
7
- #: (untyped, root_versions: Array[untyped], tree: AssociationTree, traversal: AssociationTraversal, ?range_start: untyped, ?range_end: untyped, ?prepared: PreparedActivityIndex?) -> void
7
+ #: (untyped, root_versions: Array[untyped], tree: AssociationTree, ?range_start: untyped, ?range_end: untyped, ?prepared: PreparedActivityIndex?) -> void
8
8
  def initialize( # rubocop:disable Metrics/ParameterLists
9
9
  record,
10
10
  root_versions:,
11
11
  tree:,
12
- traversal:,
13
12
  range_start: root_versions.first,
14
13
  range_end: root_versions.last,
15
14
  prepared: nil
@@ -18,18 +17,20 @@ module PaperTrailDiff
18
17
  @record = record
19
18
  @root_versions = root_versions
20
19
  @tree = tree
21
- @traversal = traversal
20
+ @traversal = AssociationTraversal.new(tree)
22
21
  @range = ActivityRange.new(range_start, range_end)
23
22
  @registry = ActivityEventRegistry.new
24
23
  end
25
24
 
25
+ # A tie between version tables, or between ids that do not count up,
26
+ # raises rather than building a timeline in an arbitrary order.
26
27
  #: () -> Array[ActivityEvent]
27
28
  def call
28
29
  @registry.add(@root_versions)
29
30
  collect_tree(@record.class, [@record.id], @tree, path: '', branch: nil) unless @tree.empty?
30
- @registry.to_a.sort_by do |event|
31
- Support.chronological_version_key(event.version)
32
- end.freeze
31
+ events = @registry.to_a.sort_by { |event| Support.chronological_version_key(event.version) }
32
+ pair = Support.ambiguous_pair(events.map(&:version))
33
+ pair ? raise(AmbiguousVersionOrderError, Support.ambiguous_message(pair)) : events.freeze
33
34
  end
34
35
 
35
36
  private
@@ -62,7 +63,7 @@ module PaperTrailDiff
62
63
  @registry.add(group.fetch(:versions), branch: branch)
63
64
  next if subtree.empty?
64
65
 
65
- child_path = Support.association_path(path, reflection.name.to_s)
66
+ child_path = Support.association_path(path, reflection.name)
66
67
  collect_tree(group.fetch(:model), group.fetch(:ids), subtree,
67
68
  path: child_path, branch: branch)
68
69
  end
@@ -74,7 +75,7 @@ module PaperTrailDiff
74
75
 
75
76
  case reflection.macro
76
77
  when :belongs_to
77
- belongs_to_groups(parent.fetch(:model), parent.fetch(:versions), reflection)
78
+ belongs_to_groups(parent.fetch(:model), parent.fetch(:ids), reflection)
78
79
  when :has_one, :has_many
79
80
  direct_child_groups(parent.fetch(:model), parent.fetch(:ids), reflection)
80
81
  when :has_and_belongs_to_many
@@ -90,24 +91,35 @@ module PaperTrailDiff
90
91
  intermediate = edge_groups(parent, through, branch)
91
92
  result = {} #: Hash[String, untyped]
92
93
  intermediate.each_value do |group|
93
- @registry.add(group.fetch(:versions), branch: branch)
94
+ # A through is always read with prepared history, which knows the
95
+ # join row's state either side of each version.
96
+ @registry.add(@prepared&.join_versions(group, reflection) || group.fetch(:versions),
97
+ branch: branch, join: true)
94
98
  source = reflection.source_reflection
95
99
  children = edge_groups(group, source, branch)
96
100
  merge_groups!(result, children)
97
101
  end
98
- result
102
+ # Under `source_type:`, only targets of that type are members.
103
+ reflection.options[:source_type]&.then { |type| result.slice(type.to_s) } || result
99
104
  end
100
105
 
106
+ # Every target the owners pointed at in the range, not only those their own
107
+ # changes there recorded: an author renamed under an article nobody edited
108
+ # is still that article's activity.
101
109
  #: (untyped, Array[untyped], untyped) -> Hash[String, untyped]
102
- def belongs_to_groups(parent_class, parent_versions, reflection)
103
- if (prepared = @prepared)
104
- rows = prepared.association_rows(parent_class, parent_versions, reflection)
105
- return identity_groups(rows, reflection)
106
- end
107
- rows = parent_class.paper_trail.version_association_class.where(
108
- version_id: parent_versions.map(&:id),
109
- foreign_key_name: reflection.foreign_key.to_s
110
- ).to_a
110
+ def belongs_to_groups(parent_class, parent_ids, reflection)
111
+ prepared = @prepared
112
+ return unprepared_belongs_to_groups(parent_class, parent_ids, reflection) unless prepared
113
+
114
+ # Prepared history holds every target its snapshots can contain. One it
115
+ # did not load -- a key changed without a version -- has no state to compare.
116
+ rows = prepared.target_rows(parent_class, parent_ids, reflection, @range)
117
+ identity_groups(rows, reflection) { |model_class, id| prepared.loaded?(model_class, id) }
118
+ end
119
+
120
+ #: (untyped, Array[untyped], untyped) -> Hash[String, untyped]
121
+ def unprepared_belongs_to_groups(parent_class, parent_ids, reflection)
122
+ rows = ActivityTargetCandidateLoader.new(parent_class, parent_ids, reflection, @range).call
111
123
  identity_groups(rows, reflection)
112
124
  end
113
125
 
@@ -127,12 +139,11 @@ module PaperTrailDiff
127
139
  #: (untyped, Array[untyped], untyped) -> Hash[String, untyped]
128
140
  def habtm_groups(parent_class, parent_versions, reflection)
129
141
  if (prepared = @prepared)
130
- rows = prepared.association_rows(parent_class, parent_versions, reflection,
131
- transactions: true)
142
+ rows = prepared.habtm_rows(parent_class, parent_versions, reflection)
132
143
  return identity_groups(rows, reflection)
133
144
  end
134
145
  transaction_ids = parent_versions.filter_map do |version|
135
- version.transaction_id if version.respond_to?(:transaction_id)
146
+ VersionBoundary.transaction_id(version)
136
147
  end
137
148
  rows = parent_class.paper_trail.version_association_class.where(
138
149
  version_id: transaction_ids,
@@ -141,7 +152,7 @@ module PaperTrailDiff
141
152
  identity_groups(rows, reflection)
142
153
  end
143
154
 
144
- #: (Array[untyped], untyped) -> Hash[String, untyped]
155
+ #: (Array[untyped], untyped) ?{ (untyped, untyped) -> bool } -> Hash[String, untyped]
145
156
  def identity_groups(rows, reflection)
146
157
  identities = rows.group_by { |row| target_class(reflection, row) }
147
158
  groups = {} #: Hash[String, untyped]
@@ -149,6 +160,7 @@ module PaperTrailDiff
149
160
  next unless model_class
150
161
 
151
162
  ids = class_rows.filter_map(&:foreign_key_id).uniq
163
+ ids = ids.select { |id| yield(model_class, id) } if block_given?
152
164
  groups[model_class.name] = group(model_class, ids)
153
165
  end
154
166
  groups
@@ -156,6 +168,7 @@ module PaperTrailDiff
156
168
 
157
169
  #: (untyped, Array[untyped]) -> Hash[Symbol, untyped]
158
170
  def group(model_class, ids)
171
+ ids = @prepared&.member_ids(model_class, ids) || ids
159
172
  { model: model_class, ids: ids, versions: versions_for(model_class, ids) }
160
173
  end
161
174
 
@@ -178,7 +191,7 @@ module PaperTrailDiff
178
191
  return [] if ids.empty?
179
192
 
180
193
  if (prepared = @prepared)
181
- return prepared.versions(model_class, ids).select { |version| @range.include?(version) }
194
+ return prepared.member_versions(model_class, ids, @range)
182
195
  end
183
196
 
184
197
  version_class = model_class.paper_trail.version_class
@@ -0,0 +1,69 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ module PaperTrailDiff
5
+ # How a request presents its activity steps: whether they keep their
6
+ # snapshots, whether a transaction's steps merge into one, and which of
7
+ # their versions' recorded changes they carry. Built and checked once per
8
+ # request, and read the same way by both activity builders, or the same
9
+ # history would read differently depending on how it was asked for.
10
+ class ActivityView
11
+ # Options only an activity view uses are refused without one.
12
+ #: (activity: bool, snapshots: bool, group: Symbol?, recorded: IgnorePolicy?) -> ActivityView
13
+ def self.build(activity:, snapshots:, group:, recorded:)
14
+ view = new(snapshots: snapshots, group: group, recorded: recorded)
15
+ return view if activity
16
+
17
+ { snapshots: snapshots, recorded_changes: !recorded.nil?, group: !group.nil? }
18
+ .each do |name, given|
19
+ raise ConfigurationError, "#{name}: requires activity: true" if given
20
+ end
21
+ view
22
+ end
23
+
24
+ #: (?snapshots: bool, ?group: Symbol?, ?recorded: IgnorePolicy?) -> void
25
+ def initialize(snapshots: false, group: nil, recorded: nil)
26
+ unless group.nil? || group == :transaction
27
+ raise ConfigurationError, 'group: must be :transaction or nil'
28
+ end
29
+
30
+ @snapshots = snapshots
31
+ @group = group
32
+ @recorded = recorded
33
+ freeze
34
+ end
35
+
36
+ # Merging a group compares its outer states, so the snapshots must survive
37
+ # the build even when the caller did not ask to keep them.
38
+ #: () -> bool
39
+ def retain?
40
+ @snapshots || grouping?
41
+ end
42
+
43
+ # The attributes a boundary's version recorded, when they were asked for.
44
+ #: (root: bool) -> Array[String]?
45
+ def recorded_attributes(root:)
46
+ @recorded&.recorded_attributes(root: root)
47
+ end
48
+
49
+ # Applied last, to finished steps, so grouping sees the same timeline the
50
+ # caller would otherwise have received.
51
+ #: (Array[ActivityStep]) -> Array[ActivityStep]
52
+ def present(steps)
53
+ return steps unless grouping?
54
+
55
+ ActivityTransactionGrouper.new(steps, retain: @snapshots).call
56
+ end
57
+
58
+ private
59
+
60
+ # @rbs @snapshots: bool
61
+ # @rbs @group: Symbol?
62
+ # @rbs @recorded: IgnorePolicy?
63
+
64
+ #: () -> bool
65
+ def grouping?
66
+ @group == :transaction
67
+ end
68
+ end
69
+ end
@@ -11,7 +11,9 @@ module PaperTrailDiff
11
11
  attr_reader :to_snapshot #: RecordSnapshot?
12
12
 
13
13
  # The result for a record whose requested history contains no versions,
14
- # which is an empty history rather than a failed request.
14
+ # which is an empty history rather than a failed request. Its snapshots
15
+ # are nil because no state was read, not because the record was absent:
16
+ # reading one would rebuild the whole graph, per record in a batch.
15
17
  #: () -> Analysis
16
18
  def self.empty
17
19
  timeline = [] #: Array[Step]
@@ -31,6 +33,16 @@ module PaperTrailDiff
31
33
  freeze
32
34
  end
33
35
 
36
+ # Every activity step's rows, in time order. Only the activity timeline says
37
+ # who made each change, so an analysis built without it has no rows to give.
38
+ #: () -> Array[ChangeRow]
39
+ def change_rows
40
+ steps = activity_timeline
41
+ raise ConfigurationError, 'change_rows requires activity: true' unless steps
42
+
43
+ steps.flat_map(&:change_rows).freeze
44
+ end
45
+
34
46
  # Reconstructed endpoint states are opt-in, because they carry the whole
35
47
  # selected graph whether or not anything changed, which dwarfs the rest of
36
48
  # the payload for a wide graph.
@@ -6,16 +6,16 @@ module PaperTrailDiff
6
6
  # versions and preparing their association history once for the whole batch
7
7
  # rather than once per root.
8
8
  class AnalysisBatch
9
- #: (Array[untyped], time_range: TimeRange?, live_loader: untyped, history_preparer: untyped, analyzer: untyped, ?version_scope: untyped, ?close_on_current: bool, ?context_required: bool) -> void
9
+ #: (Array[untyped], time_range: TimeRange?, live_loader: untyped, history_preparer: untyped, analyzer: untyped, ?version_scope: untyped, ?context_required: bool) -> void
10
10
  def initialize( # rubocop:disable Metrics/ParameterLists
11
11
  records, time_range:, live_loader:, history_preparer:, analyzer:, version_scope: nil,
12
- close_on_current: false, context_required: false
12
+ context_required: false
13
13
  )
14
14
  @records = records
15
15
  @context_required = context_required
16
16
  @time_range = time_range
17
- @version_scope = validated_scope(version_scope)
18
- @close_on_current = close_on_current
17
+ # Checked up front rather than failing partway through a batch.
18
+ @version_scope = VersionScopeFilter.validated(version_scope)
19
19
  @live_loader = live_loader
20
20
  @history_preparer = history_preparer
21
21
  @analyzer = analyzer
@@ -25,16 +25,17 @@ module PaperTrailDiff
25
25
  def call
26
26
  records = validated_records
27
27
  loaded = @live_loader.call(records)
28
+ windows = TransactionCut.batch_windows(records, @time_range)
28
29
  selected = BatchedRootVersions.new(
29
30
  records, time_range: @time_range, version_scope: @version_scope,
30
- live_endpoints: (loaded if @close_on_current),
31
- context_required: @context_required
31
+ live_endpoints: loaded,
32
+ context_required: @context_required, windows: windows
32
33
  ).call
33
- prepare(records, selected, loaded)
34
+ prepare(records, selected, loaded, windows)
34
35
  records.to_h do |record|
35
36
  key = Endpoint.identity(record)
36
37
  plan = selected.fetch(key, RootVersionPlan.empty)
37
- [Support.immutable_copy(key), analysis_for(record, plan)]
38
+ [Support.immutable_copy(key), analysis_for(record, plan, windows.fetch(key, @time_range))]
38
39
  end.freeze
39
40
  end
40
41
 
@@ -43,26 +44,19 @@ module PaperTrailDiff
43
44
  # @rbs @records: Array[untyped]
44
45
  # @rbs @time_range: TimeRange?
45
46
  # @rbs @version_scope: untyped
46
- # @rbs @close_on_current: bool
47
47
  # @rbs @context_required: bool
48
48
  # @rbs @live_loader: untyped
49
49
  # @rbs @history_preparer: untyped
50
50
  # @rbs @analyzer: untyped
51
51
 
52
- # A filter is a callable that narrows the version relation, so it is checked
53
- # up front rather than failing partway through a batch.
54
- #: (untyped) -> untyped
55
- def validated_scope(scope)
56
- return scope if scope.nil? || scope.respond_to?(:call)
57
-
58
- raise ConfigurationError, 'version_scope: must respond to call'
59
- end
60
-
61
52
  #: () -> Array[untyped]
62
53
  def validated_records
63
54
  raise ConfigurationError, 'records: must be an array' unless @records.is_a?(Array)
64
55
 
65
- @records.each { |record| Endpoint.validate!(record) }
56
+ @records.each do |record|
57
+ Endpoint.validate_root!(record)
58
+ Endpoint.validate!(record)
59
+ end
66
60
  identities = @records.map { |record| Endpoint.identity(record) }
67
61
  return @records if identities.uniq.length == identities.length
68
62
 
@@ -74,8 +68,8 @@ module PaperTrailDiff
74
68
  # The roots are preloaded first, because preparation reads their current
75
69
  # association state as a fallback and would otherwise walk it one root at a
76
70
  # time.
77
- #: (Array[untyped], Hash[Array[String], RootVersionPlan], Hash[Array[String], untyped]) -> void
78
- def prepare(records, selected, loaded)
71
+ #: (Array[untyped], Hash[Array[String], RootVersionPlan], Hash[Array[String], untyped], Hash[Array[String], TimeRange]) -> void
72
+ def prepare(records, selected, loaded, windows)
79
73
  records.group_by(&:class).each_value do |grouped|
80
74
  versions = grouped.flat_map do |record|
81
75
  selected.fetch(Endpoint.identity(record), RootVersionPlan.empty).reconstruction_versions
@@ -84,7 +78,7 @@ module PaperTrailDiff
84
78
 
85
79
  roots = grouped.map { |record| loaded.fetch(Endpoint.identity(record), record) }
86
80
  live = closes_live?(grouped, selected)
87
- @history_preparer.call(roots, versions, **preparation_range(versions, live: live))
81
+ @history_preparer.call(roots, versions, **preparation_range(versions, windows, live: live))
88
82
  end
89
83
  end
90
84
 
@@ -97,21 +91,21 @@ module PaperTrailDiff
97
91
 
98
92
  # A plan closing on the live record reads history up to now; the others
99
93
  # stop at the window, so a past window does not load everything since.
100
- #: (Array[untyped], ?live: bool) -> Hash[Symbol, untyped]
101
- def preparation_range(versions, live: @close_on_current)
102
- last = versions.map(&:created_at).max
103
- end_at = [last, @time_range&.end_time, (Time.now.utc if live)].compact.max
104
- { start_at: @time_range&.begin_time || versions.map(&:created_at).min, end_at: end_at }
94
+ #: (Array[untyped], Hash[Array[String], TimeRange], live: bool) -> Hash[Symbol, untyped]
95
+ def preparation_range(versions, windows, live:)
96
+ times = versions.map(&:created_at)
97
+ end_at = [times.max, @time_range&.end_time, (Time.now.utc if live)].compact.max
98
+ { start_at: TransactionCut.earliest_start(@time_range, windows) || times.min, end_at: end_at }
105
99
  end
106
100
 
107
101
  # A root with no versions in range has nothing to report, which is an empty
108
102
  # result rather than a failed request -- unless an activity view closes it
109
103
  # on current state, where its descendants may still have moved.
110
- #: (untyped, RootVersionPlan) -> Analysis
111
- def analysis_for(record, plan)
104
+ #: (untyped, RootVersionPlan, TimeRange?) -> Analysis
105
+ def analysis_for(record, plan, window)
112
106
  return Analysis.empty if plan.empty? && !plan.closing_record
113
107
 
114
- @analyzer.call(record, plan)
108
+ @analyzer.call(record, plan, window)
115
109
  end
116
110
  end
117
111
  end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ module PaperTrailDiff
5
+ # The requested paths prepared history cannot read exactly, each with why.
6
+ # PT-AT reads such a path instead, one record at a time, when the caller
7
+ # passes `allow_approximate: true`.
8
+ module ApproximatePaths
9
+ #: (AssociationTraversal, untyped) -> Array[[String, String]]
10
+ def self.call(traversal, model)
11
+ traversal.selected_reflections(model).filter_map do |path, reflection|
12
+ reason = fallback_reason(reflection, ranked: true)
13
+ [path, reason] if reason
14
+ end
15
+ end
16
+
17
+ # A has_many through reads its parts' conditions only, at any depth. A
18
+ # has_one through over a ranked part is refused whole, so its parts, too,
19
+ # are checked for conditions alone.
20
+ #: (untyped, ranked: bool) -> String?
21
+ def self.fallback_reason(reflection, ranked:)
22
+ reason = reason_for(reflection, ranked)
23
+ return reason if reason || !reflection.through_reflection?
24
+
25
+ [reflection.through_reflection, reflection.source_reflection].each do |part|
26
+ part_reason = fallback_reason(part, ranked: false)
27
+ return part_reason if part_reason
28
+ end
29
+ nil
30
+ end
31
+ private_class_method :fallback_reason
32
+
33
+ # A scope prepared history can read as conditions on stored attributes
34
+ # is batched like any other path. A polymorphic target's class, and so
35
+ # its scope, is known only per record.
36
+ #: (untyped, bool) -> String?
37
+ def self.reason_for(reflection, ranked)
38
+ return ('association scope' if reflection.scope) if reflection.polymorphic?
39
+ if ranked && ScopeCondition.ranked_through?(reflection)
40
+ return 'limit, offset or has_one order inside a has_one through'
41
+ end
42
+ return if ScopeCondition.build(reflection, ranked: ranked)
43
+
44
+ reflection.scope ? 'association scope' : 'default-scoped target'
45
+ end
46
+ private_class_method :reason_for
47
+ end
48
+ end
@@ -0,0 +1,236 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ module PaperTrailDiff
5
+ # One association edge read backwards for a window: given the ids of records
6
+ # on its far side, the query for the owners that held them while it was open.
7
+ #
8
+ # `filter_type` is the type of the column those ids are compared with, and
9
+ # `type` that of the owner column the query selects, so a caller can keep a
10
+ # subquery only where the database can compare the two.
11
+ class AssociationActivityEdge
12
+ attr_reader :column #: untyped
13
+ attr_reader :type #: Symbol?
14
+ attr_reader :filter_type #: Symbol?
15
+
16
+ #: (untyped, TimeRange?) -> void
17
+ def initialize(reflection, time_range)
18
+ @reflection = reflection
19
+ @time_range = time_range
20
+ @owner = reflection.active_record
21
+ end
22
+
23
+ #: () -> bool
24
+ def available?
25
+ !@reflection.foreign_key.is_a?(Array)
26
+ end
27
+
28
+ #: (untyped) -> untyped
29
+ def relation(_filter)
30
+ raise NotImplementedError, "#{self.class} must build its relation"
31
+ end
32
+
33
+ private
34
+
35
+ # @rbs @reflection: untyped
36
+ # @rbs @time_range: TimeRange?
37
+ # @rbs @owner: untyped
38
+
39
+ # The window plus the state when it opened, which is what
40
+ # VersionAssociationCandidateScope selects for an activity analysis.
41
+ #: (untyped, untyped) -> untyped
42
+ def candidates(versions, relation)
43
+ range = @time_range
44
+ return relation unless range
45
+
46
+ VersionAssociationCandidateScope.new(versions, range.begin_time, end_at: range.end_time)
47
+ .call(relation)
48
+ end
49
+
50
+ #: (untyped, String) -> Symbol?
51
+ def column_type(model, name)
52
+ model.type_for_attribute(name).type
53
+ end
54
+
55
+ # A relation is compared as its SQL; ids are compared as values.
56
+ #: (untyped) -> untyped
57
+ def arel_value(filter)
58
+ filter.respond_to?(:arel) ? filter.arel : filter
59
+ end
60
+
61
+ # The owners a child pointed at when the window opened or after a change
62
+ # inside it, as PT-AT recorded them on the child's own versions.
63
+ class Child < AssociationActivityEdge
64
+ #: (untyped, TimeRange?) -> void
65
+ def initialize(reflection, time_range)
66
+ super
67
+ @versions = reflection.klass.paper_trail.version_class
68
+ @associations = reflection.klass.paper_trail.version_association_class
69
+ @column = @associations.arel_table[:foreign_key_id]
70
+ @type = column_type(@associations, 'foreign_key_id')
71
+ @filter_type = column_type(@versions, 'item_id')
72
+ end
73
+
74
+ #: (untyped) -> untyped
75
+ def relation(filter)
76
+ versions = { item_type: @reflection.klass.base_class.name, item_id: filter }
77
+ relation = VersionTable.joined(@associations, @versions)
78
+ .where(foreign_key_name: @reflection.foreign_key,
79
+ foreign_type: owner_types)
80
+ .where(@versions.table_name => versions)
81
+ candidates(@versions, relation)
82
+ end
83
+
84
+ private
85
+
86
+ # @rbs @versions: untyped
87
+ # @rbs @associations: untyped
88
+
89
+ #: () -> Array[String?]
90
+ def owner_types
91
+ [nil, '', @owner.name, @owner.base_class.name]
92
+ end
93
+ end
94
+
95
+ # The owners that pointed at a target when the window opened or after a
96
+ # change inside it, as PT-AT recorded them on the owners' versions.
97
+ class BelongsTo < AssociationActivityEdge
98
+ #: (untyped, TimeRange?, ?foreign_type: String?) -> void
99
+ def initialize(reflection, time_range, foreign_type: nil)
100
+ super(reflection, time_range)
101
+ @foreign_type = foreign_type
102
+ @versions = @owner.paper_trail.version_class
103
+ @associations = @owner.paper_trail.version_association_class
104
+ @column = @versions.arel_table[:item_id]
105
+ @type = column_type(@versions, 'item_id')
106
+ @filter_type = column_type(@associations, 'foreign_key_id')
107
+ end
108
+
109
+ # The types a polymorphic key's rows name, the only way to know its targets.
110
+ #: () -> Array[String]
111
+ def target_types
112
+ candidates(@versions, owner_rows(foreign_key_name: @reflection.foreign_key))
113
+ .distinct.pluck(@associations.arel_table[:foreign_type]).compact
114
+ end
115
+
116
+ # The owners that pointed at a target of this edge's type when the window
117
+ # opened or after a change inside it, whichever target that was.
118
+ #: () -> untyped
119
+ def typed_owners
120
+ conditions = { foreign_key_name: @reflection.foreign_key, foreign_type: @foreign_type }
121
+ candidates(@versions, owner_rows(conditions)).select(@column)
122
+ end
123
+
124
+ #: (untyped) -> untyped
125
+ def relation(filter)
126
+ conditions = { foreign_key_name: @reflection.foreign_key, foreign_key_id: filter }
127
+ conditions[:foreign_type] = @foreign_type if @foreign_type
128
+ candidates(@versions, owner_rows(conditions))
129
+ end
130
+
131
+ private
132
+
133
+ # @rbs @foreign_type: String?
134
+ # @rbs @versions: untyped
135
+ # @rbs @associations: untyped
136
+
137
+ #: (Hash[Symbol, untyped]) -> untyped
138
+ def owner_rows(conditions)
139
+ VersionTable.joined(@associations, @versions).where(conditions)
140
+ .where(@versions.table_name => { item_type: @owner.base_class.name })
141
+ end
142
+ end
143
+
144
+ # The owners a HABTM join row links to a target now. A join table has no
145
+ # model to type its columns, so the owner column is read by quoted name.
146
+ class LiveHabtm < AssociationActivityEdge
147
+ #: (untyped, TimeRange?) -> void
148
+ def initialize(reflection, time_range)
149
+ super
150
+ @table = arel::Table.new(reflection.join_table)
151
+ columns = join_columns
152
+ @type = columns.fetch(reflection.foreign_key)
153
+ @filter_type = columns.fetch(reflection.association_foreign_key)
154
+ @column = quoted_owner_column
155
+ end
156
+
157
+ #: (untyped) -> untyped
158
+ def relation(filter)
159
+ target = @table[@reflection.association_foreign_key]
160
+ @owner.base_class.unscoped.from(@table).where(target.in(arel_value(filter)))
161
+ end
162
+
163
+ private
164
+
165
+ # @rbs @table: untyped
166
+
167
+ #: () -> Hash[String, Symbol?]
168
+ def join_columns
169
+ connected do |connection|
170
+ connection.columns(@reflection.join_table).to_h { |column| [column.name, column.type] }
171
+ end
172
+ end
173
+
174
+ # Some adapters take the quoted name as a plain string too, but a raw SQL
175
+ # check may not, so it is marked as SQL; no SQLite spec can tell.
176
+ # mutant:disable
177
+ #: () -> untyped
178
+ def quoted_owner_column
179
+ connected do |connection|
180
+ arel.sql("#{connection.quote_table_name(@reflection.join_table)}." \
181
+ "#{connection.quote_column_name(@reflection.foreign_key)}")
182
+ end
183
+ end
184
+
185
+ # Arel ships no signatures; see VersionQuery. Any spelling of the
186
+ # constant finds the same module.
187
+ # mutant:disable
188
+ #: () -> untyped
189
+ def arel
190
+ Object.const_get(:Arel)
191
+ end
192
+
193
+ # Active Record 7.1 has no `with_connection`; see VersionAssociationCandidateScope.
194
+ # Only that version takes the fallback, so no spec run on a newer one can
195
+ # tell its mutations apart.
196
+ # mutant:disable
197
+ #: [T] () { (untyped) -> T } -> T
198
+ def connected(&block)
199
+ return @owner.with_connection(&block) if @owner.respond_to?(:with_connection)
200
+
201
+ yield(@owner.connection)
202
+ end
203
+ end
204
+
205
+ # The owners whose versions PT-AT recorded a HABTM target with, keyed by
206
+ # the transaction each version was saved in.
207
+ class RecordedHabtm < AssociationActivityEdge
208
+ #: (untyped, TimeRange?) -> void
209
+ def initialize(reflection, time_range)
210
+ super
211
+ @versions = @owner.paper_trail.version_class
212
+ @associations = @owner.paper_trail.version_association_class
213
+ @column = @versions.arel_table[:item_id]
214
+ @type = column_type(@versions, 'item_id')
215
+ @filter_type = column_type(@associations, 'foreign_key_id')
216
+ end
217
+
218
+ #: () -> bool
219
+ def available?
220
+ @versions.column_names.include?('transaction_id')
221
+ end
222
+
223
+ #: (untyped) -> untyped
224
+ def relation(filter)
225
+ transactions = @associations.where(foreign_key_name: @reflection.name,
226
+ foreign_key_id: filter).select(:version_id)
227
+ relation = @versions.where(item_type: @owner.base_class.name, transaction_id: transactions)
228
+ range = @time_range
229
+ range ? relation.where(created_at: range.begin_time..) : relation
230
+ end
231
+
232
+ # @rbs @versions: untyped
233
+ # @rbs @associations: untyped
234
+ end
235
+ end
236
+ end