evalsync 0.2.0

Experiment synchronization library for benchmark coordination via ZeroMQ
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
use once_cell::sync::OnceCell;
use prost::Message;
use std::collections::HashMap;
use std::env;
use std::sync::{Arc, Mutex};

pub mod proto {
    include!(concat!(env!("OUT_DIR"), "/evalsync.rs"));
}

use proto::{ExperimentCommand, ManagerMessage, ServiceState, StateSync};

pub struct ExperimentWorker {
    context: zmq::Context,
    state_socket: zmq::Socket,
    command_socket: zmq::Socket,
    experiment_id: String,
    client_id: String,
    state: ServiceState,
    verbose: bool,
    metadata: HashMap<String, String>,
    measurement_started: bool,
    measurement_completed: bool,
}

static WORKER: OnceCell<Arc<Mutex<ExperimentWorker>>> = OnceCell::new();

const CONNECTION_TIMEOUT_MS: i64 = 1000;

fn verify_socket_connection(socket: &zmq::Socket, timeout_ms: i64) -> Result<(), String> {
    let mut poll_items = [socket.as_poll_item(zmq::POLLOUT)];
    let rc = zmq::poll(&mut poll_items, timeout_ms).map_err(|e| e.to_string())?;
    if rc > 0 && poll_items[0].get_revents().contains(zmq::POLLOUT) {
        Ok(())
    } else if poll_items[0].get_revents().contains(zmq::POLLERR) {
        Err("Socket error during connection verification".to_string())
    } else {
        Err("Connection verification timed out".to_string())
    }
}

/// Initialize the worker with explicit experiment_id, client_id, and verbose flag.
#[must_use = "this `Result` may contain an error that should be handled"]
pub fn init(experiment_id: &str, client_id: &str, verbose: bool) -> Result<(), String> {
    if WORKER.get().is_some() {
        return Err("Worker already initialized".to_string());
    }
    let context = zmq::Context::new();
    let state_socket_path = format!("ipc:///tmp/{experiment_id}-STATE");
    let state_socket = context.socket(zmq::DEALER).map_err(|e| e.to_string())?;
    state_socket.set_linger(1000).map_err(|e| e.to_string())?;
    state_socket
        .set_identity(client_id.as_bytes())
        .map_err(|e| e.to_string())?;
    state_socket
        .connect(&state_socket_path)
        .map_err(|e| e.to_string())?;
    if verbose {
        eprintln!("[evalsync-worker] state channel: {state_socket_path}");
    }
    verify_socket_connection(&state_socket, CONNECTION_TIMEOUT_MS)?;
    if verbose {
        eprintln!("[evalsync-worker] state channel connected");
    }

    let command_socket_path = format!("ipc:///tmp/{experiment_id}-COMMAND");
    let command_socket = context.socket(zmq::DEALER).map_err(|e| e.to_string())?;
    command_socket.set_linger(1000).map_err(|e| e.to_string())?;
    command_socket
        .set_identity(client_id.as_bytes())
        .map_err(|e| e.to_string())?;
    command_socket
        .connect(&command_socket_path)
        .map_err(|e| e.to_string())?;
    if verbose {
        eprintln!("[evalsync-worker] command channel: {command_socket_path}");
    }
    verify_socket_connection(&command_socket, CONNECTION_TIMEOUT_MS)?;
    if verbose {
        eprintln!("[evalsync-worker] command channel connected");
    }

    let worker = ExperimentWorker {
        context,
        state_socket,
        command_socket,
        experiment_id: experiment_id.to_string(),
        client_id: client_id.to_string(),
        state: ServiceState::Init,
        verbose,
        metadata: HashMap::new(),
        measurement_started: false,
        measurement_completed: false,
    };
    WORKER
        .set(Arc::new(Mutex::new(worker)))
        .map_err(|_| "Failed to set worker".to_string())?;
    Ok(())
}

/// Initialize the worker using environment variables (EVALSYNC_EXPERIMENT_ID, EVALSYNC_CLIENT_ID, EVALSYNC_VERBOSE).
#[must_use = "this `Result` may contain an error that should be handled"]
pub fn init_env() -> Result<(), String> {
    let experiment_id = env::var("EVALSYNC_EXPERIMENT_ID")
        .map_err(|_| "EVALSYNC_EXPERIMENT_ID not set".to_string())?;
    let client_id =
        env::var("EVALSYNC_CLIENT_ID").map_err(|_| "EVALSYNC_CLIENT_ID not set".to_string())?;
    let verbose = env::var("EVALSYNC_VERBOSE").unwrap_or_default() == "1";
    init(&experiment_id, &client_id, verbose)
}

