syren 0.6.0

A parallel Rust framework for agent-based models with ECS storage, scheduling, messaging, environments, and optional GPU execution.
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
//! Non-owning handle granting shared or exclusive access to ECS state.
//!
//! [`ECSReference`] is a lightweight, copyable handle into a live [`ECSManager`].
//! It is the primary interface through which systems read and mutate ECS data.
//!
//! # Boundary Resource Access
//!
//! [`ECSReference::boundary`] provides typed access to boundary resources
//! registered on the `ECSManager`. The method clones the target resource slot
//! while briefly holding the boundary registry mutex, then drops that mutex
//! before returning a [`crate::BoundaryHandle`]. The handle holds a per-resource read
//! guard, so systems using different boundary resources do not contend on the
//! registry mutex; lifecycle hooks wait for readers of their own resource to
//! drop.
//!
//! # Access modes
//!
//! | Method family             | Phase   | Borrows        | Structural mutation |
//! |---------------------------|---------|----------------|---------------------|
//! | `for_each_*` / `for_each` | Read    | Read + Write   | Forbidden           |
//! | `reduce_*`                | Read    | Read only      | Forbidden           |
//! | `defer`                   | None    | None           | Queued              |
//! | `with_exclusive`          | Write   | Bypassed       | Immediate           |
//! | `boundary`                | None    | None           | None (interior mut) |

use std::sync::atomic::Ordering;

use parking_lot::ArcRwLockReadGuard;
use parking_lot::RawRwLock;

use crate::engine::activation::RunContext;
use crate::engine::borrow::BorrowGuard;
use crate::engine::boundary::BoundaryResource;
use crate::engine::commands::{Command, CommandEvents};
use crate::engine::error::{ECSError, ECSResult, ExecutionError, InternalViolation};
use crate::engine::query::{BuiltQuery, QueryBuilder};
use crate::engine::storage::{cast_slice, cast_slice_mut};
use crate::engine::types::{BoundaryID, ChannelID};

#[cfg(feature = "gpu")]
use crate::engine::types::GPUResourceID;
#[cfg(feature = "gpu")]
use crate::gpu::GPUResource;
use crate::{ComponentID, Entity};

use super::data::ECSData;
use super::ecs_manager::{CommandDrainError, ECSManager};
use super::iteration::IterationScope;
use super::query_param::{EntityQueryParam, QueryParam, Read, Write};

/// A non-owning handle granting access to ECS data.
///
/// `ECSReference` allows systems to read or mutate ECS state while the
/// `ECSManager` remains shared across threads.
#[derive(Copy, Clone)]
pub struct ECSReference<'a> {
    pub(super) manager: &'a ECSManager,
}

impl<'a> ECSReference<'a> {
    /// Clears all component borrows. Must only be called when no systems are running.
    #[inline]
    pub(crate) fn clear_borrows(&self) {
        self.manager.borrows.clear();
    }

    #[inline]
    #[allow(clippy::result_large_err)]
    pub(crate) fn apply_deferred_commands_with_events(
        &self,
    ) -> Result<CommandEvents, CommandDrainError> {
        self.manager.apply_deferred_commands_with_events()
    }

    /// Executes a closure with **exclusive access** to the ECS world.
    ///
    /// Must not be called during parallel iteration.
    #[inline]
    pub fn with_exclusive<R>(&self, f: impl FnOnce(&mut ECSData) -> ECSResult<R>) -> ECSResult<R> {
        if self.manager.active_iters.load(Ordering::Acquire) != 0 {
            return Err(ECSError::from(
                ExecutionError::StructuralMutationDuringIteration,
            ));
        }
        let _phase = self.manager.phase_write()?;
        // SAFETY: We hold the exclusive phase lock.
        let data = unsafe { self.manager.data_mut_unchecked(&_phase) };
        f(data)
    }

    /// Enqueues a structural command for deferred execution at the next boundary.
    #[inline]
    pub fn defer(&self, command: Command) -> ECSResult<()> {
        let mut queue = self.manager.deferred.lock().map_err(|_| {
            ECSError::from(ExecutionError::LockPoisoned {
                what: "deferred command queue",
            })
        })?;
        queue.push(command);
        Ok(())
    }

    /// Begins construction of a component query against this world's registry.
    #[inline]
    pub fn query(&self) -> ECSResult<QueryBuilder> {
        Ok(QueryBuilder::with_registry(self.manager.registry()))
    }

