odem-rs-core 0.3.0

Core components of the odem-rs simulation framework
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
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
//! Provides [`Job`], a lightweight, cooperatively scheduled unit of execution
//! within the simulation framework.
//!
//! # Overview
//!
//! Jobs represent asynchronous tasks that can be dynamically created and
//! managed within the context of a simulation [`Agent`].
//! They are the primary means of expressing concurrent activities that share
//! state within a single agent's execution context.
//!
//! Unlike isolated [`Agent`]s, `Job`s are designed to easily interact with
//! variables in their lexical creation scope and with other jobs spawned by the
//! same agent, facilitating complex, stateful interactions within that agent's
//! boundary.
//!
//! # Key Concepts
//!
//! * **Unit of Execution:** A `Job` wraps a user-provided [`Future`],
//!   representing a sequence of asynchronous operations.
//! * **State Sharing:** Jobs created within the same agent share the same
//!   context, allowing access to the agent's state and simulation primitives
//!   (`Sim`). They can also directly capture and use variables from their
//!   creation environment (subject to lifetime constraints).
//! * **Cooperative Scheduling:** Jobs yield control back to the simulator
//!   scheduler via `.await` points (e.g., `sim.advance().await`). The scheduler
//!   manages the resumption of jobs based on model time, agent rank, and job
//!   precedence.
//! * **Return Values:** While the underlying [`Continuation`] mechanism only
//!   tracks success/failure, `Job` captures the actual `Output` of its future.
//!   This value can be retrieved by the creator using the [`Puck`] handle
//!   (e.g., by `.await`ing the `Puck`).
//! * **Finalization:** The [`Settle`] trait determines how a job's raw `Output`
//!   is translated into an [`ExitStatus`] (success/failure) for the underlying
//!   continuation mechanism. [`Unchecked`] treats all outcomes as success,
//!   while [`Checked`] interprets `Result`, `Option`, and `bool` meaningfully.
//! * **Lifecycle:** Jobs are created (using [`Job::new`] or
//!   [`Job::build`]), activated via [`Sim::activate`], and run until
//!   completion. They can be awaited using their [`Puck`] or prematurely
//!   terminated via [`Job::abort`] or [`Puck::abort`].
//! * **Branding:** A lifetime parameter is used internally with token witnesses
//!   to prevent accidental misuse of tokens obtained from one job instance with
//!   another. For most user interactions, this can be ignored.
//!
//! # Relationship to Agents and Continuations
//!
//! - **Agent:** An [`Agent`] is an *isolated* execution context. A `Job` runs
//!   *within* an Agent's context. An Agent acts as the root of a tree of Jobs.
//! - **Continuation:** A [`Continuation`] is the core, low-level scheduling
//!   primitive. A `Job` builds upon a `Continuation` by adding a concrete
//!   future, return value handling, and state-sharing capabilities.
//!
//! # Examples
//!
//! Creating and running a simple job that accesses a local variable:
//!
//! ```
//! # use odem_rs_core::{simulator::Sim, job::Job};
//! # use core::pin::pin;
//! async fn sim_main(sim: &Sim) {
//!     // Variable in the scope where the job is created
//!     let message = "Hello from Job!".to_string();
//!     let repeat_count = 3;
//!
//!     // Create a job (as an async block) that captures `message` and `repeat_count`
//!     let my_job = pin!(Job::new(async {
//!         println!("Job starting...");
//!         for i in 0..repeat_count {
//!             // Access captured variable
//!             println!("{}: {}", i, message);
//!             // Interact with the simulation
//!             sim.advance(1.0).await;
//!         }
//!         println!("Job finished!");
//!         // Return a value
//!         repeat_count * 10 // Job output is i32
//!     }));
//!
//!     // Activate the job using the simulation context
//!     let job_handle = sim.activate(my_job);
//!
//!     // Optionally, await the job's completion and get its return value
//!     let result: i32 = job_handle.await;
//!     assert_eq!(result, 30);
//!     println!("Job returned: {}", result);
//!
//!     // Ensure simulation runs long enough if not awaiting
//!     // sim.advance(4.0).await;
//! }
//! ```
//!
//! [`Agent`]: crate::agent::Agent

use crate::{
	Active, Dispatch, ExitStatus,
	config::Config,
	continuation::{Continuation, Label, Puck as ContPuck, Share, erased::State, token},
	error,
	fsm::*,
	ptr::{AsIrc, IntrusivelyCounted, Irc, IrcBox, IrcBoxed, Lease, LeasedMut},
	simulator::{Prec, Sim},
};