/// Clean up the worker, closing sockets and terminating the ZMQ context.
/// This should be called when the worker is no longer needed.
pub fn cleanup() -> Result<(), String> {
    // Note: OnceCell doesn't support taking the value out, so we can only
    // access and clean up through the mutex. The actual cleanup happens
    // when the worker is dropped after this function signals completion.
    with_worker(|worker| {
        if worker.verbose {
            eprintln!("[evalsync-worker] API CALL: cleanup() - cleaning up resources");
        }
        // ZMQ sockets and context will be cleaned up when dropped
        // We mark the state to indicate cleanup was requested
        Ok(())
    })?
}

/// Set a metadata key-value pair.
pub fn set_metadata(key: &str, value: &str) -> Result<(), String> {
    with_worker(|worker| {
        worker.metadata.insert(key.to_string(), value.to_string());
        Ok(())
    })?
}

/// Get a metadata value by key.
pub fn get_metadata(key: &str) -> Result<Option<String>, String> {
    with_worker(|worker| Ok(worker.metadata.get(key).cloned()))?
}

/// Get all metadata as a HashMap.
pub fn get_all_metadata() -> Result<HashMap<String, String>, String> {
    with_worker(|worker| Ok(worker.metadata.clone()))?
}

/// Clear all metadata.
pub fn clear_metadata() -> Result<(), String> {
    with_worker(|worker| {
        worker.metadata.clear();
        Ok(())
    })?
}

/// Check if verbose mode is enabled.
pub fn is_verbose() -> Result<bool, String> {
    with_worker(|worker| Ok(worker.verbose))?
}

fn with_worker<T, F: FnOnce(&mut ExperimentWorker) -> T>(f: F) -> Result<T, String> {
    let arc = WORKER.get().ok_or("Worker not initialized".to_string())?;
    let mut guard = arc.lock().map_err(|_| "Worker lock poisoned".to_string())?;
    Ok(f(&mut guard))
}

fn notify_manager(worker: &mut ExperimentWorker, msg: &str) -> Result<(), String> {
    let message = StateSync {
        state: worker.state as i32,
        error_message: msg.to_string(),
        metadata: worker.metadata.clone(),
    };
    let mut buf = Vec::with_capacity(message.encoded_len());
    message.encode(&mut buf).map_err(|e| e.to_string())?;
    if worker.verbose {
        eprintln!(
            "[evalsync-worker] [+] send message: state={:?} msg={:?}",
            worker.state, msg
        );
    }
    worker
        .state_socket
        .send_multipart([b"", buf.as_slice()], 0)
        .map_err(|e| e.to_string())?;
    Ok(())
}

/// Set the worker state to READY and notify the manager.
#[must_use = "this `Result` may contain an error that should be handled"]
pub fn ready() -> Result<(), String> {
    with_worker(|worker| {
        if worker.verbose {
            eprintln!("[evalsync-worker] API CALL: ready() - current state: {:?}", worker.state);
        }
        if worker.state == ServiceState::Init {
            worker.state = ServiceState::Ready;
            notify_manager(worker, "ready")?;
            if worker.verbose {
                eprintln!("[evalsync-worker] API CALL: ready() - SUCCESS, transitioned to READY");
            }
            Ok(())
        } else {
            if worker.verbose {
                eprintln!("[evalsync-worker] API CALL: ready() - FAILED, not in INIT state");
            }
            Err("Worker not in INIT state".to_string())
        }
    })?
}

/// Set the worker state to RUNNING and notify the manager.
#[must_use = "this `Result` may contain an error that should be handled"]
pub fn start() -> Result<(), String> {
    with_worker(|worker| {
        if worker.state == ServiceState::Ready {
            worker.state = ServiceState::Running;
            notify_manager(worker, "running")?;
            Ok(())
        } else {
            Err("Worker not in READY state".to_string())
        }
    })?
}