    /// Returns deterministic context for the system currently running on this
    /// thread.
    ///
    /// Code running outside the scheduler receives the zero-valued default.
    #[inline]
    pub fn run_context(&self) -> RunContext {
        crate::engine::activation::current_run_context()
    }

    /// Returns a typed handle to a registered boundary resource.
    ///
    /// The returned [`crate::BoundaryHandle`] owns a clone of the resource's `Arc`
    /// and a per-resource read guard. The outer registry mutex is dropped
    /// before the handle is returned, so two systems holding handles to
    /// different resources never contend, and two systems holding handles
    /// to the same resource take read locks in parallel.
    ///
    /// Drop the handle as soon as the interaction is complete; lifecycle
    /// hooks at the next boundary stage need to acquire the per-resource
    /// write lock and will block until the last reader releases.
    ///
    /// # Errors
    /// - [`ExecutionError::BoundaryAccessFailed`] with
    ///   `reason = OutOfRange` if `id` exceeds the number of registered
    ///   resources.
    /// - [`ExecutionError::BoundaryAccessFailed`] with
    ///   `reason = TypeMismatch` if the stored resource's concrete type
    ///   does not match `R`.
    /// - [`ExecutionError::LockPoisoned`] if the boundary registry mutex
    ///   is poisoned (another thread panicked while holding it).
    pub fn boundary<R: BoundaryResource + 'static>(
        &self,
        id: BoundaryID,
    ) -> ECSResult<BoundaryHandle<R>> {
        let slot = {
            let guard = self.manager.boundary_resources.lock().map_err(|_| {
                ECSError::from(ExecutionError::LockPoisoned {
                    what: "boundary_resources (ECSReference::boundary)",
                })
            })?;
            if id as usize >= guard.slots.len() {
                return Err(ECSError::from(ExecutionError::BoundaryAccessFailed {
                    reason: crate::engine::error::BoundaryAccessFailure::OutOfRange,
                    id,
                }));
            }
            guard.slots[id as usize].clone()
        };

        // Acquire the per-resource read guard once and resolve the typed
        // pointer here, so `Deref` is a plain pointer read instead of a
        // downcast per call.
        let guard = slot.read_arc();
        let typed = match guard.as_any().downcast_ref::<R>() {
            Some(resource) => TypedResourcePtr(std::ptr::NonNull::from(resource)),
            None => {
                return Err(ECSError::from(ExecutionError::BoundaryAccessFailed {
                    reason: crate::engine::error::BoundaryAccessFailure::TypeMismatch,
                    id,
                }));
            }
        };

        Ok(BoundaryHandle {
            guard,
            typed,
            _phantom: std::marker::PhantomData,
        })
    }

    /// Generic parallel chunk-oriented ECS query.
    ///
    /// # Safety
    ///
    /// The caller must ensure `query`'s read and write component order matches
    /// the raw byte-slice contract expected by `f`.
    pub unsafe fn for_each_abstraction(
        &self,
        query: BuiltQuery,
        f: impl Fn(&[&[u8]], &mut [&mut [u8]]) + Send + Sync,
    ) -> ECSResult<()> {
        let _phase = self.manager.phase_read()?;
        let _iter_scope = IterationScope::new(&self.manager.active_iters);
        let _borrows = BorrowGuard::new(&self.manager.borrows, query.read_ids(), query.write_ids())
            .map_err(ECSError::from)?;
        // SAFETY: shared phase lock held; iteration scope active.
        let data = unsafe { self.manager.data_ref_unchecked(&_phase) };
        data.for_each_abstraction_unchecked(query, f)
            .map_err(ECSError::from)?;
        Ok(())
    }

    /// Parallel chunk iteration whose closure may return an error.
    ///
    /// Same semantics as [`Self::for_each_abstraction`] for borrow checking, phase
    /// discipline, and chunk-disjoint parallel execution. The closure
    /// returns [`ECSResult<()>`]; on the first error the iteration short-
    /// circuits and that error is returned. When two chunks fail
    /// concurrently the lower-indexed chunk's error wins, so the surfaced
    /// error is deterministic across thread counts.
    ///
    /// # Safety
    ///
    /// The caller must ensure `query`'s read and write component order matches
    /// the raw byte-slice contract expected by `f`.
    pub unsafe fn for_each_abstraction_fallible(
        &self,
        query: BuiltQuery,
        f: impl Fn(&[&[u8]], &mut [&mut [u8]]) -> ECSResult<()> + Send + Sync,
    ) -> ECSResult<()> {
        let _phase = self.manager.phase_read()?;
        let _iter_scope = IterationScope::new(&self.manager.active_iters);
        let _borrows = BorrowGuard::new(&self.manager.borrows, query.read_ids(), query.write_ids())
            .map_err(ECSError::from)?;
        // SAFETY: shared phase lock held; iteration scope active.
        let data = unsafe { self.manager.data_ref_unchecked(&_phase) };
        data.for_each_abstraction_fallible_unchecked(query, f)
    }

    /// Entity-aware parallel chunk iteration.
    ///
    /// Same safety contract as [`Self::for_each_abstraction`], but the closure
    /// also receives a row-aligned entity slice for each chunk.
    ///
    /// # Safety
    ///
    /// The caller must ensure `query`'s read and write component order matches
    /// the raw byte-slice contract expected by `f`.
    pub unsafe fn for_each_entity_abstraction(
        &self,
        query: BuiltQuery,
        f: impl Fn(&[Entity], &[&[u8]], &mut [&mut [u8]]) + Send + Sync,
    ) -> ECSResult<()> {
        let _phase = self.manager.phase_read()?;
        let _iter_scope = IterationScope::new(&self.manager.active_iters);
        let _borrows = BorrowGuard::new(&self.manager.borrows, query.read_ids(), query.write_ids())
            .map_err(ECSError::from)?;
        // SAFETY: shared phase lock held; iteration scope active.
        let data = unsafe { self.manager.data_ref_unchecked(&_phase) };
        data.for_each_entity_abstraction_unchecked(query, f)
            .map_err(ECSError::from)?;
        Ok(())
    }

    /// Entity-aware parallel chunk iteration whose closure may return an error.
    ///
    /// Same semantics as [`Self::for_each_entity_abstraction`] for borrow
    /// checking, phase discipline, and chunk-disjoint parallel execution.
    ///
    /// # Safety
    ///
    /// The caller must ensure `query`'s read and write component order matches
    /// the raw byte-slice contract expected by `f`.
    pub unsafe fn for_each_entity_abstraction_fallible(
        &self,
        query: BuiltQuery,
        f: impl Fn(&[Entity], &[&[u8]], &mut [&mut [u8]]) -> ECSResult<()> + Send + Sync,
    ) -> ECSResult<()> {
        let _phase = self.manager.phase_read()?;
        let _iter_scope = IterationScope::new(&self.manager.active_iters);
        let _borrows = BorrowGuard::new(&self.manager.borrows, query.read_ids(), query.write_ids())
            .map_err(ECSError::from)?;
        // SAFETY: shared phase lock held; iteration scope active.
        let data = unsafe { self.manager.data_ref_unchecked(&_phase) };
        data.for_each_entity_abstraction_fallible_unchecked(query, f)
    }

    /// Generic parallel read-only reduction over ECS data.
    ///
    /// # Safety
    ///
    /// The caller must ensure `query`'s read component order matches the raw
    /// byte-slice contract expected by `fold_chunk`.
    pub unsafe fn reduce_abstraction<R>(
        &self,
        query: BuiltQuery,
        init: impl Fn() -> R + Send + Sync,
        fold_chunk: impl Fn(&mut R, &[&[u8]], usize) + Send + Sync,
        combine: impl Fn(&mut R, R) + Send + Sync,
    ) -> ECSResult<R>
    where
        R: Send + 'static,
    {
        if !query.write_ids().is_empty() {
            return Err(InternalViolation::ReduceWritesNotAllowed.into());
        }
        let _phase = self.manager.phase_read()?;
        let _iter = IterationScope::new(&self.manager.active_iters);
        let _borrows = BorrowGuard::new(&self.manager.borrows, query.read_ids(), query.write_ids())
            .map_err(ECSError::from)?;
        // SAFETY: shared phase lock held.
        let data = unsafe { self.manager.data_ref_unchecked(&_phase) };
        data.reduce_abstraction_unchecked(query, init, fold_chunk, combine)
            .map_err(ECSError::from)
    }

    /// Registers a world-owned GPU resource.
    #[cfg(feature = "gpu")]
    pub fn register_gpu_resource<R: GPUResource + 'static>(
        &self,
        r: R,
    ) -> ECSResult<GPUResourceID> {
        self.with_exclusive(|data| data.register_gpu_resource(r))
    }
}