use core::{
	any::Any,
	cell::{RefCell, RefMut},
	fmt,
	future::{Future, IntoFuture, Pending},
	marker::PhantomData,
	panic::Location,
	pin::Pin,
	task::{Context, Poll},
};

/* ******************************************************************** Job */

/// A cooperatively scheduled, lightweight execution unit (job) within a
/// simulation [`Agent`].
///
/// `Job` combines a [`Future`] (representing the job's logic) with a
/// [`Continuation`] (providing the scheduling context). It allows asynchronous
/// tasks to run within the simulation, share state with their parent [`Agent`]
/// and sibling jobs, and capture variables from their lexical scope.
///
/// Unlike the base [`Continuation`] which only tracks success/failure, `Job`
/// captures the actual `Output` of its future `F`. This output can be retrieved
/// upon completion via the [`Puck`] handle. The interpretation of completion
/// (success vs. failure) for scheduling purposes is controlled by the
/// [`Settle`] strategy `S`.
///
/// Jobs must be pinned before activation. They are typically created using
/// [`Job::new`] or [`Job::build`].
///
/// # Type Parameters
///
/// * `C`: The simulation configuration type ([`Config`]).
/// * `F`: The [`Future`] type defining the job's asynchronous logic.
/// * `S`: The [`Settle`] strategy (default: [`Unchecked`]) determining how
///   `F::Output` translates to an [`ExitStatus`].
///
/// # Examples
///
/// ```
/// # use odem_rs_core::{simulator::Sim, job::Job};
/// # use core::pin::pin;
/// async fn sim_main(sim: &Sim) {
///     let local_data = 10;
///
///     // Create a job using an async block, capturing `local_data`
///     let job = pin!(Job::new(async move {
///         println!("Job started with data: {}", local_data);
///         sim.advance(5.0).await;
///         println!("Job finishing.");
///         local_data * 2 // The job returns an i32
///     }));
///
///     // Activate and await the result
///     let result: i32 = sim.activate(job).await;
///     assert_eq!(result, 20);
/// }
/// ```
///
/// [`Agent`]: crate::agent::Agent
pub type Job<C, F, S = Unchecked> = BrandedJob<'static, C, F, S>;

/// Branded version of the user-facing [`Job`] type.
///
/// This is the type underlying the `Job` type-alias and exposes branding
/// methods to safely manipulate the state of the underlying [`Continuation`].
#[pin_project::pin_project(PinnedDrop, !Unpin)]
pub struct BrandedJob<'brand, C: ?Sized + Config, F: Future, S> {
	/// The underlying continuation providing the scheduling context and state.
	#[pin]
	cont: Continuation<'brand, C>,
	/// Internal state holding either the pending future or the final result.
	#[pin]
	state: RefCell<Inner<F, S>>,
}

impl<C: ?Sized + Config, F: Future> Job<C, F> {
	/// Creates a new `Job` wrapping the given asynchronous action.
	///
	/// The `actions` argument can be any type that implements `IntoFuture`,
	/// typically an `async` block or function.
	///
	/// Uses the default [`Unchecked`] settle strategy and default precedence.
	/// For more configuration options, use [`Job::build`].
	///
	/// Returns a [`Lease`], which must be pinned before activation.
	#[track_caller]
	pub fn new<'p, A>(actions: A) -> Lease<'p, Self>
	where
		A: IntoFuture<IntoFuture = F>,
	{
		Job::build().with_actions(actions).finish()
	}
}

impl Job<(), Pending<()>> {
	/// Creates a [`Builder`] for constructing `Job` instances with custom
	/// configurations.
	///
	/// Use the builder to set options like a custom [`Settle`] strategy,
	/// initial scheduling [precedence], and explicit source code [`Location`].
	///
	/// [precedence]: Prec
	pub const fn build() -> Builder {
		Builder::new()
	}
}