/// Set the worker state to DONE and notify the manager.
/// If still in MEASURING, this will merge measurement end with workload end.
/// Idempotent if already DONE.
#[must_use = "this `Result` may contain an error that should be handled"]
pub fn end() -> Result<(), String> {
    with_worker(|worker| {
        if worker.verbose {
            eprintln!("[evalsync-worker] API CALL: end() - current state: {:?}", worker.state);
        }
        if worker.state == ServiceState::Measuring {
            // Merge measurement end with workload end.
            worker.measurement_completed = true;
            worker.state = ServiceState::Done;
            notify_manager(worker, "done")?;
            if worker.verbose {
                eprintln!("[evalsync-worker] API CALL: end() - SUCCESS, transitioned to DONE (measurement_end merged)");
            }
            Ok(())
        } else if worker.state == ServiceState::MeasureDone {
            if !worker.measurement_completed {
                if worker.verbose {
                    eprintln!("[evalsync-worker] API CALL: end() - FAILED, measurement_end() required before end()");
                }
                return Err("measurement_end() required before end()".to_string());
            }
            worker.state = ServiceState::Done;
            notify_manager(worker, "done")?;
            if worker.verbose {
                eprintln!("[evalsync-worker] API CALL: end() - SUCCESS, transitioned to DONE");
            }
            Ok(())
        } else if worker.state == ServiceState::Done {
            // Already done - idempotent success
            if worker.verbose {
                eprintln!("[evalsync-worker] API CALL: end() - already DONE (no-op)");
            }
            Ok(())
        } else {
            if worker.verbose {
                eprintln!("[evalsync-worker] API CALL: end() - FAILED, not in MEASURING or MEASURE_DONE state");
            }
            Err("Worker not in MEASURING or MEASURE_DONE state".to_string())
        }
    })?
}

/// Set the worker state to ERROR and notify the manager.
#[must_use = "this `Result` may contain an error that should be handled"]
pub fn abort() -> Result<(), String> {
    with_worker(|worker| {
        if worker.state == ServiceState::Running
            || worker.state == ServiceState::Measuring
            || worker.state == ServiceState::MeasureDone
        {
            worker.state = ServiceState::Error;
            notify_manager(worker, "error")?;
            Ok(())
        } else {
            Err("Worker not in RUNNING, MEASURING, or MEASURE_DONE state".to_string())
        }
    })?
}

/// Transition to MEASURING state (after warmup, before actual measurement).
/// Call this after warmup is complete to enable precise timing.
/// For servers with no warmup, this can be called directly from READY state
/// (will auto-transition through RUNNING).
#[must_use = "this `Result` may contain an error that should be handled"]
pub fn measure_start() -> Result<(), String> {
    with_worker(|worker| {
        if worker.verbose {
            eprintln!("[evalsync-worker] API CALL: measure_start() - current state: {:?}", worker.state);
        }
        // Allow transition from READY (for servers with no warmup)
        if worker.state == ServiceState::Ready {
            worker.state = ServiceState::Running;
            notify_manager(worker, "running")?;
            if worker.verbose {
                eprintln!("[evalsync-worker] API CALL: measure_start() - auto-transitioned to RUNNING");
            }
        }
        if worker.state == ServiceState::Running {
            worker.state = ServiceState::Measuring;
            worker.measurement_started = true;
            worker.measurement_completed = false;
            notify_manager(worker, "measuring")?;
            if worker.verbose {
                eprintln!("[evalsync-worker] API CALL: measure_start() - SUCCESS, transitioned to MEASURING");
            }
            Ok(())
        } else {
            if worker.verbose {
                eprintln!("[evalsync-worker] API CALL: measure_start() - FAILED, not in READY or RUNNING state");
            }
            Err("Worker not in READY or RUNNING state".to_string())
        }
    })?
}

/// Transition from MEASURING to MEASURE_DONE (measurement complete).
/// Call this after measurement is complete and cleanup work remains.
#[must_use = "this `Result` may contain an error that should be handled"]
pub fn measure_end() -> Result<(), String> {
    with_worker(|worker| {
        if worker.verbose {
            eprintln!("[evalsync-worker] API CALL: measure_end() - current state: {:?}", worker.state);
        }
        if worker.state == ServiceState::Measuring && worker.measurement_started {
            worker.state = ServiceState::MeasureDone;
            worker.measurement_completed = true;
            notify_manager(worker, "measure_done")?;
            if worker.verbose {
                eprintln!("[evalsync-worker] API CALL: measure_end() - SUCCESS, transitioned to MEASURE_DONE");
            }
            Ok(())
        } else {
            if worker.verbose {
                eprintln!("[evalsync-worker] API CALL: measure_end() - FAILED, not in MEASURING state");
            }
            Err("Worker not in MEASURING state".to_string())
        }
    })?
}