// Generic tuple for_each
impl ECSReference<'_> {
    /// Generic tuple-based parallel iteration. `P` is `Read<T>`/`Write<T>` or
    /// a tuple thereof (up to four reads and four writes).
    ///
    /// The closure receives [`QueryParam::Item`] per row and is statically
    /// dispatched - the compiler inlines it into the per-row loop. Because
    /// the closure type is inferred, name only `P` and let `_` stand for the
    /// closure:
    ///
    /// ```text
    /// world.for_each::<(Read<Productivity>, Write<Wealth>), _>(query, |(p, w)| {
    ///     w.value += p.rate;
    /// })?;
    /// ```
    pub fn for_each<P, F>(&self, query: BuiltQuery, f: F) -> ECSResult<()>
    where
        P: QueryParam,
        F: for<'i> Fn(P::Item<'i>) + Send + Sync,
    {
        P::validate(&query)?;
        // SAFETY: the typed query was validated against its stored TypeIds.
        unsafe {
            self.for_each_abstraction(query, move |reads, writes| {
                P::for_each_chunk(reads, writes, &f)
            })
        }
    }

    /// Generic tuple-based parallel iteration that also passes the owning
    /// [`Entity`] for each component row.
    pub fn for_each_entity<P, F>(&self, query: BuiltQuery, f: F) -> ECSResult<()>
    where
        P: EntityQueryParam,
        F: for<'i> Fn(P::EntityItem<'i>) + Send + Sync,
    {
        P::validate(&query)?;
        // SAFETY: the typed query was validated against its stored TypeIds.
        unsafe {
            self.for_each_entity_abstraction(query, move |entities, reads, writes| {
                P::for_each_entity_chunk(entities, reads, writes, &f)
            })
        }
    }

    /// Generic tuple-based entity-aware iteration whose closure may fail.
    pub fn for_each_entity_fallible<P, F>(&self, query: BuiltQuery, f: F) -> ECSResult<()>
    where
        P: EntityQueryParam,
        F: for<'i> Fn(P::EntityItem<'i>) -> ECSResult<()> + Send + Sync,
    {
        P::validate(&query)?;
        // SAFETY: the typed query was validated against its stored TypeIds.
        unsafe {
            self.for_each_entity_abstraction_fallible(query, move |entities, reads, writes| {
                P::for_each_entity_chunk_fallible(entities, reads, writes, &f)
            })
        }
    }
}