impl<C: ?Sized + Config, F: Future, S: Settle<F::Output>> Job<C, F, S> {
	/// Used during startup of a simulation run to initialize the root job.
	pub(crate) fn boot<'p>(
		this: Pin<LeasedMut<'p, Self>>,
		share: Pin<&'p Share<C>>,
	) -> Puck<'p, C, F, S> {
		// create a reference-counted type
		let mut this = Irc::new(this);

		// set the most-specialized vptr for the continuation
		unsafe {
			let vptr = Irc::into_raw(this);
			this = Irc::from_raw(vptr);
			this.cont.set_vptr(vptr);
		}

		this.get_pin_mut().unwrap().brand(move |job, once| {
			let born = job.token(once).into_born().unwrap();

			// bind the shared agent data to it
			unsafe { job.bind(born, share.get_ref()) };
		});

		// initialize the pinned job reference
		Puck(this, PhantomData)
	}
}

impl<'brand, C: ?Sized + Config, F: Future, S> BrandedJob<'brand, C, F, S> {
	/// Sets the scheduling precedence for this job.
	/// Higher precedence jobs run before lower precedence jobs at the same
	/// simulation time.
	pub fn set_prec(&self, prec: Prec) {
		self.cont.set_prec(prec);
	}

	/// Returns the current execution state of the job's underlying
	/// continuation.
	pub fn state(&self) -> State {
		self.cont.state().borrow().erased()
	}

	/// Attempts to retrieve the job's return value if it has completed
	/// successfully.
	///
	/// Returns `Ok(value)` if the job is finished and the value hasn't been
	/// taken. Returns `Err(NotDone)` if the job is still running, was aborted,
	/// panicked, or the value was already retrieved.
	pub fn result(&self) -> Result<F::Output, error::NotDone> {
		self.brand(|job, once| Ok(job.inner_result(job.token(once).into_done()?).1))
	}

	/// Aborts the execution of this job immediately.
	///
	/// - Removes the job from the event calendar or `active` slot.
	/// - Drops the internal future, releasing its resources.
	/// - Sets the job's `ExitStatus` to `Failure`.
	/// - The job's return value (if any) is discarded.
	///
	/// This operation is idempotent; aborting an already aborted or completed
	/// job has no effect.
	pub fn abort(self: Pin<&Self>) {
		self.brand(|job, once| {
			job.inner_abort(job.token(once));
		});
	}

	/// Special abort method for use in drop implementations.
	///
	/// Does everything [`Self::abort`] does, but clears the vtable pointer
	/// before aborting in order to prevent `reclaim` from running.
	pub(crate) fn abort_on_drop(self: Pin<&Self>) {
		// Clear the vtable pointer *before* aborting. This prevents `reclaim`
		// (part of Continuation drop) from being called if `abort` causes the
		// ref-count to hit zero, as accessing `self` during `reclaim` after
		// starting the drop would be undefined due to the active mut reference.
		self.cont.clear_vptr();

		// Now we can abort.
		self.abort();
	}

