rails_why 0.1.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.
@@ -0,0 +1,298 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "prism"
4
+
5
+ module RailsWhy
6
+ class ConditionAnalyzer
7
+ # Represents a discovered conditional expression from AST
8
+ ConditionRecord = Struct.new(
9
+ :type, # :if, :unless, :case, :guard, :logical_and, :logical_or
10
+ :line, # Start line
11
+ :code, # Source snippet of the condition
12
+ :status, # :evaluated_true, :evaluated_false, :executed, :skipped, :inconclusive
13
+ :branch_taken, # :consequent, :alternative, :none, :unknown
14
+ :location, # file:line
15
+ keyword_init: true
16
+ )
17
+
18
+ def initialize(config)
19
+ @config = config
20
+ @file_cache = {}
21
+ @ast_cache = {}
22
+ end
23
+
24
+ # Analyze conditions inside a node based on executed lines and children calls
25
+ def analyze_node(node)
26
+ return [] unless @config.enable_condition_analysis
27
+ return [] unless node.path && File.file?(node.path)
28
+
29
+ file_lines = read_file_lines(node.path)
30
+ return [] if file_lines.empty?
31
+
32
+ ast = parse_ast(node.path)
33
+ return [] unless ast
34
+
35
+ visitor = ConditionVisitor.new(node.line, node.lines_hit, file_lines, node.path, @config)
36
+ visitor.visit(ast.value)
37
+ visitor.conditions
38
+ rescue StandardError => e
39
+ # AST analysis should never break runtime tracing
40
+ [
41
+ ConditionRecord.new(
42
+ type: :error,
43
+ line: node.line || 0,
44
+ code: "AST analysis skipped: #{e.message}",
45
+ status: :inconclusive,
46
+ branch_taken: :unknown,
47
+ location: "#{node.path}:#{node.line}"
48
+ )
49
+ ]
50
+ end
51
+
52
+ private
53
+
54
+ def read_file_lines(path)
55
+ @file_cache[path] ||= begin
56
+ if File.exist?(path) && File.file?(path)
57
+ File.readlines(path, chomp: false)
58
+ else
59
+ []
60
+ end
61
+ rescue StandardError
62
+ []
63
+ end
64
+ end
65
+
66
+ def parse_ast(path)
67
+ @ast_cache[path] ||= begin
68
+ if File.exist?(path) && File.file?(path)
69
+ Prism.parse_file(path)
70
+ else
71
+ nil
72
+ end
73
+ rescue StandardError
74
+ nil
75
+ end
76
+ end
77
+
78
+ class ConditionVisitor < Prism::Visitor
79
+ attr_reader :conditions
80
+
81
+ def initialize(start_line, lines_hit, file_lines, file_path, config = nil)
82
+ super()
83
+ @start_line = start_line || 1
84
+ @lines_hit = lines_hit || Set.new
85
+ @file_lines = file_lines
86
+ @file_path = file_path
87
+ @config = config || RailsWhy.configuration
88
+ @redactor = Redactor.new(@config)
89
+ @conditions = []
90
+ end
91
+
92
+ def visit_if_node(node)
93
+ process_conditional(node, type: :if)
94
+ super
95
+ end
96
+
97
+ def visit_unless_node(node)
98
+ process_conditional(node, type: :unless)
99
+ super
100
+ end
101
+
102
+ def visit_case_node(node)
103
+ process_case(node)
104
+ super
105
+ end
106
+
107
+ def visit_and_node(node)
108
+ process_logical(node, type: :logical_and)
109
+ super
110
+ end
111
+
112
+ def visit_or_node(node)
113
+ process_logical(node, type: :logical_or)
114
+ super
115
+ end
116
+
117
+ private
118
+
119
+ def snippet(location)
120
+ start_line = location.start_line - 1
121
+ end_line = location.end_line - 1
122
+ return "" if start_line < 0 || start_line >= @file_lines.size
123
+
124
+ if start_line == end_line
125
+ line = @file_lines[start_line]
126
+ line ? line.strip : ""
127
+ else
128
+ @file_lines[start_line..end_line].map(&:strip).join(" ")
129
+ end
130
+ end
131
+
132
+ def process_conditional(node, type:)
133
+ line = node.location.start_line
134
+ # Only process if this node was executed/hit
135
+ predicate_hit = @lines_hit.include?(line)
136
+
137
+ predicate_text = snippet(node.predicate.location)
138
+ predicate_text = predicate_text.empty? ? node.location.slice.lines.first.to_s.strip : predicate_text
139
+ predicate_text = predicate_text.sub(/\Aif\s+/, "").sub(/\Aunless\s+/, "")
140
+
141
+ consequent_lines = extract_lines(node.statements)
142
+ consequent_hit = consequent_lines.any? { |l| @lines_hit.include?(l) }
143
+
144
+ alternative_lines = if node.respond_to?(:subsequent)
145
+ extract_lines(node.subsequent)
146
+ elsif node.respond_to?(:else_clause)
147
+ extract_lines(node.else_clause)
148
+ else
149
+ []
150
+ end
151
+ alternative_hit = alternative_lines.any? { |l| @lines_hit.include?(l) }
152
+
153
+ if !predicate_hit && !consequent_hit && !alternative_hit
154
+ return # Not reached
155
+ end
156
+
157
+ # Determine status
158
+ branch_taken = :none
159
+ status = :inconclusive
160
+
161
+ if type == :if
162
+ if consequent_hit
163
+ branch_taken = :then_branch
164
+ status = :evaluated_true
165
+ elsif alternative_hit
166
+ branch_taken = :else_branch
167
+ status = :evaluated_false
168
+ elsif predicate_hit
169
+ # If predicate ran, but neither body nor else ran, or maybe guard return
170
+ if is_guard_return?(node.statements)
171
+ branch_taken = :guard_not_taken
172
+ status = :evaluated_false
173
+ else
174
+ status = :executed
175
+ end
176
+ end
177
+ elsif type == :unless
178
+ if consequent_hit
179
+ branch_taken = :then_branch
180
+ status = :evaluated_false # unless condition is false
181
+ elsif alternative_hit
182
+ branch_taken = :else_branch
183
+ status = :evaluated_true
184
+ elsif predicate_hit
185
+ if is_guard_return?(node.statements)
186
+ branch_taken = :guard_not_taken
187
+ status = :evaluated_true
188
+ else
189
+ status = :executed
190
+ end
191
+ end
192
+ end
193
+
194
+ code_text = "#{type} #{predicate_text}"
195
+ redacted_code = @redactor.redact_sensitive_snippet(code_text)
196
+
197
+ @conditions << ConditionRecord.new(
198
+ type: type,
199
+ line: line,
200
+ code: redacted_code,
201
+ status: status,
202
+ branch_taken: branch_taken,
203
+ location: "#{@file_path}:#{line}"
204
+ )
205
+ end
206
+
207
+ def process_case(node)
208
+ line = node.location.start_line
209
+ return unless @lines_hit.include?(line)
210
+
211
+ executed_when = nil
212
+ node.conditions.each_with_index do |when_node, idx|
213
+ when_lines = extract_lines(when_node.statements)
214
+ if when_lines.any? { |l| @lines_hit.include?(l) }
215
+ executed_when = "when #{snippet(when_node.location)}"
216
+ break
217
+ end
218
+ end
219
+
220
+ status = executed_when ? :branch_selected : :executed
221
+ branch = executed_when || :default_or_none
222
+
223
+ @conditions << ConditionRecord.new(
224
+ type: :case,
225
+ line: line,
226
+ code: @redactor.redact_sensitive_snippet(snippet(node.location).lines.first.to_s.strip),
227
+ status: status,
228
+ branch_taken: branch,
229
+ location: "#{@file_path}:#{line}"
230
+ )
231
+ end
232
+
233
+ def process_logical(node, type:)
234
+ line = node.location.start_line
235
+ return unless @lines_hit.include?(line)
236
+
237
+ # If this logical node is a sub-expression of a parent logical node on the same line,
238
+ # avoid duplicating the condition report unless it provides unique info.
239
+ left_lines = extract_lines(node.left)
240
+ right_lines = extract_lines(node.right)
241
+
242
+ right_hit = right_lines.any? { |l| l != line && @lines_hit.include?(l) }
243
+
244
+ # Avoid unsupported condition inference:
245
+ # If both left and right expressions are on the exact same physical line,
246
+ # MRI TracePoint :line fires only once for the whole line, so we cannot safely
247
+ # infer individual operand truthiness without speculative guesses.
248
+ status = if left_lines == right_lines || (left_lines | right_lines) == [line]
249
+ :inconclusive_same_line
250
+ elsif right_hit
251
+ :evaluated_both
252
+ elsif type == :logical_and
253
+ :short_circuited_false
254
+ else
255
+ :short_circuited_true
256
+ end
257
+
258
+ op = type == :logical_and ? "&&" : "||"
259
+ code_str = snippet(node.location)
260
+ if code_str.empty?
261
+ code_str = "#{snippet(node.left.location)} #{op} #{snippet(node.right.location)}"
262
+ end
263
+
264
+ redacted_code = @redactor.redact_sensitive_snippet(code_str)
265
+
266
+ # Avoid duplicate conditions with identical line and code
267
+ return if @conditions.any? { |c| c.line == line && (c.code == redacted_code || c.code.include?(redacted_code)) }
268
+
269
+ @conditions << ConditionRecord.new(
270
+ type: type,
271
+ line: line,
272
+ code: redacted_code,
273
+ status: status,
274
+ branch_taken: (status == :inconclusive_same_line) ? :unsupported_inference : (right_hit ? :both_evaluated : :short_circuited),
275
+ location: "#{@file_path}:#{line}"
276
+ )
277
+ end
278
+
279
+ def extract_lines(node)
280
+ return [] if node.nil?
281
+
282
+ loc = node.location
283
+ (loc.start_line..loc.end_line).to_a
284
+ end
285
+
286
+ def is_guard_return?(statements_node)
287
+ return false if statements_node.nil?
288
+ return true if statements_node.is_a?(Prism::ReturnNode)
289
+
290
+ if statements_node.respond_to?(:body) && statements_node.body.is_a?(Array)
291
+ statements_node.body.any? { |stmt| stmt.is_a?(Prism::ReturnNode) }
292
+ else
293
+ false
294
+ end
295
+ end
296
+ end
297
+ end
298
+ end
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RailsWhy
4
+ class Configuration
5
+ DEFAULT_SENSITIVE_PATTERNS = [
6
+ /password/i, /secret/i, /token/i, /credential/i, /key/i,
7
+ /auth/i, /ssn/i, /cvv/i, /credit_card/i, /api_key/i
8
+ ].freeze
9
+
10
+ attr_accessor :root, :included_paths, :excluded_paths, :max_depth,
11
+ :max_events, :output_format, :enable_condition_analysis,
12
+ :enable_rails_notifications, :redact_sensitive_data,
13
+ :sensitive_patterns, :max_string_length, :color_output
14
+
15
+ def initialize
16
+ @root = defined?(Rails) && Rails.respond_to?(:root) && Rails.root ? Rails.root.to_s : Dir.pwd
17
+ @included_paths = []
18
+ @excluded_paths = ["vendor/", "bundle/", ".gem/"]
19
+ @max_depth = 25
20
+ @max_events = 5000
21
+ @output_format = :text # :text, :json, :quiet
22
+ @enable_condition_analysis = true
23
+ @enable_rails_notifications = true
24
+ @redact_sensitive_data = true
25
+ @sensitive_patterns = DEFAULT_SENSITIVE_PATTERNS.dup
26
+ @max_string_length = 200
27
+ @color_output = true
28
+ end
29
+
30
+ def path_included?(file_path)
31
+ return false if file_path.nil? || file_path.start_with?("<")
32
+
33
+ expanded = File.expand_path(file_path)
34
+ expanded_root = File.expand_path(@root)
35
+
36
+ return false unless expanded.start_with?(expanded_root)
37
+
38
+ rel_path = expanded.delete_prefix("#{expanded_root}/")
39
+
40
+ return false if @excluded_paths.any? { |excluded| rel_path.start_with?(excluded) || rel_path.include?(excluded) }
41
+
42
+ if @included_paths.any?
43
+ return @included_paths.any? { |inc| rel_path.start_with?(inc) || rel_path.include?(inc) }
44
+ end
45
+
46
+ true
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,177 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RailsWhy
4
+ class DiagnosticEngine
5
+ def initialize(config)
6
+ @config = config
7
+ end
8
+
9
+ # Analyze root cause given the root nodes, final result, and expected result
10
+ def diagnose(root_nodes, final_result, expected_result: :not_specified, raised_exception: nil)
11
+ all_nodes = root_nodes.flat_map { |n| [n, *n.all_descendants] }
12
+
13
+ # Did an exception occur?
14
+ if raised_exception
15
+ mark_exception_cause(all_nodes, raised_exception)
16
+ return
17
+ end
18
+
19
+ # Did user specify an expected result?
20
+ unexpected = if expected_result.is_a?(Proc)
21
+ !expected_result.call(final_result)
22
+ elsif expected_result != :not_specified
23
+ final_result != expected_result
24
+ else
25
+ # Default heuristic: false or nil can be unexpected,
26
+ # OR result object responding to success? and returning false,
27
+ # OR hash with status: "failed" or error present
28
+ final_result.equal?(false) ||
29
+ final_result.nil? ||
30
+ (final_result.respond_to?(:success?) && !final_result.success?) ||
31
+ (final_result.is_a?(Hash) && (final_result[:status] == "failed" || final_result["status"] == "failed" || final_result[:error] || final_result["error"]))
32
+ end
33
+
34
+ return unless unexpected
35
+
36
+ # If there were ActiveRecord validation errors recorded in thread
37
+ ar_errors = Thread.current[:__rails_why_ar_errors]
38
+ if ar_errors && ar_errors.any?
39
+ if root_nodes.any?
40
+ target = root_nodes.first
41
+ target.is_root_cause_candidate = true
42
+ target.validation_errors.concat(ar_errors)
43
+ target.explanation ||= "ActiveRecord validation failed: #{ar_errors.uniq.join(', ')}"
44
+ else
45
+ # Synthesize a diagnostic root node if no user-space methods were traced (e.g. u.save directly)
46
+ synthetic = Node.new(
47
+ id: 0,
48
+ defined_class: "ActiveRecord",
49
+ method_name: :validation,
50
+ path: "ActiveRecord::Validations",
51
+ line: 1
52
+ )
53
+ synthetic.is_root_cause_candidate = true
54
+ synthetic.validation_errors = ar_errors.uniq
55
+ synthetic.explanation = "ActiveRecord validation failed: #{ar_errors.uniq.join(', ')}"
56
+ root_nodes << synthetic
57
+ end
58
+ end
59
+
60
+ # Attach SQL queries if nodes did not receive them directly
61
+ sql_queries = Thread.current[:__rails_why_sql_queries]
62
+ if sql_queries && sql_queries.any? && root_nodes.any?
63
+ target = root_nodes.last
64
+ if target.sql_queries.empty?
65
+ target.sql_queries = sql_queries.select do |q|
66
+ sql = q[:sql].to_s.upcase
67
+ sql.start_with?("INSERT", "UPDATE", "DELETE", "ROLLBACK", "COMMIT", "BEGIN")
68
+ end
69
+ end
70
+ end
71
+
72
+ # Find candidates:
73
+ # Look for deepest nodes that:
74
+ # 1. Had validation errors
75
+ # 2. Aborted a callback (throw :abort)
76
+ # 3. Failed a condition or returned false/nil causing caller to return false/nil
77
+ find_candidates(root_nodes, expected_result)
78
+ end
79
+
80
+ private
81
+
82
+ def mark_exception_cause(all_nodes, exception)
83
+ # Find deepest node that raised this exception or matching class
84
+ raising_node = all_nodes.reverse.find do |node|
85
+ node.exception && node.exception[:class] == exception.class.name
86
+ end || all_nodes.first
87
+
88
+ if raising_node
89
+ raising_node.is_root_cause_candidate = true
90
+ raising_node.explanation = "Raised unhandled #{exception.class}: #{exception.message}"
91
+ end
92
+ end
93
+
94
+ def find_candidates(nodes, expected_result)
95
+ candidates = []
96
+
97
+ nodes.each do |node|
98
+ # 1. Check for active record validation failures
99
+ if node.validation_errors.any?
100
+ node.is_root_cause_candidate = true
101
+ node.explanation = "ActiveRecord validation failed: #{node.validation_errors.join(', ')}"
102
+ candidates << node
103
+ next
104
+ end
105
+
106
+ # 2. Check for aborted callbacks
107
+ if node.aborted_callbacks.any?
108
+ node.is_root_cause_candidate = true
109
+ node.explanation = "Callback aborted chain: #{node.aborted_callbacks.join(', ')}"
110
+ candidates << node
111
+ next
112
+ end
113
+
114
+ # 3. Check condition short-circuiting or failure in this node
115
+ failed_condition = node.conditions.find do |c|
116
+ c.status == :short_circuited_false ||
117
+ (c.type == :if && c.status == :evaluated_false && c.branch_taken == :else_branch)
118
+ end
119
+
120
+ # Recurse into children
121
+ child_candidates = find_candidates(node.children, expected_result)
122
+
123
+ if child_candidates.any?
124
+ # Child already explained it
125
+ candidates.concat(child_candidates)
126
+ elsif node_is_failure?(node, expected_result)
127
+ # Only flag as root cause if this node itself is the leaf failing condition
128
+ # or if it was the direct source of the failure
129
+ node.is_root_cause_candidate = true
130
+ if failed_condition
131
+ node.explanation = "Condition #{failed_condition.code} at #{failed_condition.location} evaluated to false/short-circuited"
132
+ else
133
+ node.explanation = "Returned #{node.return_value.inspect} (expected: #{expected_result == :not_specified ? 'truthy' : expected_result.inspect})"
134
+ end
135
+ candidates << node
136
+ end
137
+ end
138
+
139
+ candidates
140
+ end
141
+
142
+ def node_is_failure?(node, expected_result)
143
+ return true if node.exception
144
+ # Do not flag standard constructor initialization returning nil as a business failure
145
+ return false if node.method_name == :initialize
146
+
147
+ val = node.return_value
148
+
149
+ # Callback methods returning nil without aborting or adding errors are successful passes
150
+ # However, if an if condition was evaluated_true in the callback, it may be an aborting condition!
151
+ if node.path && (node.path.include?("/models/") || node.defined_class.to_s.end_with?("Record"))
152
+ if node.validation_errors.empty? && node.aborted_callbacks.empty? && (val.nil? || val == "nil")
153
+ has_abort_condition = node.conditions.any? { |c| c.status == :evaluated_true && c.branch_taken == :then_branch }
154
+ return true if has_abort_condition
155
+ return false
156
+ end
157
+ end
158
+
159
+ # Never call methods on business objects during diagnosis to avoid side effects or re-executions.
160
+ # Separate Ruby truthiness (false/nil) from failure:
161
+ if expected_result.is_a?(Proc)
162
+ !expected_result.call(val)
163
+ elsif expected_result != :not_specified
164
+ val != expected_result
165
+ else
166
+ # Inspect state without invoking business logic:
167
+ # Check string representation or primitive values
168
+ val.equal?(false) ||
169
+ val.nil? ||
170
+ val == "false" ||
171
+ val == "nil" ||
172
+ (val.is_a?(String) && val.include?(":success?=false")) ||
173
+ (val.is_a?(Hash) && (val[:status] == "failed" || val["status"] == "failed" || val[:error] || val["error"]))
174
+ end
175
+ end
176
+ end
177
+ end
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RailsWhy
4
+ class Node
5
+ attr_accessor :id, :parent_id, :defined_class, :method_name, :path,
6
+ :line, :call_type, :arguments, :return_value,
7
+ :exception, :children, :lines_hit, :conditions, :duration_ms,
8
+ :sql_queries, :validation_errors, :aborted_callbacks,
9
+ :is_root_cause_candidate, :explanation
10
+
11
+ def initialize(id:, parent_id: nil, defined_class: nil, method_name: nil, path: nil, line: nil, call_type: :method)
12
+ @id = id
13
+ @parent_id = parent_id
14
+ @defined_class = defined_class
15
+ @method_name = method_name
16
+ @path = path
17
+ @line = line
18
+ @call_type = call_type # :method, :block, :c_call
19
+ @arguments = {}
20
+ @return_value = nil
21
+ @exception = nil
22
+ @children = []
23
+ @lines_hit = Set.new
24
+ @conditions = []
25
+ @duration_ms = 0.0
26
+ @sql_queries = []
27
+ @validation_errors = []
28
+ @aborted_callbacks = []
29
+ @is_root_cause_candidate = false
30
+ @explanation = nil
31
+ end
32
+
33
+ def add_child(child_node)
34
+ @children << child_node
35
+ end
36
+
37
+ def record_line(lineno)
38
+ @lines_hit.add(lineno)
39
+ end
40
+
41
+ def call_signature
42
+ case @call_type
43
+ when :block
44
+ "#{@defined_class}#<block>:#{@line}"
45
+ else
46
+ "#{@defined_class}##{@method_name}"
47
+ end
48
+ end
49
+
50
+ def successful?
51
+ @exception.nil? && !@return_value.nil? && !@return_value.equal?(false)
52
+ end
53
+
54
+ def failed_or_falsy?
55
+ !@exception.nil? || @return_value.nil? || @return_value.equal?(false)
56
+ end
57
+
58
+ def all_descendants
59
+ @children.flat_map { |c| [c, *c.all_descendants] }
60
+ end
61
+ end
62
+ end