// Typed reductions
impl ECSReference<'_> {
    /// Typed parallel reduction over one read component.
    pub fn reduce_read<A, R>(
        &self,
        query: BuiltQuery,
        init: impl Fn() -> R + Send + Sync,
        fold: impl Fn(&mut R, &A) + Send + Sync,
        combine: impl Fn(&mut R, R) + Send + Sync,
    ) -> ECSResult<R>
    where
        A: 'static + Send + Sync,
        R: Send + 'static,
    {
        if query.reads().len() != 1 || !query.writes().is_empty() {
            return Err(InternalViolation::QueryShapeMismatch {
                method: "reduce_read",
                expected_reads: 1,
                expected_writes: 0,
            }
            .into());
        }
        query.validate_read_type::<A>(0, "reduce_read")?;
        unsafe {
            self.reduce_abstraction(
                query,
                init,
                move |acc, cols, _| {
                    let slice = cast_slice::<A>(cols[0].as_ptr(), cols[0].len());
                    for v in slice {
                        fold(acc, v);
                    }
                },
                combine,
            )
        }
    }

    /// Typed parallel reduction over two read components.
    pub fn reduce_read2<A, B, R>(
        &self,
        query: BuiltQuery,
        init: impl Fn() -> R + Send + Sync,
        fold: impl Fn(&mut R, &A, &B) + Send + Sync,
        combine: impl Fn(&mut R, R) + Send + Sync,
    ) -> ECSResult<R>
    where
        A: 'static + Send + Sync,
        B: 'static + Send + Sync,
        R: Send + 'static,
    {
        if query.reads().len() != 2 || !query.writes().is_empty() {
            return Err(InternalViolation::QueryShapeMismatch {
                method: "reduce_read2",
                expected_reads: 2,
                expected_writes: 0,
            }
            .into());
        }
        query.validate_read_type::<A>(0, "reduce_read2")?;
        query.validate_read_type::<B>(1, "reduce_read2")?;
        unsafe {
            self.reduce_abstraction(
                query,
                init,
                move |acc, cols, _| {
                    let a = cast_slice::<A>(cols[0].as_ptr(), cols[0].len());
                    let b = cast_slice::<B>(cols[1].as_ptr(), cols[1].len());
                    debug_assert_eq!(a.len(), b.len());
                    for i in 0..a.len() {
                        fold(acc, &a[i], &b[i]);
                    }
                },
                combine,
            )
        }
    }
}