	/// Returns the current state of the job as a lifetime-branded token.
	///
	/// Tokens ([`token::State`]) are used to prove the job's state at a
	/// specific moment, enabling safe state transitions and operations.
	/// Requires an [`Ephemeral`] token tied to the job's `'brand`.
	pub fn token(&self, once: Ephemeral<'brand>) -> token::State<'brand> {
		self.cont.token(once)
	}

	/// Returns an exclusive reference to the job's finalizer if the job is in
	/// the `Born` state (i.e., before activation).
	///
	/// Requires a [`token::Born`] to prove the job's state. Allows modifying
	/// the `Settle` strategy before the job starts running.
	pub fn finalizer(self: Pin<&mut Self>, born: &token::Born<'brand>) -> &mut S {
		let _ = born; // Ensure the Born token is provided

		match self.inner_state_mut().project() {
			InnerProject::Pending(_, settle) => settle,

			// SAFETY: We are `Pending` due to being in the Born state.
			// Mutable access is safe before activation.
			// We need to pin the mutable reference to the finalizer S.
			_ => unsafe { core::hint::unreachable_unchecked() },
		}
	}

	/// Core logic for aborting the job based on its current state token.
	fn inner_abort(self: Pin<&Self>, state: token::State<'brand>) -> token::Gone<'brand> {
		use scopeguard::{ScopeGuard, guard};
		use token::State::*;

		// Handle abort based on the current state proved by the token.
		match state {
			// Already aborted/finished, return Gone token.
			Gone(gone) => return gone,
			// Finished, drop result, return Gone.
			Done(done) => return self.inner_result(done).0,
			// Need to drop the future before transitioning.
			_ => {}
		};

		// Perform the actual transition into the `Gone` state.
		let to_gone = |state: token::State<'brand>| -> token::Gone<'brand> {
			let sm = self.cont.state();
			let rc = Err(crate::Failure);

			let gone = match state {
				// Nothing to do, other than transition for `Born` and `Idle`.
				Born(born) => sm.transition(born, rc),
				Idle(idle) => sm.transition(idle, rc),

				// Scheduled, remove from calendar.
				Next(next) => sm.transition(self.cont.deschedule(next), rc),
				// Currently running, deactivate.
				Busy(busy) => sm.transition(self.cont.deactivate(busy), rc),

				// This is not reachable due to the logic above.
				_ => unsafe { core::hint::unreachable_unchecked() },
			};

			// Wake up any other continuations that might have been waiting.
			self.cont.wake_pending();
			gone
		};

		// Secure the transition to `Gone(Failure)` using a scope guard.
		let guard = guard(state, |state| {
			to_gone(state);
		});

		// Enter the job's tracing span if tracing is enabled.
		let _span = self.cont.enter_span();

		// Drop the future payload; this may panic, invoking the scope guard.
		// User `drop` impls cannot be used to transition, since the current
		// state is frozen by this scope.
		self.inner_state().as_mut().abort();

		// Perform the transition on the happy path and return the `Gone` token.
		to_gone(ScopeGuard::into_inner(guard))
	}

	/// Core logic for extracting the result after completion.
	/// Returns the `Gone` token and the `Output`.
	fn inner_result(&self, done: token::Done<'brand>) -> (token::Gone<'brand>, F::Output) {
		let task = &self.cont;
		// Get the ExitStatus determined by the Settle strategy.
		let exit_status = task.branded_result(&done);

		// Extract the result.
		let output = self
			.state
			.borrow_mut()
			.result()
			.expect("Job::result: Result missing in Done state");

		// Enter the job's tracing span.
		let _span = task.enter_span();

		// Transition the Continuation state to Gone(exit_status).
		let gone = task.state().transition(done, exit_status);

		// Wake pending continuations now that this one is truly gone.
		task.wake_pending();

		(gone, output)
	}

	/// Performs a pin projection from the pinned job to a pinned `RefMut`
	/// of the inner state.
	///
	/// This realizes structural pinning of a `RefCell`, which is otherwise
	/// not possible.
	fn inner_state(self: Pin<&Self>) -> Pin<RefMut<'_, Inner<F, S>>> {
		unsafe { Pin::new_unchecked(self.get_ref().state.borrow_mut()) }
	}

	/// Performs a pin projection from a mutably pinned job to a mutably
	/// pinned reference of the inner state.
	fn inner_state_mut(self: Pin<&mut Self>) -> Pin<&mut Inner<F, S>> {
		unsafe { self.map_unchecked_mut(|job| job.state.get_mut()) }
	}

	/// Binds the shared agent context (`Share`) to a `Born` job.
	/// Transitions the job from `Born` to `Idle`.
	///
	/// # Safety
	/// Caller must ensure the `share` reference outlives the job's execution.
	/// This is typically guaranteed by the agent activation logic.
	pub(crate) unsafe fn bind(
		self: Pin<&mut Self>,
		born: token::Born<'brand>,
		share: &Share<C>,
	) -> token::Idle<'brand> {
		unsafe { self.project().cont.bind(born, share) }
	}
}

impl<'b, C, F, S> Stateful for BrandedJob<'b, C, F, S>
where
	C: ?Sized + Config,
	F: Future,
{
	type Brand = &'b ();

	unsafe fn enter(&self) {
		unsafe {
			self.cont.enter();
		}
	}

	unsafe fn leave(&self) {
		unsafe {
			self.cont.leave();
		}
	}
}

impl<'b, C, F, S> Rebrand<'b> for BrandedJob<'b, C, F, S>
where
	C: ?Sized + Config,
	F: Future,
{
	type Kind<'a> = BrandedJob<'a, C, F, S>;
}

impl<C, F, S> fmt::Debug for BrandedJob<'_, C, F, S>
where
	C: ?Sized + Config,
	F: Future,
{
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		use core::any::type_name;
		f.debug_struct("Job")
			.field("cont", &self.cont)
			.field("future_type", &type_name::<F>())
			.field("settle_type", &type_name::<S>())
			.finish()
	}
}