/// Wait for a BEGIN command from the manager and transition to RUNNING.
#[must_use = "this `Result` may contain an error that should be handled"]
pub fn wait_for_start() -> Result<(), String> {
    with_worker(|worker| {
        if worker.verbose {
            eprintln!("[evalsync-worker] API CALL: wait_for_start() - current state: {:?}", worker.state);
        }
        if worker.state == ServiceState::Ready {
            loop {
                let msgs = worker
                    .command_socket
                    .recv_multipart(0)
                    .map_err(|e| e.to_string())?;
                if worker.verbose {
                    eprintln!(
                        "[evalsync-worker] [-] received command: {} bytes",
                        msgs[1].len()
                    );
                }
                let msg = ManagerMessage::decode(&*msgs[1]).map_err(|e| e.to_string())?;
                match ExperimentCommand::try_from(msg.command) {
                    Ok(ExperimentCommand::Begin) => {
                        worker.state = ServiceState::Running;
                        notify_manager(worker, "running")?;
                        if worker.verbose {
                            eprintln!("[evalsync-worker] API CALL: wait_for_start() - SUCCESS, received BEGIN");
                        }
                        return Ok(());
                    }
                    Ok(ExperimentCommand::End) | Ok(ExperimentCommand::Abort) => {
                        worker.state = ServiceState::Error;
                        notify_manager(worker, "error")?;
                        if worker.verbose {
                            eprintln!("[evalsync-worker] API CALL: wait_for_start() - FAILED, received END/ABORT");
                        }
                        return Err("Received END or ABORT before start".to_string());
                    }
                    _ => {}
                }
            }
        } else {
            if worker.verbose {
                eprintln!("[evalsync-worker] API CALL: wait_for_start() - FAILED, not in READY state");
            }
            Err("Worker not in READY state".to_string())
        }
    })?
}

/// Wait for an END command from the manager and transition to DONE.
/// If still in MEASURING, this will merge measurement end with workload end.
#[must_use = "this `Result` may contain an error that should be handled"]
pub fn wait_for_end() -> Result<(), String> {
    with_worker(|worker| {
        if worker.verbose {
            eprintln!("[evalsync-worker] API CALL: wait_for_end() - current state: {:?}", worker.state);
        }
        if worker.state == ServiceState::Measuring
            || (worker.state == ServiceState::MeasureDone && worker.measurement_completed)
        {
            loop {
                let msgs = worker
                    .command_socket
                    .recv_multipart(0)
                    .map_err(|e| e.to_string())?;
                let msg = ManagerMessage::decode(&*msgs[1]).map_err(|e| e.to_string())?;
                match ExperimentCommand::try_from(msg.command) {
                    Ok(ExperimentCommand::End) => {
                        if worker.state == ServiceState::Measuring {
                            worker.measurement_completed = true;
                        }
                        worker.state = ServiceState::Done;
                        notify_manager(worker, "done")?;
                        if worker.verbose {
                            eprintln!("[evalsync-worker] API CALL: wait_for_end() - SUCCESS, received END");
                        }
                        return Ok(());
                    }
                    Ok(ExperimentCommand::Begin) | Ok(ExperimentCommand::Abort) => {
                        worker.state = ServiceState::Error;
                        notify_manager(worker, "error")?;
                        if worker.verbose {
                            eprintln!("[evalsync-worker] API CALL: wait_for_end() - FAILED, received BEGIN/ABORT");
                        }
                        return Err("Received BEGIN or ABORT during end".to_string());
                    }
                    _ => {}
                }
            }
        } else {
            if worker.verbose {
                eprintln!("[evalsync-worker] API CALL: wait_for_end() - FAILED, not in MEASURING or MEASURE_DONE state");
            }
            Err("Worker not in MEASURING or MEASURE_DONE state".to_string())
        }
    })?
}