// Named rNwM helpers
impl ECSReference<'_> {
    /// Single read.
    pub fn for_each_r1<A>(&self, query: BuiltQuery, f: impl Fn(&A) + Send + Sync) -> ECSResult<()>
    where
        A: 'static + Send + Sync,
    {
        <(Read<A>,) as QueryParam>::validate(&query)?;
        unsafe {
            self.for_each_abstraction(query, move |reads, _| {
                let a = cast_slice::<A>(reads[0].as_ptr(), reads[0].len());
                for v in a {
                    f(v);
                }
            })
        }
    }

    /// Single read with owning entity.
    pub fn for_each_entity_r1<A>(
        &self,
        query: BuiltQuery,
        f: impl Fn(Entity, &A) + Send + Sync,
    ) -> ECSResult<()>
    where
        A: 'static + Send + Sync,
    {
        <(Read<A>,) as QueryParam>::validate(&query)?;
        unsafe {
            self.for_each_entity_abstraction(query, move |entities, reads, _| {
                let a = cast_slice::<A>(reads[0].as_ptr(), reads[0].len());
                debug_assert_eq!(entities.len(), a.len());
                for i in 0..a.len() {
                    f(entities[i], &a[i]);
                }
            })
        }
    }

    /// Single write.
    pub fn for_each_w1<A>(
        &self,
        query: BuiltQuery,
        f: impl Fn(&mut A) + Send + Sync,
    ) -> ECSResult<()>
    where
        A: 'static + Send + Sync,
    {
        <(Write<A>,) as QueryParam>::validate(&query)?;
        unsafe {
            self.for_each_abstraction(query, move |_, writes| {
                let slice = cast_slice_mut::<A>(writes[0].as_mut_ptr(), writes[0].len());
                for item in slice {
                    f(item);
                }
            })
        }
    }

    /// Single write with owning entity.
    pub fn for_each_entity_w1<A>(
        &self,
        query: BuiltQuery,
        f: impl Fn(Entity, &mut A) + Send + Sync,
    ) -> ECSResult<()>
    where
        A: 'static + Send + Sync,
    {
        <(Write<A>,) as QueryParam>::validate(&query)?;
        unsafe {
            self.for_each_entity_abstraction(query, move |entities, _, writes| {
                let slice = cast_slice_mut::<A>(writes[0].as_mut_ptr(), writes[0].len());
                debug_assert_eq!(entities.len(), slice.len());
                for i in 0..slice.len() {
                    f(entities[i], &mut slice[i]);
                }
            })
        }
    }

    /// Two reads.
    pub fn for_each_r2<A, B>(
        &self,
        query: BuiltQuery,
        f: impl Fn(&A, &B) + Send + Sync,
    ) -> ECSResult<()>
    where
        A: 'static + Send + Sync,
        B: 'static + Send + Sync,
    {
        <(Read<A>, Read<B>) as QueryParam>::validate(&query)?;
        unsafe {
            self.for_each_abstraction(query, move |reads, _| {
                let a = cast_slice::<A>(reads[0].as_ptr(), reads[0].len());
                let b = cast_slice::<B>(reads[1].as_ptr(), reads[1].len());
                debug_assert_eq!(a.len(), b.len());
                for i in 0..a.len() {
                    f(&a[i], &b[i]);
                }
            })
        }
    }

    /// Three reads.
    pub fn for_each_r3<A, B, C>(
        &self,
        query: BuiltQuery,
        f: impl Fn(&A, &B, &C) + Send + Sync,
    ) -> ECSResult<()>
    where
        A: 'static + Send + Sync,
        B: 'static + Send + Sync,
        C: 'static + Send + Sync,
    {
        <(Read<A>, Read<B>, Read<C>) as QueryParam>::validate(&query)?;
        unsafe {
            self.for_each_abstraction(query, move |reads, _| {
                let a = cast_slice::<A>(reads[0].as_ptr(), reads[0].len());
                let b = cast_slice::<B>(reads[1].as_ptr(), reads[1].len());
                let c = cast_slice::<C>(reads[2].as_ptr(), reads[2].len());
                debug_assert_eq!(a.len(), b.len());
                debug_assert_eq!(a.len(), c.len());
                for i in 0..a.len() {
                    f(&a[i], &b[i], &c[i]);
                }
            })
        }
    }

    /// One read, one write.
    pub fn for_each_r1w1<A, B>(
        &self,
        query: BuiltQuery,
        f: impl Fn(&A, &mut B) + Send + Sync,
    ) -> ECSResult<()>
    where
        A: 'static + Send + Sync,
        B: 'static + Send + Sync,
    {
        <(Read<A>, Write<B>) as QueryParam>::validate(&query)?;
        unsafe {
            self.for_each_abstraction(query, move |reads, writes| {
                let a = cast_slice::<A>(reads[0].as_ptr(), reads[0].len());
                let b = cast_slice_mut::<B>(writes[0].as_mut_ptr(), writes[0].len());
                debug_assert_eq!(a.len(), b.len());
                for i in 0..a.len() {
                    f(&a[i], &mut b[i]);
                }
            })
        }
    }

    /// One read, one write, with owning entity.
    pub fn for_each_entity_r1w1<A, B>(
        &self,
        query: BuiltQuery,
        f: impl Fn(Entity, &A, &mut B) + Send + Sync,
    ) -> ECSResult<()>
    where
        A: 'static + Send + Sync,
        B: 'static + Send + Sync,
    {
        <(Read<A>, Write<B>) as QueryParam>::validate(&query)?;
        unsafe {
            self.for_each_entity_abstraction(query, move |entities, reads, writes| {
                let a = cast_slice::<A>(reads[0].as_ptr(), reads[0].len());
                let b = cast_slice_mut::<B>(writes[0].as_mut_ptr(), writes[0].len());
                debug_assert_eq!(entities.len(), a.len());
                debug_assert_eq!(a.len(), b.len());
                for i in 0..a.len() {
                    f(entities[i], &a[i], &mut b[i]);
                }
            })
        }
    }

    /// Two reads, one write.
    pub fn for_each_r2w1<A, B, C>(
        &self,
        query: BuiltQuery,
        f: impl Fn(&A, &B, &mut C) + Send + Sync,
    ) -> ECSResult<()>
    where
        A: 'static + Send + Sync,
        B: 'static + Send + Sync,
        C: 'static + Send + Sync,
    {
        <(Read<A>, Read<B>, Write<C>) as QueryParam>::validate(&query)?;
        unsafe {
            self.for_each_abstraction(query, move |reads, writes| {
                let a = cast_slice::<A>(reads[0].as_ptr(), reads[0].len());
                let b = cast_slice::<B>(reads[1].as_ptr(), reads[1].len());
                let c = cast_slice_mut::<C>(writes[0].as_mut_ptr(), writes[0].len());
                debug_assert_eq!(a.len(), b.len());
                debug_assert_eq!(a.len(), c.len());
                for i in 0..a.len() {
                    f(&a[i], &b[i], &mut c[i]);
                }
            })
        }
    }

    /// Two reads, two writes.
    pub fn for_each_r2w2<A, B, C, D>(
        &self,
        query: BuiltQuery,
        f: impl Fn(&A, &B, &mut C, &mut D) + Send + Sync,
    ) -> ECSResult<()>
    where
        A: 'static + Send + Sync,
        B: 'static + Send + Sync,
        C: 'static + Send + Sync,
        D: 'static + Send + Sync,
    {
        <(Read<A>, Read<B>, Write<C>, Write<D>) as QueryParam>::validate(&query)?;
        unsafe {
            self.for_each_abstraction(query, move |reads, writes| {
                let a = cast_slice::<A>(reads[0].as_ptr(), reads[0].len());
                let b = cast_slice::<B>(reads[1].as_ptr(), reads[1].len());
                let c = cast_slice_mut::<C>(writes[0].as_mut_ptr(), writes[0].len());
                let d = cast_slice_mut::<D>(writes[1].as_mut_ptr(), writes[1].len());
                debug_assert_eq!(a.len(), b.len());
                debug_assert_eq!(a.len(), c.len());
                debug_assert_eq!(a.len(), d.len());
                for i in 0..a.len() {
                    f(&a[i], &b[i], &mut c[i], &mut d[i]);
                }
            })
        }
    }
}