impl<C, F, S> Dispatch for BrandedJob<'_, C, F, S>
where
	C: ?Sized + Config,
	F: Future,
	S: Settle<F::Output>,
{
	fn poll(self: Pin<&Self>, cx: &mut Context<'_>) -> Poll<ExitStatus> {
		// Borrow the internal state.
		let mut inner = self.inner_state();

		// Poll the inner future.
		inner
			.as_mut()
			.poll(cx)
			.map(|value| inner.as_mut().ready(value))
	}
}

impl<C, F, S> Active<C> for Job<C, F, S>
where
	C: ?Sized + Config,
	F: Future,
	S: Settle<F::Output>,
{
	type Output = F::Output;
	type Puck<'p>
		= Puck<'p, C, F, S>
	where
		Self: 'p;

	/// Activates a `Born` job by binding it to a simulation context.
	///
	/// This is called by [`Sim::activate`]. It wraps the job in an `Irc`, sets
	/// up the vtable pointer for dispatch, binds the shared context, and
	/// returns a [`Puck`].
	fn bind<'p>(this: Pin<LeasedMut<'p, Self>>, sctx: &'p Share<C>) -> Self::Puck<'p> {
		// Wrap the leased mutable reference in an Irc.
		let mut irc = Irc::new(this);

		// Set the vtable pointer in the Continuation part for dispatch.
		// SAFETY: Similar to Job::boot, setting up the Irc dispatch mechanism.
		unsafe {
			let vptr = Irc::into_raw(irc);
			irc = Irc::from_raw(vptr);
			irc.cont.set_vptr(vptr);
		}

		// Use branding to safely transition state and bind the context.
		irc.get_pin_mut().unwrap().brand(move |mut job, once| {
			// Get a 'Born' token, proving the job is in the initial state.
			let born_token = job
				.token(once)
				.into_born()
				.expect("Job::bind called on non-Born job");

			// Bind the provided shared context of the active agent.
			// SAFETY: `Sim::activate` ensures `sctx` outlives the activated job
			// `this`. Lifetime 'p connects `this` and `sctx`.
			unsafe {
				job.as_mut().bind(born_token, sctx);
			}
			// Job is now Idle.
		});

		// Return the Puck handle, containing the Irc and PhantomData for
		// lifetime 'p.
		Puck(irc, PhantomData)
	}
}

// SAFETY: the `IrcBox`-method points to an inner `IrcBox`.
unsafe impl<C, F, S> IntrusivelyCounted for BrandedJob<'_, C, F, S>
where
	C: ?Sized + Config,
	F: Future,
{
	fn irc_box(&self) -> &IrcBox<dyn IrcBoxed> {
		self.cont.irc_box()
	}
}

impl<'brand, C, F, S> AsRef<Continuation<'brand, C>> for BrandedJob<'brand, C, F, S>
where
	C: ?Sized + Config,
	F: Future,
{
	fn as_ref(&self) -> &Continuation<'brand, C> {
		&self.cont
	}
}

#[pin_project::pinned_drop]
impl<C: ?Sized + Config, F: Future, T> PinnedDrop for BrandedJob<'_, C, F, T> {
	fn drop(self: Pin<&mut Self>) {
		// Abort the job's execution cleanly (removes from schedule, drops future).
		self.into_ref().abort_on_drop();
	}
}

/* ********************************************************************* Puck */

/// An owned handle to an activated [`Job`], providing interaction capabilities.
///
/// A `Puck` represents an active instance of a `Job` within the simulation. It
/// holds an intrusive reference to the `Job`.
///
/// `Puck` allows you to:
/// - Await the job's completion and retrieve its `Output`.
/// - Check the job's state ([`Puck::state`]).
/// - Access shared context information ([`Puck::share`], [`Puck::sim`], etc.).
/// - Abort the job prematurely ([`Puck::abort`]).
///
/// The `'p` lifetime ensures the `Puck` doesn't outlive the job bound to during
/// activation. `PhantomDrop` ensures correct diagnostics related to temporary
/// lifetimes during activation.
///
/// [`Puck::state`]: crate::Puck::state
/// [`Puck::sim`]: crate::Puck::sim
pub struct Puck<'p, C: ?Sized + Config, F: Future, S = Unchecked>(
	/// Intrusive reference counter holding the Job instance.
	Irc<Job<C, F, S>>,
	/// Signals to the borrow checker that the Puck may not outlive the Job
	/// that spawned it.
	PhantomDrop<Pin<&'p mut Job<C, F, S>>>,
);

