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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! Runtime Integration for Cancellation Tracing
//!
//! This module provides integration points for the cancellation tracer with the
//! asupersync runtime. It shows how the tracer would be wired into the task and
//! region lifecycle to provide comprehensive cancellation monitoring.
//!
//! NOTE: This is a foundation module that will be fully activated when
//! asupersync-6r9mk9 (Cancel-Correctness Property Oracle) is completed.
use crate::observability::cancellation_tracer::{
CancellationTracer, CancellationTracerConfig, EntityType, TraceId,
};
use crate::record::region::RegionState;
use crate::types::{CancelKind, CancelReason, RegionId, TaskId};
use parking_lot::RwLock;
use std::collections::HashMap;
use std::sync::Arc;
/// Integration hooks for cancellation tracing in the runtime.
#[derive(Debug)]
pub struct CancellationTracerIntegration {
tracer: Arc<CancellationTracer>,
/// Active traces by task ID.
task_traces: Arc<RwLock<HashMap<TaskId, TraceId>>>,
/// Active traces by region ID.
region_traces: Arc<RwLock<HashMap<RegionId, TraceId>>>,
}
impl CancellationTracerIntegration {
/// Creates a new tracer integration with the given configuration.
#[must_use]
pub fn new(config: CancellationTracerConfig) -> Self {
Self {
tracer: Arc::new(CancellationTracer::new(config)),
task_traces: Arc::new(RwLock::new(HashMap::new())),
region_traces: Arc::new(RwLock::new(HashMap::new())),
}
}
/// Gets a reference to the underlying tracer.
#[must_use]
pub fn tracer(&self) -> &Arc<CancellationTracer> {
&self.tracer
}
/// Called when a task cancellation is initiated.
///
/// This should be called from TaskRecord::request_cancel_with_budget()
/// when the state transitions to CancelRequested.
pub fn on_task_cancel_initiated(
&self,
task_id: TaskId,
cancel_reason: &CancelReason,
cancel_kind: CancelKind,
parent_task: Option<TaskId>,
) {
// Check if this is part of an existing trace
let (trace_id, _is_new_trace) = if let Some(parent) = parent_task {
if let Some(&parent_trace_id) = self.task_traces.read().get(&parent) {
(parent_trace_id, false)
} else {
let trace_id = self.tracer.start_trace(
format!("{task_id:?}"),
EntityType::Task,
cancel_reason,
cancel_kind,
);
(trace_id, true)
}
} else {
let trace_id = self.tracer.start_trace(
format!("{task_id:?}"),
EntityType::Task,
cancel_reason,
cancel_kind,
);
(trace_id, true)
};
// Record the step
let parent_entity = parent_task.map(|id| format!("{id:?}"));
self.tracer.record_step(
trace_id,
format!("{task_id:?}"),
EntityType::Task,
cancel_reason,
cancel_kind,
"CancelRequested".to_string(),
parent_entity,
false, // Not yet completed
);
// Track the trace for this task
self.task_traces.write().insert(task_id, trace_id);
}
/// Called when a task acknowledges cancellation.
///
/// This should be called from TaskRecord::acknowledge_cancel()
/// when the state transitions to Cancelling.
pub fn on_task_cancel_acknowledged(
&self,
task_id: TaskId,
cancel_reason: &CancelReason,
cancel_kind: CancelKind,
) {
if let Some(&trace_id) = self.task_traces.read().get(&task_id) {
self.tracer.record_step(
trace_id,
format!("{task_id:?}"),
EntityType::Task,
cancel_reason,
cancel_kind,
"Cancelling".to_string(),
None, // No parent for acknowledgment step
false, // Still propagating
);
}
}
/// Called when a task enters finalizing phase.
///
/// This should be called when TaskState transitions to Finalizing.
pub fn on_task_finalizing(
&self,
task_id: TaskId,
cancel_reason: &CancelReason,
cancel_kind: CancelKind,
) {
if let Some(&trace_id) = self.task_traces.read().get(&task_id) {
self.tracer.record_step(
trace_id,
format!("{task_id:?}"),
EntityType::Task,
cancel_reason,
cancel_kind,
"Finalizing".to_string(),
None,
false, // Still finalizing
);
}
}
/// Called when a task completes cancellation.
///
/// This should be called from TaskRecord::complete() when the task
/// reaches terminal state with Cancelled outcome.
pub fn on_task_cancel_completed(&self, task_id: TaskId) {
// Extract the removal into a `let` binding so the `RwLockWriteGuard`
// produced by `task_traces.write()` drops at the end of THIS
// statement. If we inline the `remove(...)` into the `if let`
// scrutinee below, the write-guard's lifetime is extended to the
// end of the `if let` block, and the subsequent
// `self.task_traces.read()` tries to re-acquire the same
// non-reentrant `parking_lot::RwLock` — hard self-deadlock
// (observed as `test_task_cancel_flow` hanging indefinitely).
let removed_trace_id = self.task_traces.write().remove(&task_id);
if let Some(trace_id) = removed_trace_id {
// Check if this was the root task of the trace
let should_complete_trace = {
let task_traces = self.task_traces.read();
let region_traces = self.region_traces.read();
// If no other tasks or regions reference this trace, complete it
!task_traces.values().any(|&id| id == trace_id)
&& !region_traces.values().any(|&id| id == trace_id)
};
if should_complete_trace {
self.tracer.complete_trace(trace_id);
}
}
}
/// Called when a region begins cancellation.
///
/// This should be called from RegionRecord::begin_close() when cancellation
/// is propagated to child regions.
pub fn on_region_cancel_initiated(
&self,
region_id: RegionId,
cancel_reason: &CancelReason,
cancel_kind: CancelKind,
parent_region: Option<RegionId>,
) {
// Check if this is part of an existing trace
let (trace_id, _is_new_trace) = if let Some(parent) = parent_region {
if let Some(&parent_trace_id) = self.region_traces.read().get(&parent) {
(parent_trace_id, false)
} else {
let trace_id = self.tracer.start_trace(
format!("{region_id:?}"),
EntityType::Region,
cancel_reason,
cancel_kind,
);
(trace_id, true)
}
} else {
let trace_id = self.tracer.start_trace(
format!("{region_id:?}"),
EntityType::Region,
cancel_reason,
cancel_kind,
);
(trace_id, true)
};
// Record the step
let parent_entity = parent_region.map(|id| format!("{id:?}"));
self.tracer.record_step(
trace_id,
format!("{region_id:?}"),
EntityType::Region,
cancel_reason,
cancel_kind,
"Closing".to_string(),
parent_entity,
false,
);
// Track the trace for this region
self.region_traces.write().insert(region_id, trace_id);
}
/// Called when a region state transitions during cancellation.
pub fn on_region_state_transition(
&self,
region_id: RegionId,
_from_state: RegionState,
to_state: RegionState,
cancel_reason: Option<&CancelReason>,
cancel_kind: Option<CancelKind>,
) {
if let Some(&trace_id) = self.region_traces.read().get(®ion_id) {
// Only record if this is a cancellation-related transition
if matches!(
to_state,
RegionState::Closing | RegionState::Draining | RegionState::Finalizing
) {
if let (Some(reason), Some(kind)) = (cancel_reason, cancel_kind) {
self.tracer.record_step(
trace_id,
format!("{region_id:?}"),
EntityType::Region,
reason,
kind,
format!("{to_state:?}"),
None,
to_state == RegionState::Closed, // Complete when closed
);
}
}
}
}
/// Called when a region closes completely.
///
/// This should be called when RegionState reaches Closed.
pub fn on_region_closed(&self, region_id: RegionId) {
// Same non-reentrant RwLock self-deadlock pattern as
// `on_task_cancel_completed` above — extract the `remove(...)`
// into a `let` binding so the write guard drops before the
// subsequent read acquisitions inside the `if let` body.
let removed_trace_id = self.region_traces.write().remove(®ion_id);
if let Some(trace_id) = removed_trace_id {
// Check if this was the root region of the trace
let should_complete_trace = {
let task_traces = self.task_traces.read();
let region_traces = self.region_traces.read();
// If no other tasks or regions reference this trace, complete it
!task_traces.values().any(|&id| id == trace_id)
&& !region_traces.values().any(|&id| id == trace_id)
};
if should_complete_trace {
self.tracer.complete_trace(trace_id);
}
}
}
/// Gets traces currently being tracked for tasks.
#[must_use]
pub fn active_task_traces(&self) -> HashMap<TaskId, TraceId> {
self.task_traces.read().clone()
}
/// Gets traces currently being tracked for regions.
#[must_use]
pub fn active_region_traces(&self) -> HashMap<RegionId, TraceId> {
self.region_traces.read().clone()
}
/// Cleanup orphaned traces (for maintenance).
pub fn cleanup_orphaned_traces(&self) {
// This would be called periodically to clean up traces that may have
// been orphaned due to unexpected termination or other edge cases.
// Implementation would check for traces older than a threshold and
// complete them if no active references exist.
}
}
/// Example integration points showing where hooks would be called.
#[cfg(feature = "test-internals")]
pub mod integration_examples {
/// Example of how TaskRecord::request_cancel_with_budget would be modified.
///
/// ```rust,ignore
/// impl TaskRecord {
/// pub fn request_cancel_with_budget(
/// &mut self,
/// reason: CancelReason,
/// cleanup_budget: Budget,
/// tracer: Option<&CancellationTracerIntegration>,
/// ) -> bool {
/// // ... existing logic ...
///
/// match &mut self.state {
/// TaskState::Created | TaskState::Running => {
/// self.state = TaskState::CancelRequested {
/// reason: reason.clone(),
/// cleanup_budget,
/// };
/// self.phase.store(TaskPhase::CancelRequested);
///
/// // NEW: Hook for cancellation tracing
/// if let Some(tracer) = tracer {
/// tracer.on_task_cancel_initiated(
/// self.id,
/// &reason,
/// reason.kind,
/// None, // Would need parent task context
/// );
/// }
///
/// true
/// }
/// // ... other cases ...
/// }
/// }
/// }
/// ```
pub fn example_task_integration() {
// This is just documentation - the actual integration would happen
// in the TaskRecord and RegionRecord implementations.
}
/// Example of how RegionRecord::begin_close would be modified.
///
/// ```rust,ignore
/// impl RegionRecord {
/// pub fn begin_close(
/// &mut self,
/// reason: Option<CancelReason>,
/// tracer: Option<&CancellationTracerIntegration>,
/// ) {
/// // ... existing logic ...
///
/// if let Some(reason) = &reason {
/// // NEW: Hook for cancellation tracing
/// if let Some(tracer) = tracer {
/// tracer.on_region_cancel_initiated(
/// self.id,
/// reason,
/// reason.kind,
/// self.parent_id, // Parent region for trace propagation
/// );
/// }
/// }
///
/// // ... rest of implementation ...
/// }
/// }
/// ```
pub fn example_region_integration() {
// This is just documentation
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_integration_creation() {
let config = CancellationTracerConfig::default();
let integration = CancellationTracerIntegration::new(config);
let stats = integration.tracer().stats();
assert_eq!(stats.traces_collected, 0);
}
#[test]
fn test_task_cancel_flow() {
let config = CancellationTracerConfig::default();
let integration = CancellationTracerIntegration::new(config);
let task_id = TaskId::new_for_test(1, 0);
let cancel_reason = CancelReason::user("test");
let cancel_kind = CancelKind::User;
// Initiate cancellation
integration.on_task_cancel_initiated(task_id, &cancel_reason, cancel_kind, None);
// Task should be tracked
let active_traces = integration.active_task_traces();
assert!(active_traces.contains_key(&task_id));
// Acknowledge cancellation
integration.on_task_cancel_acknowledged(task_id, &cancel_reason, cancel_kind);
// Enter finalizing
integration.on_task_finalizing(task_id, &cancel_reason, cancel_kind);
// Complete cancellation
integration.on_task_cancel_completed(task_id);
// Task should no longer be tracked
let active_traces = integration.active_task_traces();
assert!(!active_traces.contains_key(&task_id));
// Should have recorded a complete trace
let stats = integration.tracer().stats();
assert_eq!(stats.traces_collected, 1);
assert!(stats.steps_recorded >= 3); // At least 3 steps recorded
}
#[test]
fn test_region_cancel_flow() {
let config = CancellationTracerConfig::default();
let integration = CancellationTracerIntegration::new(config);
let region_id = RegionId::new_for_test(1, 0);
let cancel_reason = CancelReason::user("region test");
let cancel_kind = CancelKind::User;
// Initiate region cancellation
integration.on_region_cancel_initiated(region_id, &cancel_reason, cancel_kind, None);
// Region should be tracked
let active_traces = integration.active_region_traces();
assert!(active_traces.contains_key(®ion_id));
// Transition through states
integration.on_region_state_transition(
region_id,
RegionState::Open,
RegionState::Closing,
Some(&cancel_reason),
Some(cancel_kind),
);
integration.on_region_state_transition(
region_id,
RegionState::Closing,
RegionState::Draining,
Some(&cancel_reason),
Some(cancel_kind),
);
integration.on_region_state_transition(
region_id,
RegionState::Draining,
RegionState::Finalizing,
Some(&cancel_reason),
Some(cancel_kind),
);
// Close region
integration.on_region_closed(region_id);
// Region should no longer be tracked
let active_traces = integration.active_region_traces();
assert!(!active_traces.contains_key(®ion_id));
// Should have recorded a complete trace
let stats = integration.tracer().stats();
assert_eq!(stats.traces_collected, 1);
assert!(stats.steps_recorded >= 3);
}
}