Skip to main content

ralph_workflow/reducer/state/
metrics.rs

1// Run-level execution metrics for the pipeline.
2//
3// This is the single source of truth for all iteration/attempt/retry/fallback statistics.
4//
5// # Where Metrics Are Updated
6//
7// Metrics are updated **only** in reducer code paths (`state_reduction/*.rs`):
8//
9// - `development.rs`: dev_iterations_started, dev_iterations_completed,
10//                     dev_attempts_total, dev_continuation_attempt,
11//                     analysis_attempts_*, xsd_retry_development
12// - `review.rs`: review_passes_started, review_passes_completed, review_runs_total,
13//                fix_runs_total, fix_continuations_total, fix_continuation_attempt,
14//                current_review_pass, xsd_retry_review, xsd_retry_fix
15// - `commit.rs`: commits_created_total, xsd_retry_commit
16// - `planning.rs`: xsd_retry_planning
17// - `agent.rs`: same_agent_retry_attempts_total, agent_fallbacks_total,
18//               model_fallbacks_total, retry_cycles_started_total
19//
20// # Event-to-Metric Mapping
21//
22// | Metric                              | Incremented On Event                                      | Notes                                    |
23// |-------------------------------------|-----------------------------------------------------------|------------------------------------------|
24// | dev_iterations_started              | DevelopmentEvent::IterationStarted                        | Not incremented on continuations         |
25// | dev_iterations_completed            | DevelopmentEvent::IterationCompleted { output_valid: true } | Advanced to commit phase                |
26// |                                     | DevelopmentEvent::ContinuationSucceeded                   | Continuation advanced to commit phase    |
27// | dev_attempts_total                  | DevelopmentEvent::AgentInvoked                            | Includes initial + continuations         |
28// | dev_continuation_attempt            | DevelopmentEvent::ContinuationTriggered                   | Reset on IterationStarted                |
29// | analysis_attempts_total             | DevelopmentEvent::AnalysisAgentInvoked                    | Total across all iterations              |
30// | analysis_attempts_in_current_iteration | DevelopmentEvent::AnalysisAgentInvoked                 | Reset on IterationStarted                |
31// | review_passes_started               | ReviewEvent::PassStarted                                  | Increments when pass != previous         |
32// | review_passes_completed             | ReviewEvent::Completed { issues_found: false }            | Clean pass                               |
33// |                                     | ReviewEvent::PassCompletedClean                           | Alternative event for clean pass         |
34// |                                     | ReviewEvent::FixAttemptCompleted                          | Fix completed, pass advances             |
35// | review_runs_total                   | ReviewEvent::AgentInvoked                                 | Total reviewer invocations               |
36// | fix_runs_total                      | ReviewEvent::FixAgentInvoked                              | Total fix invocations                    |
37// | fix_continuations_total             | ReviewEvent::FixContinuationTriggered                     | Fix continuation attempts                |
38// | fix_continuation_attempt            | ReviewEvent::FixContinuationTriggered                     | Reset on PassStarted                     |
39// | current_review_pass                 | ReviewEvent::PassStarted                                  | Tracks current pass number               |
40// | xsd_retry_*                         | *Event::OutputValidationFailed (when will_retry == true)  | Only when retrying, not when exhausted   |
41// | same_agent_retry_attempts_total     | AgentEvent::TimedOut / InternalError (when will_retry)    | Only when retrying same agent            |
42// | timeout_no_output_agent_switches_total | AgentEvent::TimedOut { output_kind: NoOutput }         | NoOutput timeout triggered immediate switch |
43// | agent_fallbacks_total               | AgentEvent::FallbackTriggered                             | Agent switched in chain                  |
44// | model_fallbacks_total               | AgentEvent::ModelFallbackTriggered                        | Model switched for agent                 |
45// | retry_cycles_started_total          | AgentEvent::RetryCycleStarted                             | Chain exhausted, restarting              |
46// | commits_created_total               | CommitEvent::Created                                      | Actual git commit created                |
47//
48// # How to Add New Metrics
49//
50// 1. Add field to `RunMetrics` struct with `#[serde(default)]`
51// 2. Update `RunMetrics::new()` if config-derived display field
52// 3. Update appropriate reducer in `state_reduction/` to increment on event
53// 4. Add unit test in `state_reduction/tests/metrics.rs`
54// 5. Update `finalize_pipeline()` if displayed in final summary
55// 6. Add checkpoint compatibility test
56//
57// # Checkpoint Compatibility
58//
59// All fields have `#[serde(default)]` to ensure old checkpoints can be loaded
60// with new metrics fields defaulting to 0.
61
62/// Run-level execution metrics tracked by the reducer.
63///
64/// This struct provides a complete picture of pipeline execution progress,
65/// including iteration counts, attempt counts, retry counts, and fallback events.
66/// All fields are monotonic counters that only increment during a run.
67///
68/// # Checkpoint Compatibility
69///
70/// All fields have `#[serde(default)]` to ensure backward compatibility when
71/// loading checkpoints created before metrics were added or when new fields
72/// are introduced in future versions.
73///
74/// # Single Source of Truth
75///
76/// The reducer is the **only** code that mutates these metrics. They are
77/// updated deterministically based on events, ensuring:
78/// - Metrics survive checkpoint/resume
79/// - No drift between runtime state and actual progress
80/// - Final summary is always consistent with reducer state
81#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
82pub struct RunMetrics {
83    // Development iteration tracking
84    /// Number of development iterations started.
85    /// Incremented on `DevelopmentEvent::IterationStarted` (not on continuations).
86    #[serde(default)]
87    pub dev_iterations_started: u32,
88    /// Number of development iterations completed (advanced to commit phase).
89    /// A dev iteration is "completed" when the reducer transitions to `PipelinePhase::CommitMessage`
90    /// after dev output is valid, regardless of whether an actual git commit is created.
91    /// Incremented on `DevelopmentEvent::IterationCompleted { output_valid: true }` and
92    /// `DevelopmentEvent::ContinuationSucceeded`.
93    #[serde(default)]
94    pub dev_iterations_completed: u32,
95    /// Total number of developer agent invocations (includes continuations).
96    #[serde(default)]
97    pub dev_attempts_total: u32,
98    /// Current continuation attempt within the current development iteration (0 = initial).
99    /// Reset when starting a new iteration.
100    #[serde(default)]
101    pub dev_continuation_attempt: u32,
102
103    // Analysis tracking
104    /// Total number of analysis agent invocations across all iterations.
105    #[serde(default)]
106    pub analysis_attempts_total: u32,
107    /// Analysis attempts in the current development iteration (reset per iteration).
108    #[serde(default)]
109    pub analysis_attempts_in_current_iteration: u32,
110
111    // Review tracking
112    /// Number of review passes started.
113    /// Incremented on `ReviewEvent::PassStarted` when `pass != previous_pass`.
114    #[serde(default)]
115    pub review_passes_started: u32,
116    /// Number of review passes completed (advanced past without issues or after fixes).
117    /// A review pass is "completed" when it advances to the next pass or to commit phase,
118    /// either because no issues were found or because fixes were successfully applied.
119    /// Incremented on `ReviewEvent::Completed { issues_found: false }`,
120    /// `ReviewEvent::PassCompletedClean`, and `ReviewEvent::FixAttemptCompleted`.
121    #[serde(default)]
122    pub review_passes_completed: u32,
123    /// Total number of reviewer agent invocations.
124    #[serde(default)]
125    pub review_runs_total: u32,
126    /// Total number of fix agent invocations.
127    #[serde(default)]
128    pub fix_runs_total: u32,
129    /// Total number of fix continuation attempts.
130    #[serde(default)]
131    pub fix_continuations_total: u32,
132    /// Current fix continuation attempt within the current review pass (0 = initial).
133    ///
134    /// Reset when starting a new review pass.
135    /// Note: fix-attempt boundaries do not reset this counter; it is scoped to the review pass.
136    #[serde(default)]
137    pub fix_continuation_attempt: u32,
138    /// Current review pass number (for X/Y display).
139    #[serde(default)]
140    pub current_review_pass: u32,
141
142    // XSD retry tracking
143    /// Total XSD retry attempts across all phases.
144    #[serde(default)]
145    pub xsd_retry_attempts_total: u32,
146    /// XSD retry attempts in planning phase.
147    #[serde(default)]
148    pub xsd_retry_planning: u32,
149    /// XSD retry attempts in development/analysis phase.
150    #[serde(default)]
151    pub xsd_retry_development: u32,
152    /// XSD retry attempts in review phase.
153    #[serde(default)]
154    pub xsd_retry_review: u32,
155    /// XSD retry attempts in fix phase.
156    #[serde(default)]
157    pub xsd_retry_fix: u32,
158    /// XSD retry attempts in commit phase.
159    #[serde(default)]
160    pub xsd_retry_commit: u32,
161
162    // Same-agent retry tracking
163    /// Total same-agent retry attempts (for transient failures like timeout).
164    #[serde(default)]
165    pub same_agent_retry_attempts_total: u32,
166
167    /// Agent switches caused by no-output timeouts.
168    ///
169    /// Incremented only in the reducer's `TimedOut { output_kind: NoOutput }` arm.
170    /// Distinct from `agent_fallbacks_total` (which tracks `FallbackTriggered` events).
171    /// Distinct from `same_agent_retry_attempts_total` (`NoOutput` does not retry same agent).
172    #[serde(default)]
173    pub timeout_no_output_agent_switches_total: u32,
174
175    // Agent/model fallback tracking
176    /// Total agent fallback events.
177    #[serde(default)]
178    pub agent_fallbacks_total: u32,
179    /// Total model fallback events.
180    #[serde(default)]
181    pub model_fallbacks_total: u32,
182    /// Total retry cycles started (agent chain exhaustion + restart).
183    #[serde(default)]
184    pub retry_cycles_started_total: u32,
185
186    // Commit tracking
187    /// Total commits created during the run.
188    #[serde(default)]
189    pub commits_created_total: u32,
190
191    // Config-derived display fields (set once at init, not serialized from events)
192    /// Maximum development iterations (from config, for X/Y display).
193    #[serde(default)]
194    pub max_dev_iterations: u32,
195    /// Maximum review passes (from config, for X/Y display).
196    #[serde(default)]
197    pub max_review_passes: u32,
198    /// Maximum XSD retry count (from config, for X/max display).
199    #[serde(default)]
200    pub max_xsd_retry_count: u32,
201    /// Maximum development continuation count (from config, for X/max display).
202    #[serde(default)]
203    pub max_dev_continuation_count: u32,
204    /// Maximum fix continuation count (from config, for X/max display).
205    #[serde(default)]
206    pub max_fix_continuation_count: u32,
207    /// Maximum same-agent retry count (from config, for X/max display).
208    #[serde(default)]
209    pub max_same_agent_retry_count: u32,
210}
211
212impl RunMetrics {
213    /// Create metrics with config-derived display fields.
214    #[must_use] 
215    pub fn new(
216        max_dev_iterations: u32,
217        max_review_passes: u32,
218        continuation: &ContinuationState,
219    ) -> Self {
220        Self {
221            max_dev_iterations,
222            max_review_passes,
223            max_xsd_retry_count: continuation.max_xsd_retry_count,
224            max_dev_continuation_count: continuation.max_continue_count,
225            max_fix_continuation_count: continuation.max_fix_continue_count,
226            max_same_agent_retry_count: continuation.max_same_agent_retry_count,
227            ..Self::default()
228        }
229    }
230
231    // =========================================================================
232    // Builder methods for updating metrics without full struct clones
233    // =========================================================================
234    // These methods consume self and return a new instance with the updated field.
235    // This eliminates the need to clone all 40+ fields when updating a single metric.
236
237    // Development metrics
238    #[must_use] 
239    pub const fn increment_dev_iterations_started(mut self) -> Self {
240        self.dev_iterations_started += 1;
241        self
242    }
243
244    #[must_use] 
245    pub const fn increment_dev_iterations_completed(mut self) -> Self {
246        self.dev_iterations_completed += 1;
247        self
248    }
249
250    #[must_use] 
251    pub const fn increment_dev_attempts_total(mut self) -> Self {
252        self.dev_attempts_total += 1;
253        self
254    }
255
256    #[must_use] 
257    pub const fn increment_dev_continuation_attempt(mut self) -> Self {
258        self.dev_continuation_attempt += 1;
259        self
260    }
261
262    #[must_use] 
263    pub const fn reset_dev_continuation_attempt(mut self) -> Self {
264        self.dev_continuation_attempt = 0;
265        self
266    }
267
268    // Analysis metrics
269    #[must_use] 
270    pub const fn increment_analysis_attempts_total(mut self) -> Self {
271        self.analysis_attempts_total += 1;
272        self
273    }
274
275    #[must_use] 
276    pub const fn increment_analysis_attempts_in_current_iteration(mut self) -> Self {
277        self.analysis_attempts_in_current_iteration += 1;
278        self
279    }
280
281    #[must_use] 
282    pub const fn reset_analysis_attempts_in_current_iteration(mut self) -> Self {
283        self.analysis_attempts_in_current_iteration = 0;
284        self
285    }
286
287    // Review metrics
288    #[must_use] 
289    pub const fn increment_review_passes_started(mut self) -> Self {
290        self.review_passes_started += 1;
291        self
292    }
293
294    #[must_use] 
295    pub const fn increment_review_passes_completed(mut self) -> Self {
296        self.review_passes_completed += 1;
297        self
298    }
299
300    #[must_use] 
301    pub const fn increment_review_runs_total(mut self) -> Self {
302        self.review_runs_total += 1;
303        self
304    }
305
306    #[must_use] 
307    pub const fn increment_fix_runs_total(mut self) -> Self {
308        self.fix_runs_total += 1;
309        self
310    }
311
312    #[must_use] 
313    pub const fn increment_fix_continuations_total(mut self) -> Self {
314        self.fix_continuations_total += 1;
315        self
316    }
317
318    #[must_use] 
319    pub const fn increment_fix_continuation_attempt(mut self) -> Self {
320        self.fix_continuation_attempt += 1;
321        self
322    }
323
324    #[must_use] 
325    pub const fn reset_fix_continuation_attempt(mut self) -> Self {
326        self.fix_continuation_attempt = 0;
327        self
328    }
329
330    #[must_use] 
331    pub const fn set_current_review_pass(mut self, pass: u32) -> Self {
332        self.current_review_pass = pass;
333        self
334    }
335
336    // XSD retry metrics
337    #[must_use] 
338    pub const fn increment_xsd_retry_attempts_total(mut self) -> Self {
339        self.xsd_retry_attempts_total += 1;
340        self
341    }
342
343    #[must_use] 
344    pub const fn increment_xsd_retry_planning(mut self) -> Self {
345        self.xsd_retry_planning += 1;
346        self.xsd_retry_attempts_total += 1;
347        self
348    }
349
350    #[must_use] 
351    pub const fn increment_xsd_retry_development(mut self) -> Self {
352        self.xsd_retry_development += 1;
353        self.xsd_retry_attempts_total += 1;
354        self
355    }
356
357    #[must_use] 
358    pub const fn increment_xsd_retry_review(mut self) -> Self {
359        self.xsd_retry_review += 1;
360        self.xsd_retry_attempts_total += 1;
361        self
362    }
363
364    #[must_use] 
365    pub const fn increment_xsd_retry_fix(mut self) -> Self {
366        self.xsd_retry_fix += 1;
367        self.xsd_retry_attempts_total += 1;
368        self
369    }
370
371    #[must_use] 
372    pub const fn increment_xsd_retry_commit(mut self) -> Self {
373        self.xsd_retry_commit += 1;
374        self.xsd_retry_attempts_total += 1;
375        self
376    }
377
378    // Same-agent retry metrics
379    #[must_use]
380    pub const fn increment_same_agent_retry_attempts_total(mut self) -> Self {
381        self.same_agent_retry_attempts_total += 1;
382        self
383    }
384
385    /// Increment `timeout_no_output_agent_switches_total` counter.
386    ///
387    /// Called only when a `TimedOut { output_kind: NoOutput }` event triggers
388    /// an immediate agent switch.
389    #[must_use]
390    pub const fn increment_timeout_no_output_agent_switches_total(mut self) -> Self {
391        self.timeout_no_output_agent_switches_total += 1;
392        self
393    }
394
395    // Agent/model fallback metrics
396    #[must_use] 
397    pub const fn increment_agent_fallbacks_total(mut self) -> Self {
398        self.agent_fallbacks_total += 1;
399        self
400    }
401
402    #[must_use] 
403    pub const fn increment_model_fallbacks_total(mut self) -> Self {
404        self.model_fallbacks_total += 1;
405        self
406    }
407
408    #[must_use] 
409    pub const fn increment_retry_cycles_started_total(mut self) -> Self {
410        self.retry_cycles_started_total += 1;
411        self
412    }
413
414    // Commit metrics
415    #[must_use] 
416    pub const fn increment_commits_created_total(mut self) -> Self {
417        self.commits_created_total += 1;
418        self
419    }
420}