impl<C: ?Sized + Config, F: Future, S> Puck<'_, C, F, S> {
	/// Returns a reference to the [`Share`]d context associated with this job's
	/// agent.
	///
	/// Provides access to the agent's state, simulation context, label, rank,
	/// etc.
	pub fn share(&self) -> &Share<C> {
		self.0
			.cont
			.share()
			.expect("Puck::share called on unbound Job")
	}

	/// Aborts the referenced job prematurely.
	///
	/// Consumes the `Puck` to prevent further interaction (like awaiting the
	/// result) after aborting. See [`Job::abort`] for details on the abort
	/// process.
	pub fn abort(self) {
		self.0.get_pin().abort();
	}
}

impl<C, F, S> fmt::Debug for Puck<'_, C, F, S>
where
	C: ?Sized + Config,
	F: Future,
{
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		f.debug_tuple("Puck").field(&self.0).finish()
	}
}

impl<C, F, S> IntoFuture for Puck<'_, C, F, S>
where
	C: ?Sized + Config,
	F: Future,
{
	type Output = F::Output;
	type IntoFuture = crate::ops::Join<C, Self>;

	#[inline]
	fn into_future(self) -> Self::IntoFuture {
		crate::ops::join(self)
	}
}

impl<C, F, S> crate::Puck<C> for Puck<'_, C, F, S>
where
	C: ?Sized + Config,
	F: Future,
{
	fn result(&mut self) -> Option<Self::Output> {
		self.0.result().ok()
	}

	fn subject(&self) -> &dyn Any {
		self.share().subject()
	}

	fn sim(&self) -> &Sim<C> {
		self.share().sim()
	}

	fn label(&self) -> Label {
		self.share().label()
	}

	fn time(&self) -> Option<C::Time> {
		self.0.cont.time()
	}

	fn rank(&self) -> C::Rank {
		self.share().rank()
	}

	fn prec(&self) -> Prec {
		self.0.cont.prec()
	}

	fn state(&self) -> State {
		self.0.cont.state().borrow().erased()
	}

	fn location(&self) -> &'static Location<'static> {
		self.0.cont.location()
	}

	fn puck(&self) -> ContPuck<C> {
		ContPuck::checked(self.as_irc()).expect("Puck::puck called on unbound Job")
	}
}

impl<C, F, S> From<Puck<'_, C, F, S>> for Irc<Job<C, F, S>>
where
	C: ?Sized + Config,
	F: Future,
{
	fn from(value: Puck<'_, C, F, S>) -> Self {
		value.0
	}
}

impl<C, F, S> AsRef<Continuation<'static, C>> for Puck<'_, C, F, S>
where
	C: ?Sized + Config,
	F: Future,
{
	fn as_ref(&self) -> &Continuation<'static, C> {
		&self.0.cont
	}
}

impl<C, F, S> AsIrc<Continuation<'static, C>> for Puck<'_, C, F, S>
where
	C: ?Sized + Config,
	F: Future,
{
	fn as_irc(&self) -> Irc<Continuation<'static, C>> {
		Irc::map(self.0.clone(), |inner| &inner.cont)
	}
}

/* **************************************** Return-Type-Erased Future Adapter */

/// Enumeration managing the state of the job's future.
///
/// This `enum` efficiently stores either the pending `Future` and its
/// associated [`Settle`] strategy or the `Option<F::Output>` once the future
/// completes.
#[pin_project::pin_project(
	project = InnerProject,
	project_replace = InnerOwn,
)]
enum Inner<F: Future, S> {
	/// Variant containing a pending `Future` and its `Settle`.
	Pending(#[pin] F, S),

	/// Variant containing the result of the `Future` or `None` in case of an
	/// aborted or terminated job where the result has already been retrieved.
	Ready(Option<F::Output>),
}

impl<F: Future, S> Inner<F, S> {
	/// Initializes a new return-type-erased instance from a future returning
	/// a `Result`.
	const fn new(actions: F, settle: S) -> Self {
		Inner::Pending(actions, settle)
	}

	/// Polls the inner future, panicking if it already terminated.
	fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<F::Output> {
		match self.project() {
			InnerProject::Pending(future, _) => future.poll(cx),
			_ => panic!("attempted to poll a terminated job"),
		}
	}

	/// Drops the jobs future `F` and settler `S`.
	fn abort(mut self: Pin<&mut Self>) {
		self.set(Inner::Ready(None));
	}