// Named rNwM helpers whose closures return ECSResult.
impl ECSReference<'_> {
    /// Single read, fallible closure.
    pub fn for_each_r1_fallible<A>(
        &self,
        query: BuiltQuery,
        f: impl Fn(&A) -> ECSResult<()> + Send + Sync,
    ) -> ECSResult<()>
    where
        A: 'static + Send + Sync,
    {
        <(Read<A>,) as QueryParam>::validate(&query)?;
        unsafe {
            self.for_each_abstraction_fallible(query, move |reads, _| {
                let a = cast_slice::<A>(reads[0].as_ptr(), reads[0].len());
                for v in a {
                    f(v)?;
                }
                Ok(())
            })
        }
    }

    /// Single read with owning entity and fallible closure.
    pub fn for_each_entity_r1_fallible<A>(
        &self,
        query: BuiltQuery,
        f: impl Fn(Entity, &A) -> ECSResult<()> + Send + Sync,
    ) -> ECSResult<()>
    where
        A: 'static + Send + Sync,
    {
        <(Read<A>,) as QueryParam>::validate(&query)?;
        unsafe {
            self.for_each_entity_abstraction_fallible(query, move |entities, reads, _| {
                let a = cast_slice::<A>(reads[0].as_ptr(), reads[0].len());
                debug_assert_eq!(entities.len(), a.len());
                for i in 0..a.len() {
                    f(entities[i], &a[i])?;
                }
                Ok(())
            })
        }
    }

    /// Single write, fallible closure.
    pub fn for_each_w1_fallible<A>(
        &self,
        query: BuiltQuery,
        f: impl Fn(&mut A) -> ECSResult<()> + Send + Sync,
    ) -> ECSResult<()>
    where
        A: 'static + Send + Sync,
    {
        <(Write<A>,) as QueryParam>::validate(&query)?;
        unsafe {
            self.for_each_abstraction_fallible(query, move |_, writes| {
                let slice = cast_slice_mut::<A>(writes[0].as_mut_ptr(), writes[0].len());
                for item in slice {
                    f(item)?;
                }
                Ok(())
            })
        }
    }

    /// Single write with owning entity and fallible closure.
    pub fn for_each_entity_w1_fallible<A>(
        &self,
        query: BuiltQuery,
        f: impl Fn(Entity, &mut A) -> ECSResult<()> + Send + Sync,
    ) -> ECSResult<()>
    where
        A: 'static + Send + Sync,
    {
        <(Write<A>,) as QueryParam>::validate(&query)?;
        unsafe {
            self.for_each_entity_abstraction_fallible(query, move |entities, _, writes| {
                let slice = cast_slice_mut::<A>(writes[0].as_mut_ptr(), writes[0].len());
                debug_assert_eq!(entities.len(), slice.len());
                for i in 0..slice.len() {
                    f(entities[i], &mut slice[i])?;
                }
                Ok(())
            })
        }
    }

    /// Two reads, fallible closure.
    pub fn for_each_r2_fallible<A, B>(
        &self,
        query: BuiltQuery,
        f: impl Fn(&A, &B) -> ECSResult<()> + Send + Sync,
    ) -> ECSResult<()>
    where
        A: 'static + Send + Sync,
        B: 'static + Send + Sync,
    {
        <(Read<A>, Read<B>) as QueryParam>::validate(&query)?;
        unsafe {
            self.for_each_abstraction_fallible(query, move |reads, _| {
                let a = cast_slice::<A>(reads[0].as_ptr(), reads[0].len());
                let b = cast_slice::<B>(reads[1].as_ptr(), reads[1].len());
                debug_assert_eq!(a.len(), b.len());
                for i in 0..a.len() {
                    f(&a[i], &b[i])?;
                }
                Ok(())
            })
        }
    }

    /// One read, one write, fallible closure.
    pub fn for_each_r1w1_fallible<A, B>(
        &self,
        query: BuiltQuery,
        f: impl Fn(&A, &mut B) -> ECSResult<()> + Send + Sync,
    ) -> ECSResult<()>
    where
        A: 'static + Send + Sync,
        B: 'static + Send + Sync,
    {
        <(Read<A>, Write<B>) as QueryParam>::validate(&query)?;
        unsafe {
            self.for_each_abstraction_fallible(query, move |reads, writes| {
                let a = cast_slice::<A>(reads[0].as_ptr(), reads[0].len());
                let b = cast_slice_mut::<B>(writes[0].as_mut_ptr(), writes[0].len());
                debug_assert_eq!(a.len(), b.len());
                for i in 0..a.len() {
                    f(&a[i], &mut b[i])?;
                }
                Ok(())
            })
        }
    }

    /// One read, one write, with owning entity and fallible closure.
    pub fn for_each_entity_r1w1_fallible<A, B>(
        &self,
        query: BuiltQuery,
        f: impl Fn(Entity, &A, &mut B) -> ECSResult<()> + Send + Sync,
    ) -> ECSResult<()>
    where
        A: 'static + Send + Sync,
        B: 'static + Send + Sync,
    {
        <(Read<A>, Write<B>) as QueryParam>::validate(&query)?;
        unsafe {
            self.for_each_entity_abstraction_fallible(query, move |entities, reads, writes| {
                let a = cast_slice::<A>(reads[0].as_ptr(), reads[0].len());
                let b = cast_slice_mut::<B>(writes[0].as_mut_ptr(), writes[0].len());
                debug_assert_eq!(entities.len(), a.len());
                debug_assert_eq!(a.len(), b.len());
                for i in 0..a.len() {
                    f(entities[i], &a[i], &mut b[i])?;
                }
                Ok(())
            })
        }
    }

    /// Two reads, one write, fallible closure.
    pub fn for_each_r2w1_fallible<A, B, C>(
        &self,
        query: BuiltQuery,
        f: impl Fn(&A, &B, &mut C) -> ECSResult<()> + Send + Sync,
    ) -> ECSResult<()>
    where
        A: 'static + Send + Sync,
        B: 'static + Send + Sync,
        C: 'static + Send + Sync,
    {
        <(Read<A>, Read<B>, Write<C>) as QueryParam>::validate(&query)?;
        unsafe {
            self.for_each_abstraction_fallible(query, move |reads, writes| {
                let a = cast_slice::<A>(reads[0].as_ptr(), reads[0].len());
                let b = cast_slice::<B>(reads[1].as_ptr(), reads[1].len());
                let c = cast_slice_mut::<C>(writes[0].as_mut_ptr(), writes[0].len());
                debug_assert_eq!(a.len(), b.len());
                debug_assert_eq!(a.len(), c.len());
                for i in 0..a.len() {
                    f(&a[i], &b[i], &mut c[i])?;
                }
                Ok(())
            })
        }
    }

    /// Random-access single-entity component read.
    pub fn read_entity_component<T: 'static + Clone>(
        &self,
        entity: Entity,
        component_id: ComponentID,
    ) -> ECSResult<T> {
        let _phase = self.manager.phase_read()?;
        let data = unsafe { self.manager.data_ref_unchecked(&_phase) };
        data.read_component::<T>(entity, component_id)
    }

    /// Finalises boundary channels with scheduler-derived backend profiles.
    #[inline]
    pub(crate) fn finalise_boundaries_with_profiles(
        &self,
        channels: &[ChannelID],
        profiles: &[crate::engine::boundary::BoundaryChannelProfile],
    ) -> ECSResult<()> {
        self.manager
            .finalise_boundaries_with_profiles(channels, profiles)
    }
}

