ralph-workflow 0.7.18

PROMPT-driven multi-agent orchestrator for git repos
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! Checkpoint serialization performance benchmarks
//!
//! These benchmarks measure serialization/deserialization performance for checkpoints
//! with various state sizes. They establish baseline metrics for:
//! - Serialization time for different history sizes
//! - Checkpoint file size growth
//! - Deserialization time
//!
//! These are primarily measurement benchmarks (run with `--nocapture` to see output),
//! with a small number of hard invariants to prevent unbounded regression.
//! Run with `--nocapture` to see output.

use crate::checkpoint::execution_history::{ExecutionStep, StepOutcome};
use crate::checkpoint::SizeThresholds;
use crate::reducer::state::PipelineState;
use std::time::Instant;

fn perf_ceiling_asserts_enabled() -> bool {
    // Wall-clock performance varies wildly across CI runners and build profiles.
    // Keep ceilings as an explicit opt-in for dedicated perf jobs.
    std::env::var_os("RALPH_WORKFLOW_PERF_CEILINGS").is_some()
}

/// Helper function to create a test execution step.
fn create_test_step(iteration: u32) -> ExecutionStep {
    ExecutionStep::new(
        "Development",
        iteration,
        "agent_invoked",
        StepOutcome::success(
            Some("Test output from agent".to_string()),
            vec!["src/file1.rs".to_string(), "src/file2.rs".to_string()],
        ),
    )
    .with_agent("test-agent")
    .with_duration(5)
}

/// Create a test pipeline state with N execution history entries.
fn create_test_pipeline_state(
    iterations: u32,
    review_passes: u32,
    history_size: usize,
) -> PipelineState {
    let mut state = PipelineState::initial(iterations, review_passes);

    for i in 0..history_size {
        state.add_execution_step(
            create_test_step(u32::try_from(i).expect("index fits in u32")),
            history_size,
        );
    }

    state
}

#[test]
fn benchmark_checkpoint_serialization_empty_state() {
    let state = create_test_pipeline_state(10, 5, 0);
    let start = Instant::now();

    let json = serde_json::to_string(&state).expect("Serialization should succeed");

    let duration = start.elapsed();
    let size_bytes = json.len();
    let size_kb = size_bytes / 1024;

    println!("\n=== Checkpoint Serialization (Empty State) ===");
    println!("Serialization time: {duration:?}");
    println!("Checkpoint size: {size_bytes} bytes ({size_kb} KB)");
    println!(
        "Execution history entries: {}",
        state.execution_history_len()
    );

    // Verify serialization works
    assert!(!json.is_empty());

    // Wall-clock sanity checks are opt-in to avoid flaky failures on noisy CI hosts.
    if perf_ceiling_asserts_enabled() {
        assert!(
            duration.as_millis() < 1000,
            "Serialization should complete in reasonable time"
        );
    }
}

#[test]
fn benchmark_checkpoint_serialization_small_state() {
    let state = create_test_pipeline_state(10, 5, 10);
    let start = Instant::now();

    let json = serde_json::to_string(&state).expect("Serialization should succeed");

    let duration = start.elapsed();
    let size_bytes = json.len();
    let size_kb = size_bytes / 1024;

    println!("\n=== Checkpoint Serialization (Small State - 10 steps) ===");
    println!("Serialization time: {duration:?}");
    println!("Checkpoint size: {size_bytes} bytes ({size_kb} KB)");
    println!(
        "Execution history entries: {}",
        state.execution_history_len()
    );
    println!(
        "Bytes per history entry: ~{}",
        size_bytes / state.execution_history_len().max(1)
    );

    // Verify serialization works
    assert_eq!(state.execution_history_len(), 10);

    // Wall-clock sanity checks are opt-in to avoid flaky failures on noisy CI hosts.
    if perf_ceiling_asserts_enabled() {
        assert!(
            duration.as_millis() < 1000,
            "Serialization should complete in reasonable time"
        );
    }
}

#[test]
fn benchmark_checkpoint_serialization_medium_state() {
    let state = create_test_pipeline_state(100, 20, 100);
    let start = Instant::now();

    let json = serde_json::to_string(&state).expect("Serialization should succeed");

    let duration = start.elapsed();
    let size_bytes = json.len();
    let size_kb = size_bytes / 1024;

    println!("\n=== Checkpoint Serialization (Medium State - 100 steps) ===");
    println!("Serialization time: {duration:?}");
    println!("Checkpoint size: {size_bytes} bytes ({size_kb} KB)");
    println!(
        "Execution history entries: {}",
        state.execution_history_len()
    );
    println!(
        "Bytes per history entry: ~{}",
        size_bytes / state.execution_history_len()
    );

    // Verify serialization works
    assert_eq!(state.execution_history_len(), 100);

    // This establishes baseline - may be slow initially
    // After bounding implementation (step 11), should improve
}