	/// Returns the result of the inner future.
	fn result(&mut self) -> Option<F::Output> {
		if let Inner::Ready(result) = self {
			result.take()
		} else {
			None
		}
	}

	/// Drops the inner future and writes out the result.
	///
	/// Panics if the job has already terminated.
	fn ready(mut self: Pin<&mut Self>, result: F::Output) -> ExitStatus
	where
		S: Settle<F::Output>,
	{
		match self.as_mut().project_replace(Inner::Ready(Some(result))) {
			InnerOwn::Pending(_, settle) => match self.project() {
				InnerProject::Ready(Some(result)) => settle.settle(result),
				_ => unsafe { core::hint::unreachable_unchecked() },
			},

			_ => panic!("terminating an already terminated job"),
		}
	}
}

/* ************************************************ Canonical Future Adapters */

/// Trait for defining how a [`Job`]'s return value (`R`) maps to an
/// [`ExitStatus`].
///
/// When a job's future completes, its `Settle` strategy is invoked with a
/// mutable reference to the return value. The `settle` method determines the
/// final `ExitStatus` (success or failure) that the underlying [`Continuation`]
/// records. This allows decoupling the job's actual output type from the
/// simulation's success/failure tracking.
pub trait Settle<R> {
	/// Called once when the job's future completes.
	fn settle(self, result: &mut R) -> ExitStatus;
}

// blanket implementation for closures
impl<R, F> Settle<R> for F
where
	F: FnOnce(&mut R) -> ExitStatus,
{
	fn settle(self, result: &mut R) -> ExitStatus {
		self(result)
	}
}

/// A [`Settle`] strategy where job completion *always* results in `Ok(Success)`.
///
/// This is the default strategy. The job's actual return value `R` is ignored
/// when determining the `ExitStatus`.
pub struct Unchecked;

impl<R> Settle<R> for Unchecked {
	fn settle(self, _result: &mut R) -> ExitStatus {
		Ok(crate::Success)
	}
}

/// A [`Settle`] strategy that interprets common types (`bool`, `Option`,
/// `Result`) to determine the [`ExitStatus`].
///
/// - `bool`: `true` -> `Ok(Success)`, `false` -> `Err(Failure)`.
/// - `Option<T>`: `Some(_)` -> `Ok(Success)`, `None` -> `Err(Failure)`.
/// - `Result<T, E>`: `Ok(_)` -> `Ok(Success)`, `Err(_)` -> `Err(Failure)`.
///
/// For other types `R`, using `Checked` will result in a compile error unless
/// a specific `Settle<R> for Checked` implementation is provided.
pub struct Checked;

impl Settle<bool> for Checked {
	fn settle(self, result: &mut bool) -> ExitStatus {
		if *result {
			Ok(crate::Success)
		} else {
			Err(crate::Failure)
		}
	}
}

impl<R, T> Settle<Result<R, T>> for Checked {
	fn settle(self, result: &mut Result<R, T>) -> ExitStatus {
		if result.is_ok() {
			Ok(crate::Success)
		} else {
			Err(crate::Failure)
		}
	}
}

impl<T> Settle<Option<T>> for Checked {
	fn settle(self, result: &mut Option<T>) -> ExitStatus {
		if result.is_some() {
			Ok(crate::Success)
		} else {
			Err(crate::Failure)
		}
	}
}

/* ************************************************************ Job Builder */

/// A builder for configuring and creating [`Job`] instances.
///
/// Provides methods to customize the job's future, settle strategy, precedence,
/// and source location before instantiation.
///
/// Start with [`Job::build()`], chain configuration methods, and finish with
/// [`finish()`](Builder::finish).
///
/// # Type Parameters
/// * `R`: `bool` indicating if this builder is for a root job (internal use).
/// * `F`: The type holding the future definition. Initially `()`.
/// * `S`: The [`Settle`] strategy type. Initially [`Unchecked`].
pub struct Builder<const R: bool = false, F = (), S = Unchecked> {
	/// The future or future provider. Set by `with_actions`.
	future: F,
	/// Optional source code location. Set by `with_location` or `with_actions`.
	location: Option<&'static Location<'static>>,
	/// The settle strategy instance. Set by `with_finalizer` or `checked`.
	finalizer: S,
	/// The initial scheduling precedence. Set by `with_precedence`.
	precedence: Prec,
}

impl Builder {
	/// Creates a new builder with default settings.
	pub const fn new() -> Self {
		Builder {
			future: (),
			location: None,
			finalizer: Unchecked,
			precedence: Prec::new(),
		}
	}