/// Shared-reference-like pointer to the resource behind a boundary guard.
///
/// Semantically this is a `&R` whose lifetime is enforced by the guard field
/// that always accompanies it, so its thread-safety impls mirror `&R`
/// (`Send`/`Sync` iff `R: Sync`). The struct's overall auto-traits therefore
/// remain exactly those of the guard, as before the pointer was cached.
struct TypedResourcePtr<R>(std::ptr::NonNull<R>);

// SAFETY: `TypedResourcePtr` is only ever dereferenced immutably, like `&R`,
// and `&R: Send + Sync` requires exactly `R: Sync`.
unsafe impl<R: Sync> Send for TypedResourcePtr<R> {}
// SAFETY: as above - shared access only exposes `&R`.
unsafe impl<R: Sync> Sync for TypedResourcePtr<R> {}

/// Short-lived typed reference to a boundary resource.
///
/// Acquired via [`ECSReference::boundary`]. Owns a per-resource read guard
/// (no other reader is blocked, write locks block until all handles are
/// dropped) and dereferences to `R`. Drop promptly.
pub struct BoundaryHandle<R: BoundaryResource + 'static> {
    /// Held for its RAII effect: keeps the per-resource read lock (and the
    /// resource behind `typed`) alive until the handle drops.
    #[allow(dead_code)]
    guard: ArcRwLockReadGuard<RawRwLock, dyn BoundaryResource>,
    /// Typed view of the resource behind `guard`, resolved once at
    /// construction so `Deref` avoids a downcast per call.
    typed: TypedResourcePtr<R>,
    _phantom: std::marker::PhantomData<R>,
}

impl<R: BoundaryResource + 'static> std::ops::Deref for BoundaryHandle<R> {
    type Target = R;

    fn deref(&self) -> &R {
        // SAFETY: `typed` was resolved from the resource behind `guard` at
        // construction. The Arc'd read guard keeps the resource alive at a
        // stable address and excludes writers for the handle's lifetime.
        unsafe { self.typed.0.as_ref() }
    }
}