#[test]
fn benchmark_checkpoint_serialization_large_state() {
    let state = create_test_pipeline_state(100, 20, 1000);
    let start = Instant::now();

    let json = serde_json::to_string(&state).expect("Serialization should succeed");

    let duration = start.elapsed();
    let size_bytes = json.len();
    let checkpoint_kb = size_bytes / 1024;
    let checkpoint_megabytes = checkpoint_kb / 1024;

    println!("\n=== Checkpoint Serialization (Large State - 1000 steps) ===");
    println!("Serialization time: {duration:?}");
    println!("Checkpoint size: {size_bytes} bytes ({checkpoint_kb} KB, {checkpoint_megabytes} MB)");
    println!(
        "Execution history entries: {}",
        state.execution_history_len()
    );
    println!(
        "Bytes per history entry: ~{}",
        size_bytes / state.execution_history_len()
    );

    // Verify serialization works
    assert_eq!(state.execution_history_len(), 1000);

    // This demonstrates serialization performance with large history
    // After bounding implementation, history will be capped at limit (default 1000)
}

#[test]
fn benchmark_checkpoint_deserialization_small_state() {
    let state = create_test_pipeline_state(10, 5, 10);
    let json = serde_json::to_string(&state).expect("Serialization should succeed");

    let start = Instant::now();
    let deserialized: PipelineState =
        serde_json::from_str(&json).expect("Deserialization should succeed");
    let duration = start.elapsed();

    println!("\n=== Checkpoint Deserialization (Small State - 10 steps) ===");
    println!("Deserialization time: {duration:?}");
    println!("Checkpoint size: {} bytes", json.len());
    println!(
        "Execution history entries: {}",
        deserialized.execution_history_len()
    );

    // Verify deserialization works correctly
    assert_eq!(deserialized.execution_history_len(), 10);

    // Wall-clock sanity checks are opt-in to avoid flaky failures on noisy CI hosts.
    if perf_ceiling_asserts_enabled() {
        assert!(
            duration.as_millis() < 1000,
            "Deserialization should complete in reasonable time"
        );
    }
}

#[test]
fn benchmark_checkpoint_deserialization_large_state() {
    let state = create_test_pipeline_state(100, 20, 1000);
    let json = serde_json::to_string(&state).expect("Serialization should succeed");

    let start = Instant::now();
    let deserialized: PipelineState =
        serde_json::from_str(&json).expect("Deserialization should succeed");
    let duration = start.elapsed();

    let size_kb = json.len() / 1024;

    println!("\n=== Checkpoint Deserialization (Large State - 1000 steps) ===");
    println!("Deserialization time: {duration:?}");
    println!("Checkpoint size: {size_kb} KB");
    println!(
        "Execution history entries: {}",
        deserialized.execution_history_len()
    );

    // Verify deserialization works correctly
    assert_eq!(deserialized.execution_history_len(), 1000);
}

#[test]
fn benchmark_checkpoint_round_trip() {
    let original = create_test_pipeline_state(50, 10, 100);

    let serialize_start = Instant::now();
    let json = serde_json::to_string(&original).expect("Serialization should succeed");
    let serialize_duration = serialize_start.elapsed();

    let deserialize_start = Instant::now();
    let restored: PipelineState =
        serde_json::from_str(&json).expect("Deserialization should succeed");
    let deserialize_duration = deserialize_start.elapsed();

    let total_duration = serialize_duration + deserialize_duration;
    let size_kb = json.len() / 1024;

    println!("\n=== Checkpoint Round Trip (100 steps) ===");
    println!("Serialize time: {serialize_duration:?}");
    println!("Deserialize time: {deserialize_duration:?}");
    println!("Total time: {total_duration:?}");
    println!("Checkpoint size: {size_kb} KB");
    println!(
        "Execution history entries: {}",
        restored.execution_history_len()
    );

    // Verify round-trip correctness
    assert_eq!(
        restored.execution_history_len(),
        original.execution_history_len()
    );
    assert_eq!(restored.iteration, original.iteration);
    assert_eq!(restored.phase, original.phase);
}

