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
//! Correlation keys + matching rules.
use std::collections::HashMap;
use aion_core::{Event, TimerId};
/// Deterministic identity for one world-touching workflow call.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum CorrelationKey {
/// Activity scheduled at the deterministic ordinal carried by its [`aion_core::ActivityId`].
Activity(
/// Deterministic scheduling ordinal.
u64,
),
/// Child workflow scheduled at the deterministic spawn ordinal.
///
/// The ordinal is positional: the n-th `spawn_child` call a run makes
/// correlates with the n-th recorded `ChildWorkflowStarted` in that run's
/// history segment. Like activity ordinals it restarts at zero for every
/// run, so replay re-derives the same identity regardless of how many
/// asynchronous-arrival events (signals, timer fires) interleave.
Child(
/// Zero-based spawn ordinal within the run segment.
u64,
),
/// Detached hatch issued at the deterministic hatch ordinal (R13.1).
///
/// Positional exactly like [`CorrelationKey::Child`]: the n-th
/// `hatch_detached` call a run makes correlates with the n-th recorded
/// [`Event::WorkflowHatched`] in that run's history segment. A hatch is a
/// SIDE EFFECT — it starts a top-level workflow — so it resolves from
/// history on replay and must never start a second one. The hatched
/// identity is additionally UUIDv5-deterministic, but that is a dedupe
/// property of the identity, NOT a licence to re-run the start: the
/// recorded event is what a replayed hatch returns.
Hatch(
/// Zero-based hatch ordinal within the run segment.
u64,
),
/// Timer selected by workflow code or assigned by the engine.
Timer(
/// Timer identifier from the recorded timer-start event.
TimerId,
),
/// Signal delivery by name and zero-based occurrence for that name in history order.
Signal {
/// Signal name selected by workflow code.
name: String,
/// Zero-based occurrence of this signal name in recorded history order.
index: usize,
},
}
/// Derives correlation keys for every event in an ordered history.
///
/// Non-world-touching events and activity/timer/child outcome events do not introduce a new call
/// key, so their slots contain `None`. Signal keys carry the per-name occurrence index and child
/// workflow start keys carry the positional spawn ordinal, both derived from event order within
/// the supplied history slice.
#[must_use]
pub fn correlation_keys_for_history(events: &[Event]) -> Vec<Option<CorrelationKey>> {
let mut counters = OccurrenceCounters::default();
events
.iter()
.map(|event| key_for_event_with_counters(event, &mut counters))
.collect()
}
/// Derives the correlation key for one event in an ordered history.
///
/// `index` is the event's index inside `events`; it is used to count prior signals with the same
/// name and prior child workflow starts, so signal occurrence indices and child spawn ordinals are
/// positional within the slice.
#[must_use]
pub fn key_for_event(events: &[Event], index: usize) -> Option<CorrelationKey> {
let event = events.get(index)?;
match event {
Event::SignalReceived { name, .. } | Event::SignalSent { name, .. } => {
let prior_same_name = events
.iter()
.take(index)
.filter(|prior| matches!(prior, Event::SignalReceived { name: prior_name, .. } | Event::SignalSent { name: prior_name, .. } if prior_name == name))
.count();
Some(CorrelationKey::Signal {
name: name.clone(),
index: prior_same_name,
})
}
Event::ChildWorkflowStarted { .. } => {
let prior_starts = events
.iter()
.take(index)
.filter(|prior| matches!(prior, Event::ChildWorkflowStarted { .. }))
.count();
// On the 64-bit targets this engine ships on, usize -> u64 never
// fails; the fallible conversion exists only to satisfy the type
// signature on hypothetical wider-usize platforms. There, an
// overflowing count would leave this start event keyless: strict
// replay reports a mismatch when resolution reaches it, but the
// live fast-forward path skips keyless events silently — a
// missing key is not guaranteed to surface as an error.
u64::try_from(prior_starts).ok().map(CorrelationKey::Child)
}
Event::WorkflowHatched { .. } => {
let prior_hatches = events
.iter()
.take(index)
.filter(|prior| matches!(prior, Event::WorkflowHatched { .. }))
.count();
// Same fallible-conversion note as the child ordinal above.
u64::try_from(prior_hatches).ok().map(CorrelationKey::Hatch)
}
_ => key_for_positionless_event(event),
}
}
/// Running occurrence counts used to derive positional keys in one history pass.
#[derive(Default)]
struct OccurrenceCounters {
signal_counts: HashMap<String, usize>,
child_spawns: u64,
hatches: u64,
}
fn key_for_event_with_counters(
event: &Event,
counters: &mut OccurrenceCounters,
) -> Option<CorrelationKey> {
match event {
Event::SignalReceived { name, .. } | Event::SignalSent { name, .. } => {
let index = counters
.signal_counts
.get(name)
.copied()
.unwrap_or_default();
counters.signal_counts.insert(name.clone(), index + 1);
Some(CorrelationKey::Signal {
name: name.clone(),
index,
})
}
Event::ChildWorkflowStarted { .. } => {
let ordinal = counters.child_spawns;
counters.child_spawns += 1;
Some(CorrelationKey::Child(ordinal))
}
Event::WorkflowHatched { .. } => {
let ordinal = counters.hatches;
counters.hatches += 1;
Some(CorrelationKey::Hatch(ordinal))
}
_ => key_for_positionless_event(event),
}
}
fn key_for_positionless_event(event: &Event) -> Option<CorrelationKey> {
match event {
Event::ActivityScheduled { activity_id, .. } => {
Some(CorrelationKey::Activity(activity_id.sequence_position()))
}
Event::TimerStarted { timer_id, .. } => Some(CorrelationKey::Timer(timer_id.clone())),
_ => None,
}
}
#[cfg(test)]
mod tests {
use aion_core::{Event, EventEnvelope, Payload, WorkflowId};
use chrono::Utc;
use serde_json::json;
use uuid::Uuid;
use super::{CorrelationKey, correlation_keys_for_history, key_for_event};
fn envelope(seq: u64) -> EventEnvelope {
EventEnvelope {
seq,
recorded_at: Utc::now(),
workflow_id: WorkflowId::new(Uuid::nil()),
}
}
fn payload() -> Result<Payload, Box<dyn std::error::Error>> {
Ok(Payload::from_json(&json!(null))?)
}
#[test]
fn derives_signal_occurrence_indices_by_name() -> Result<(), Box<dyn std::error::Error>> {
let history = vec![
Event::SignalReceived {
envelope: envelope(1),
name: "ready".to_owned(),
payload: payload()?,
},
Event::SignalReceived {
envelope: envelope(2),
name: "other".to_owned(),
payload: payload()?,
},
Event::SignalReceived {
envelope: envelope(3),
name: "ready".to_owned(),
payload: payload()?,
},
];
let keys = correlation_keys_for_history(&history);
assert_eq!(
keys,
vec![
Some(CorrelationKey::Signal {
name: "ready".to_owned(),
index: 0,
}),
Some(CorrelationKey::Signal {
name: "other".to_owned(),
index: 0,
}),
Some(CorrelationKey::Signal {
name: "ready".to_owned(),
index: 1,
}),
]
);
Ok(())
}
fn child_started(seq: u64, child: u128) -> Result<Event, Box<dyn std::error::Error>> {
Ok(Event::ChildWorkflowStarted {
envelope: envelope(seq),
child_workflow_id: WorkflowId::new(Uuid::from_u128(child)),
workflow_type: "child".to_owned(),
input: payload()?,
package_version: aion_core::PackageVersion::new("a".repeat(64)),
})
}
#[test]
fn derives_positional_child_ordinals_independent_of_sequence_numbers()
-> Result<(), Box<dyn std::error::Error>> {
// Deliberately sparse, late sequence numbers: positional ordinals
// must not be derived from event sequence values.
let history = vec![child_started(41, 1)?, child_started(97, 2)?];
let keys = correlation_keys_for_history(&history);
assert_eq!(
keys,
vec![
Some(CorrelationKey::Child(0)),
Some(CorrelationKey::Child(1)),
]
);
assert_eq!(key_for_event(&history, 0), Some(CorrelationKey::Child(0)));
assert_eq!(key_for_event(&history, 1), Some(CorrelationKey::Child(1)));
Ok(())
}
fn hatched(seq: u64, hatched_id: u128, key: &str) -> Event {
Event::WorkflowHatched {
envelope: envelope(seq),
child_workflow_id: WorkflowId::new(Uuid::from_u128(hatched_id)),
key: key.to_owned(),
}
}
/// 🔴 HATCH ORDINALS RUN ON THEIR OWN COUNTER, NOT THE CHILD ONE.
///
/// Hatches and child spawns are independent recorded families. If they
/// shared a counter, a spawn recorded between two hatches would shift the
/// second hatch's ordinal — replay would then look for `Hatch(2)` where
/// history recorded `Hatch(1)` and the run would fail non-deterministic.
/// Interleaving the two families here is what makes this test able to see
/// that; a history of hatches alone could not tell the two designs apart.
#[test]
fn hatch_ordinals_are_positional_and_independent_of_child_ordinals()
-> Result<(), Box<dyn std::error::Error>> {
let history = vec![
hatched(7, 10, "subject-a"),
child_started(9, 1)?,
hatched(11, 20, "subject-b"),
child_started(13, 2)?,
];
let keys = correlation_keys_for_history(&history);
assert_eq!(
keys,
vec![
Some(CorrelationKey::Hatch(0)),
Some(CorrelationKey::Child(0)),
Some(CorrelationKey::Hatch(1)),
Some(CorrelationKey::Child(1)),
]
);
// The single-event derivation must agree with the whole-history pass:
// replay uses one, the cursor descriptor uses the other, and a
// disagreement between them is a non-determinism bug that only shows
// up under recovery.
for (index, expected) in keys.iter().enumerate() {
assert_eq!(&key_for_event(&history, index), expected, "index {index}");
}
Ok(())
}
#[test]
fn interleaved_async_arrivals_do_not_shift_child_ordinals()
-> Result<(), Box<dyn std::error::Error>> {
let history = vec![
child_started(1, 1)?,
Event::SignalReceived {
envelope: envelope(2),
name: "mid".to_owned(),
payload: payload()?,
},
Event::ChildWorkflowCompleted {
envelope: envelope(3),
child_workflow_id: WorkflowId::new(Uuid::from_u128(1)),
result: payload()?,
},
child_started(4, 2)?,
];
let keys = correlation_keys_for_history(&history);
assert_eq!(
keys,
vec![
Some(CorrelationKey::Child(0)),
Some(CorrelationKey::Signal {
name: "mid".to_owned(),
index: 0,
}),
None,
Some(CorrelationKey::Child(1)),
]
);
assert_eq!(key_for_event(&history, 3), Some(CorrelationKey::Child(1)));
Ok(())
}
}