	/// Creates a new builder marked for a root job (internal use by Agent).
	pub const fn root() -> Builder<true> {
		Builder {
			future: (),
			location: None,
			finalizer: Unchecked,
			precedence: Prec::new(),
		}
	}
}

// Methods available before the future is set
impl<const R: bool, S> Builder<R, (), S> {
	/// Sets the asynchronous action (future) for the job.
	///
	/// Accepts any type implementing `IntoFuture`, typically an `async` block
	/// or function. Also captures the caller's location as the default source
	/// location unless explicitly set via `with_location`.
	#[track_caller]
	pub fn with_actions<F: IntoFuture>(self, future: F) -> Builder<R, F, S> {
		let Builder {
			location,
			finalizer,
			precedence,
			..
		} = self;

		Builder {
			future,
			location: Some(location.unwrap_or(Location::caller())),
			finalizer,
			precedence,
		}
	}
}

// Methods available before Settle is set (assuming default Unchecked)
impl<const R: bool, F> Builder<R, F> {
	/// Sets a custom [`Settle`] strategy for the job.
	pub fn with_finalizer<S>(self, finalizer: S) -> Builder<R, F, S> {
		let Builder {
			future,
			location,
			precedence,
			..
		} = self;

		Builder {
			future,
			location,
			finalizer,
			precedence,
		}
	}

	/// Sets the [`Settle`] strategy to [`Checked`], interpreting `bool`,
	/// `Option`, and `Result` outputs to determine success or failure.
	/// Shortcut for `with_finalizer(Checked)`.
	pub fn checked(self) -> Builder<R, F, Checked> {
		self.with_finalizer(Checked)
	}
}

// Methods always available
impl<const R: bool, F, S> Builder<R, F, S> {
	/// Sets the initial scheduling precedence for the job.
	/// Higher precedence jobs run before lower precedence jobs at the same
	/// simulation time.
	pub const fn with_precedence(mut self, precedence: Prec) -> Self {
		self.precedence = precedence;
		self
	}

	/// Explicitly sets the source code [`Location`] associated with the job.
	/// Overrides the location captured by `with_actions`.
	pub const fn with_location(mut self, location: &'static Location<'static>) -> Self {
		self.location = Some(location);
		self
	}
}

impl<const R: bool, F: IntoFuture, S: Settle<F::Output>> Builder<R, F, S> {
	/// Creates the [`Job`] instance from the builder configuration.
	///
	/// Consumes the builder and returns the configured `Job` wrapped in a
	/// [`Lease`].
	pub fn finish<'p, C>(self) -> Lease<'p, Job<C, F::IntoFuture, S>>
	where
		C: ?Sized + Config,
	{
		let location = self.location.unwrap();

		// create a new span if it's not a root fiber
		#[cfg(feature = "tracing")]
		let _span = if R {
			tracing::Span::current()
		} else {
			tracing::error_span!("Job", line = location.line()).or_current()
		}
		.entered();

		Lease::new(Job {
			cont: Continuation::new(self.precedence, location),
			state: RefCell::new(Inner::new(self.future.into_future(), self.finalizer)),
		})
	}
}

impl Default for Builder {
	fn default() -> Self {
		Self::new()
	}
}

/* ******************************************************* PhantomDrop helper */

/// This type-alias combines [`PhantomData`] with a Drop-check, ensuring that
/// even phantom types that don't implement the Drop traits themselves present
/// like they would. This is necessary to prevent code like in the following
/// example to compile which would lead to a runtime error due to increased
/// reference counts during destruction.
///
/// ```compile_fail
/// # use odem_rs_core::{simulator::Sim, job::Job};
/// # use core::pin::pin;
///
/// async fn sim_main(sim: &Sim) {
///     let puck = sim.activate(pin!(Job::new(async {})));
/// }
/// ```
type PhantomDrop<T> = PhantomData<PhantomDropInner<T>>;

/// Newtype wrapping a `T` and explicitly implementing the [Drop]-trait.
struct PhantomDropInner<T: ?Sized>(T);

impl<T: ?Sized> Drop for PhantomDropInner<T> {
	fn drop(&mut self) {}
}