#[test]
fn benchmark_serialization_scaling() {
    let sizes = vec![10, 50, 100, 500, 1000];
    let mut results = Vec::new();

    for size in &sizes {
        let state = create_test_pipeline_state(100, 20, *size);

        let start = Instant::now();
        let json = serde_json::to_string(&state).expect("Serialization should succeed");
        let duration = start.elapsed();

        let size_kb = json.len() / 1024;
        results.push((*size, duration, size_kb));
    }

    println!("\n=== Serialization Scaling ===");
    println!("History Size | Serialize Time | Checkpoint Size");
    println!("-------------|----------------|----------------");

    for (size, duration, kb) in &results {
        println!("{size:12} | {duration:14?} | {kb:12} KB");
    }

    // Verify we tested all sizes
    assert_eq!(results.len(), sizes.len());

    // This demonstrates how serialization time scales with history size
    // Helps identify if there are performance cliffs at certain sizes
}

#[test]
fn benchmark_serialization_performance_ceiling() {
    // This test establishes a performance ceiling for bounded history
    // If this test starts failing, it indicates a performance regression
    let state = create_test_pipeline_state(100, 20, 1000);

    let start = Instant::now();
    let json = serde_json::to_string(&state).unwrap();
    let duration = start.elapsed();

    let size_kb = json.len() / 1024;

    println!("\n=== Serialization Performance Ceiling ===");
    println!("Duration: {duration:?}");
    println!("Size: {size_kb} KB");

    // With bounded history (1000 entries), serialization is expected to be fast.
    // Wall-clock ceilings are opt-in to avoid flaky failures on noisy CI hosts.
    if perf_ceiling_asserts_enabled() {
        assert!(
            duration.as_millis() < 100,
            "Serialization performance regression detected: {duration:?} exceeds 100ms ceiling"
        );
    }

    // Checkpoint size must remain under the hard safety limit.
    let hard_limit_bytes = SizeThresholds::DEFAULT.error_threshold;
    assert!(
        json.len() < hard_limit_bytes,
        "Checkpoint size regression detected: {} bytes exceeds hard limit {} bytes",
        json.len(),
        hard_limit_bytes
    );

    // Stricter (1 MiB) size ceilings are opt-in to avoid brittle failures as PipelineState evolves.
    if perf_ceiling_asserts_enabled() {
        const ONE_MIB: usize = 1024 * 1024;
        assert!(
            json.len() < ONE_MIB,
            "Checkpoint size regression detected: {size_kb} KB exceeds 1 MiB ceiling"
        );
    }
}

#[test]
fn benchmark_deserialization_performance_ceiling() {
    // Companion test to serialization ceiling - verifies deserialization performance
    let state = create_test_pipeline_state(100, 20, 1000);
    let json = serde_json::to_string(&state).unwrap();

    let start = Instant::now();
    let _restored: PipelineState = serde_json::from_str(&json).unwrap();
    let duration = start.elapsed();

    let size_kb = json.len() / 1024;

    println!("\n=== Deserialization Performance Ceiling ===");
    println!("Duration: {duration:?}");
    println!("Size: {size_kb} KB");

    // Wall-clock ceilings are opt-in to avoid flaky failures on noisy CI hosts.
    if perf_ceiling_asserts_enabled() {
        assert!(
            duration.as_millis() < 100,
            "Deserialization performance regression detected: {duration:?} exceeds 100ms ceiling"
        );
    }
}

#[test]
fn benchmark_round_trip_performance_ceiling() {
    // Verifies total checkpoint cycle (save + restore) performance
    let original = create_test_pipeline_state(100, 20, 1000);

    let serialize_start = Instant::now();
    let json = serde_json::to_string(&original).unwrap();
    let serialize_duration = serialize_start.elapsed();

    let deserialize_start = Instant::now();
    let _restored: PipelineState = serde_json::from_str(&json).unwrap();
    let deserialize_duration = deserialize_start.elapsed();

    let total_duration = serialize_duration + deserialize_duration;
    let size_kb = json.len() / 1024;

    println!("\n=== Round Trip Performance Ceiling ===");
    println!("Serialize: {serialize_duration:?}");
    println!("Deserialize: {deserialize_duration:?}");
    println!("Total: {total_duration:?}");
    println!("Size: {size_kb} KB");

    // Wall-clock ceilings are opt-in to avoid flaky failures on noisy CI hosts.
    if perf_ceiling_asserts_enabled() {
        // Total round-trip should be under 200ms with bounded history
        assert!(
            total_duration.as_millis() < 200,
            "Round-trip performance regression detected: {total_duration:?} exceeds 200ms ceiling"
        );
    }
}