algeon-query-runtime 0.1.2

Native query runtime, lifecycle, ledger, and observation owners.
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
//! Immutable per-device resource-controller profile.

use std::fmt;

use query_planning::{
    admission::ExecutionCapability,
    error::{QueryError, QueryErrorCode, Result, bytes_with_gib},
};

const OPERATION: &str = "query_engine.gpu.resource_profile";

/// Stable identity of one device-execution capability required by a native
/// attempt.
///
/// Values are frozen into a device profile at installation; placement never
/// probes or mutates them at submission time.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DeviceCapability {
    capability: ExecutionCapability,
}

impl DeviceCapability {
    /// Creates one immutable device capability identity.
    pub const fn new(name: &'static str) -> Self {
        Self { capability: ExecutionCapability::new(name) }
    }

    const fn from_requirement(requirement: ExecutionCapability) -> Self {
        Self { capability: requirement }
    }
}

/// Immutable capability metadata for one installed CUDA device.
///
/// Existing supported hardware declares every execution capability available on
/// that device.
/// Installers may instead freeze an exact list for heterogeneous deployments.
/// A non-modeled requirement is never accepted merely because it appears in
/// an exact list; the planner must establish the contract first.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeviceCapabilities {
    support: DeviceCapabilitySupport,
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum DeviceCapabilitySupport {
    All,
    Exact(Vec<DeviceCapability>),
}

impl Default for DeviceCapabilities {
    fn default() -> Self {
        Self::all()
    }
}

impl DeviceCapabilities {
    /// Supports every declared execution capability.
    pub(crate) const fn all() -> Self {
        Self { support: DeviceCapabilitySupport::All }
    }

    /// Supports only the supplied capability identities.
    ///
    /// This is the per-device construction input for heterogeneous
    /// deployments.  Duplicate entries are harmless and do not change
    /// placement semantics.
    pub fn only(capabilities: impl IntoIterator<Item = DeviceCapability>) -> Self {
        let mut exact = Vec::new();
        for capability in capabilities {
            if !exact.contains(&capability) {
                exact.push(capability);
            }
        }
        Self { support: DeviceCapabilitySupport::Exact(exact) }
    }

    pub(crate) fn supports(&self, requirement: &ExecutionCapability) -> bool {
        match &self.support {
            DeviceCapabilitySupport::All => true,
            DeviceCapabilitySupport::Exact(capabilities) => {
                capabilities.contains(&DeviceCapability::from_requirement(*requirement))
            },
        }
    }

    pub(crate) fn supports_all(&self, requirements: &[ExecutionCapability]) -> bool {
        requirements.iter().all(|requirement| self.supports(requirement))
    }

    /// Whether admission must receive an explicit planner-produced requirement.
    ///
    /// An absent requirement is safe only when every execution capability is
    /// accepted. Exact profiles must not interpret an empty implicit set as
    /// evidence that the attempt can execute on the device.
    pub(crate) const fn requires_explicit_attempt_requirement(&self) -> bool {
        matches!(self.support, DeviceCapabilitySupport::Exact(_))
    }
}

/// Frozen capacity and execution-slot bounds for one CUDA device.
///
/// `cache_cap_bytes` (`K`) reserves a bounded per-device cache share taken
/// from the managed capacity (`M`). Query grants and frozen residents share
/// only the remaining query share (`Q = M - K`); query admission never
/// promises the same bytes that back the cache share.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeviceResourceProfile {
    /// CUDA device whose ledger owns this resource profile.
    pub device_ordinal: usize,
    /// Capability metadata frozen with this device's resource envelope.
    pub device_capabilities: DeviceCapabilities,
    pub(crate) configured_limit_bytes: u64,
    pub(crate) headroom_bytes: u64,
    pub(crate) backend_reserve_bytes: u64,
    /// `configured_limit_bytes - headroom_bytes`, before the backend reserve.
    pub(crate) usable_capacity_bytes: u64,
    /// `M`: the bytes the ledger may promise to grants, residents, and cache.
    pub managed_capacity_bytes: u64,
    /// Default immutable grant in bytes, before any resident-capacity adjustment at admission.
    pub default_query_limit_bytes: u64,
    /// `A_d`. Also the number of lifecycle job permits, root streams, and
    /// attempt lanes.
    pub max_active_attempts: usize,
    /// Equals `max_active_attempts`; one lane per admitted attempt.
    pub root_lane_count: usize,
    /// Equals `max_active_attempts`; one root stream per admitted attempt.
    pub root_stream_count: usize,
    /// `S_d`, normalized to at least 1.
    pub source_work_per_attempt: usize,
    /// `A_d * S_d`: auxiliary stream slots and execution job permits for the
    /// whole device.
    pub(crate) aux_source_work_capacity: usize,
    /// At least `A_d + A_d * S_d`, checked by `resolve`.
    pub stream_pool_size: usize,
    /// At least `A_d + A_d * S_d`, checked by `resolve`.
    pub worker_job_capacity: usize,
    /// Cache share reserved from managed capacity in bytes.
    pub cache_cap_bytes: u64,
}

/// Immutable input contract for one device's resolved resource envelope.
///
/// These fields jointly define the admission envelope one device freezes at
/// installation: capacity splits, the default query limit, sloting, and cache
/// share. `resolve` consumes the envelope; the derived capacities, lane and
/// stream counts, and aux-source-work arithmetic stay computed outputs on
/// [`DeviceResourceProfile`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct DeviceResourceEnvelope {
    /// Device ordinal this envelope resolves for.
    pub(crate) device_ordinal: usize,
    pub(crate) device_capabilities: DeviceCapabilities,
    /// Total configured allocation limit before headroom.
    pub(crate) configured_limit_bytes: u64,
    /// Headroom subtracted from the configured limit before backend reserve.
    pub(crate) headroom_bytes: u64,
    /// Backend-reserved bytes unavailable to managed attempts.
    pub(crate) backend_reserve_bytes: u64,
    /// Default per-query limit guaranteed inside managed capacity.
    pub(crate) default_query_limit_bytes: u64,
    /// Maximum simultaneously admitted attempts.
    pub(crate) max_active_attempts: usize,
    /// Auxiliary slots granted per attempt.
    ///
    /// Each slot backs one auxiliary permit holder of the attempt: an
    /// execution lane, a source worker, or an auxiliary fragment context.
    /// The native route serves one disjoint fork subset per live holder, so
    /// this count sizes the attempt's fork pool, and it is one input to the execution width below.
    /// Execution width is the minimum of this envelope, the free permits,
    /// the device execution-job capacity, and the ready work.
    pub(crate) source_work_per_attempt: usize,
    /// Installed stream-pool size; must cover root and auxiliary work.
    pub(crate) stream_pool_size: usize,
    /// Installed worker-job capacity; must cover root and auxiliary work.
    pub(crate) worker_job_capacity: usize,
    /// Bounded per-device cache share reserved alongside the default query limit.
    pub(crate) cache_cap_bytes: u64,
}

impl DeviceResourceProfile {
    /// Query share (`Q = M - K`) promisable to grants plus frozen residents.
    ///
    /// Cache charges (`C <= K`) never participate in this share, so query
    /// admission and cache eviction cannot promise the same bytes.
    pub fn query_share_bytes(&self) -> u64 {
        self.managed_capacity_bytes.saturating_sub(self.cache_cap_bytes)
    }

    /// Derives the default per-query grant from the service parallelism
    /// target: `floor((M - K) / N)` with checked arithmetic.
    ///
    /// This is a capacity-allocation policy that does not estimate the memory a
    /// query needs. With no frozen residents the profile admits `N` default
    /// grants. An explicitly configured default keeps its value after validation.
    pub(crate) fn derive_default_query_limit_bytes(
        device_ordinal: usize,
        managed_capacity_bytes: u64,
        cache_cap_bytes: u64,
        max_active_attempts: usize,
    ) -> Result<u64> {
        if max_active_attempts == 0 {
            return Err(
                invalid(device_ordinal, "max_active_attempts", "must be greater than zero").with_fact("reason", "zero")
            );
        }
        let query_share_bytes =
            managed_capacity_bytes.checked_sub(cache_cap_bytes).filter(|share| *share > 0).ok_or_else(|| {
                invalid(
                    device_ordinal,
                    "cache_cap_bytes",
                    format!(
                        "is {}, at or above the managed capacity of {}; the largest accepted value is {}",
                        bytes_with_gib(cache_cap_bytes),
                        bytes_with_gib(managed_capacity_bytes),
                        bytes_with_gib(managed_capacity_bytes.saturating_sub(1)),
                    ),
                )
                .with_fact("reason", "cache_cap_exceeds_managed_capacity")
                .with_fact("cache_cap_bytes", cache_cap_bytes)
                .with_fact("managed_capacity_bytes", managed_capacity_bytes)
            })?;
        let divisor = u64::try_from(max_active_attempts).map_err(|_| {
            invalid(device_ordinal, "max_active_attempts", "parallelism target exceeds the capacity integer range")
                .with_fact("reason", "max_active_attempts_overflow")
        })?;
        let derived = query_share_bytes.checked_div(divisor).filter(|cap| *cap > 0).ok_or_else(|| {
            invalid(device_ordinal, "default_query_limit_bytes", "derived default query limit is zero")
                .with_fact("reason", "derived_default_query_limit_is_zero")
                .with_fact("query_share_bytes", query_share_bytes)
                .with_fact("max_active_attempts", max_active_attempts)
        })?;
        Ok(derived)
    }

    /// Resolves all resource-controller arithmetic for one device from its
    /// immutable resource envelope.
    pub(crate) fn resolve(envelope: DeviceResourceEnvelope) -> Result<Self> {
        let DeviceResourceEnvelope {
            device_ordinal,
            device_capabilities,
            configured_limit_bytes,
            headroom_bytes,
            backend_reserve_bytes,
            default_query_limit_bytes,
            max_active_attempts,
            source_work_per_attempt,
            stream_pool_size,
            worker_job_capacity,
            cache_cap_bytes,
        } = envelope;
        let usable_capacity_bytes = configured_limit_bytes.checked_sub(headroom_bytes).ok_or_else(|| {
            invalid(
                device_ordinal,
                "headroom_bytes",
                format!(
                    "is {}, above the configured limit of {}",
                    bytes_with_gib(headroom_bytes),
                    bytes_with_gib(configured_limit_bytes),
                ),
            )
            .with_fact("reason", "configured_limit_below_headroom")
            .with_fact("configured_limit_bytes", configured_limit_bytes)
            .with_fact("headroom_bytes", headroom_bytes)
        })?;
        let managed_capacity_bytes = usable_capacity_bytes.checked_sub(backend_reserve_bytes).ok_or_else(|| {
            invalid(
                device_ordinal,
                "backend_reserve_bytes",
                format!(
                    "is {}, above the usable capacity of {}; the largest accepted value is {}",
                    bytes_with_gib(backend_reserve_bytes),
                    bytes_with_gib(usable_capacity_bytes),
                    bytes_with_gib(usable_capacity_bytes.saturating_sub(1)),
                ),
            )
            .with_fact("reason", "backend_reserve_exceeds_usable_capacity")
            .with_fact("usable_capacity_bytes", usable_capacity_bytes)
            .with_fact("backend_reserve_bytes", backend_reserve_bytes)
        })?;
        if managed_capacity_bytes == 0 {
            return Err(invalid(
                device_ordinal,
                "managed_capacity_bytes",
                format!(
                    "is zero; backend_reserve_bytes of {} takes the whole usable capacity of {}",
                    bytes_with_gib(backend_reserve_bytes),
                    bytes_with_gib(usable_capacity_bytes),
                ),
            )
            .with_fact("reason", "zero_managed_capacity"));
        }
        if cache_cap_bytes >= managed_capacity_bytes {
            return Err(invalid(
                device_ordinal,
                "cache_cap_bytes",
                format!(
                    "is {}, at or above the managed capacity of {}; the largest accepted value is {}",
                    bytes_with_gib(cache_cap_bytes),
                    bytes_with_gib(managed_capacity_bytes),
                    bytes_with_gib(managed_capacity_bytes - 1),
                ),
            )
            .with_fact("reason", "cache_cap_exceeds_managed_capacity")
            .with_fact("cache_cap_bytes", cache_cap_bytes)
            .with_fact("managed_capacity_bytes", managed_capacity_bytes));
        }
        if max_active_attempts == 0 {
            return Err(
                invalid(device_ordinal, "max_active_attempts", "must be greater than zero").with_fact("reason", "zero")
            );
        }
        if default_query_limit_bytes == 0 {
            return Err(invalid(device_ordinal, "default_query_limit_bytes", "must be greater than zero")
                .with_fact("reason", "zero"));
        }
        let query_share_bytes = managed_capacity_bytes.checked_sub(cache_cap_bytes).ok_or_else(|| {
            invalid(device_ordinal, "cache_cap_bytes", "cache cap and query share overflow capacity arithmetic")
                .with_fact("reason", "cache_cap_overflow")
        })?;
        if default_query_limit_bytes > query_share_bytes {
            return Err(invalid(
                device_ordinal,
                "default_query_limit_bytes",
                format!(
                    "is {}, above the query share of {} (managed capacity {} minus cache_cap_bytes {}); the largest accepted value is {}",
                    bytes_with_gib(default_query_limit_bytes),
                    bytes_with_gib(query_share_bytes),
                    bytes_with_gib(managed_capacity_bytes),
                    bytes_with_gib(cache_cap_bytes),
                    bytes_with_gib(query_share_bytes),
                ),
            )
            .with_fact("reason", "default_query_limit_exceeds_managed_capacity")
            .with_fact("default_query_limit_bytes", default_query_limit_bytes)
            .with_fact("query_share_bytes", query_share_bytes)
            .with_fact("managed_capacity_bytes", managed_capacity_bytes));
        }
        let source_work_per_attempt = source_work_per_attempt.max(1);
        let aux_source_work_capacity = max_active_attempts.checked_mul(source_work_per_attempt).ok_or_else(|| {
            invalid(device_ordinal, "source_work_per_attempt", "auxiliary source-work capacity overflowed")
                .with_fact("reason", "aux_source_work_overflow")
        })?;
        let required_slots = max_active_attempts.checked_add(aux_source_work_capacity).ok_or_else(|| {
            invalid(device_ordinal, "stream_pool_size", "required stream capacity overflowed")
                .with_fact("reason", "required_slot_overflow")
        })?;
        for (field, actual) in [("stream_pool_size", stream_pool_size), ("worker_job_capacity", worker_job_capacity)] {
            if actual < required_slots {
                return Err(invalid(device_ordinal, field, "must cover root and auxiliary source work")
                    .with_fact("reason", "below_required_slot_capacity")
                    .with_fact("required_slot_capacity", required_slots)
                    .with_fact("actual_capacity", actual));
            }
        }
        Ok(Self {
            device_ordinal,
            device_capabilities,
            configured_limit_bytes,
            headroom_bytes,
            backend_reserve_bytes,
            usable_capacity_bytes,
            managed_capacity_bytes,
            default_query_limit_bytes,
            max_active_attempts,
            root_lane_count: max_active_attempts,
            root_stream_count: max_active_attempts,
            source_work_per_attempt,
            aux_source_work_capacity,
            stream_pool_size,
            worker_job_capacity,
            cache_cap_bytes,
        })
    }
}

fn invalid(device_ordinal: usize, field: &'static str, message: impl fmt::Display) -> QueryError {
    QueryError::new(
        QueryErrorCode::InvalidConfiguration,
        OPERATION,
        format!("device {device_ordinal} {field} {message}"),
    )
    .with_fact("device_ordinal", device_ordinal)
    .with_fact("field", field)
}

#[cfg(test)]
mod tests {
    use query_planning::admission::ExecutionCapability;

    use super::*;

    #[test]
    fn resolves_heterogeneous_profiles_and_slot_math() {
        let small = /*OK*/DeviceResourceProfile::resolve(DeviceResourceEnvelope {
            device_ordinal: 0,
            configured_limit_bytes: 1_000,
            headroom_bytes: 100,
            backend_reserve_bytes: 100,
            default_query_limit_bytes: 100,
            max_active_attempts: 2,
            source_work_per_attempt: 3,
            stream_pool_size: 8,
            worker_job_capacity: 8,
            device_capabilities: DeviceCapabilities::default(),
            cache_cap_bytes: 0,
        }).unwrap();
        let large = DeviceResourceProfile::resolve(DeviceResourceEnvelope {
            device_ordinal: 1,
            configured_limit_bytes: 2_000,
            headroom_bytes: 200,
            backend_reserve_bytes: 100,
            default_query_limit_bytes: 100,
            max_active_attempts: 3,
            source_work_per_attempt: 1,
            stream_pool_size: 6,
            worker_job_capacity: 6,
            device_capabilities: DeviceCapabilities::default(),
            cache_cap_bytes: 0,
        })
        .unwrap();
        assert_eq!((small.usable_capacity_bytes, small.managed_capacity_bytes), (900, 800));
        assert_eq!((small.root_lane_count, small.root_stream_count, small.aux_source_work_capacity), (2, 2, 6));
        assert_eq!((large.usable_capacity_bytes, large.managed_capacity_bytes), (1_800, 1_700));
    }

    #[test]
    fn rejects_invalid_capacity_and_query_limit_arithmetic() {
        for (limit, headroom, reserve, reason) in [
            (99, 100, 0, "configured_limit_below_headroom"),
            (100, 0, 101, "backend_reserve_exceeds_usable_capacity"),
            (100, 0, 100, "zero_managed_capacity"),
        ] {
            let error = DeviceResourceProfile::resolve(DeviceResourceEnvelope {
                device_ordinal: 7,
                configured_limit_bytes: limit,
                headroom_bytes: headroom,
                backend_reserve_bytes: reserve,
                default_query_limit_bytes: 0,
                max_active_attempts: 1,
                source_work_per_attempt: 1,
                stream_pool_size: 2,
                worker_job_capacity: 2,
                device_capabilities: DeviceCapabilities::default(),
                cache_cap_bytes: 0,
            })
            .unwrap_err();
            assert_eq!(error.fact_value("device_ordinal"), Some("7"));
            assert_eq!(error.fact_value("reason"), Some(reason));
        }
        let error = DeviceResourceProfile::resolve(DeviceResourceEnvelope {
            device_ordinal: 7,
            configured_limit_bytes: u64::MAX - 1,
            headroom_bytes: 0,
            backend_reserve_bytes: 0,
            default_query_limit_bytes: u64::MAX,
            max_active_attempts: 2,
            source_work_per_attempt: 1,
            stream_pool_size: 4,
            worker_job_capacity: 4,
            device_capabilities: DeviceCapabilities::default(),
            cache_cap_bytes: 0,
        })
        .unwrap_err();
        assert_eq!(error.fact_value("reason"), Some("default_query_limit_exceeds_managed_capacity"));
    }

    #[test]
    fn validates_cache_cap_against_managed_capacity() {
        let profile = DeviceResourceProfile::resolve(DeviceResourceEnvelope {
            device_ordinal: 0,
            configured_limit_bytes: 1_000,
            headroom_bytes: 0,
            backend_reserve_bytes: 0,
            default_query_limit_bytes: 100,
            max_active_attempts: 2,
            source_work_per_attempt: 1,
            stream_pool_size: 4,
            worker_job_capacity: 4,
            device_capabilities: DeviceCapabilities::default(),
            cache_cap_bytes: 800,
        })
        .unwrap();
        assert_eq!(profile.cache_cap_bytes, 800);
        let error = DeviceResourceProfile::resolve(DeviceResourceEnvelope {
            device_ordinal: 0,
            configured_limit_bytes: 1_000,
            headroom_bytes: 0,
            backend_reserve_bytes: 0,
            default_query_limit_bytes: 100,
            max_active_attempts: 2,
            source_work_per_attempt: 1,
            stream_pool_size: 4,
            worker_job_capacity: 4,
            device_capabilities: DeviceCapabilities::default(),
            cache_cap_bytes: 1_001,
        })
        .unwrap_err();
        assert_eq!(error.fact_value("reason"), Some("cache_cap_exceeds_managed_capacity"));
    }

    #[test]
    fn rejects_zero_default_query_limit_for_an_otherwise_valid_profile() {
        let error = DeviceResourceProfile::resolve(DeviceResourceEnvelope {
            device_ordinal: 7,
            configured_limit_bytes: 100,
            headroom_bytes: 0,
            backend_reserve_bytes: 0,
            default_query_limit_bytes: 0,
            max_active_attempts: 1,
            source_work_per_attempt: 1,
            stream_pool_size: 2,
            worker_job_capacity: 2,
            device_capabilities: DeviceCapabilities::default(),
            cache_cap_bytes: 0,
        })
        .unwrap_err();
        assert_eq!(error.fact_value("field"), Some("default_query_limit_bytes"));
        assert_eq!(error.fact_value("reason"), Some("zero"));
    }

    #[test]
    fn rejects_query_limit_and_slot_capacity_below_requirements() {
        let query_limit = DeviceResourceProfile::resolve(DeviceResourceEnvelope {
            device_ordinal: 3,
            configured_limit_bytes: 100,
            headroom_bytes: 0,
            backend_reserve_bytes: 0,
            default_query_limit_bytes: 101,
            max_active_attempts: 2,
            source_work_per_attempt: 1,
            stream_pool_size: 4,
            worker_job_capacity: 4,
            device_capabilities: DeviceCapabilities::default(),
            cache_cap_bytes: 0,
        })
        .unwrap_err();
        assert_eq!(query_limit.fact_value("reason"), Some("default_query_limit_exceeds_managed_capacity"));
        let slots = DeviceResourceProfile::resolve(DeviceResourceEnvelope {
            device_ordinal: 3,
            configured_limit_bytes: 100,
            headroom_bytes: 0,
            backend_reserve_bytes: 0,
            default_query_limit_bytes: 10,
            max_active_attempts: 2,
            source_work_per_attempt: 3,
            stream_pool_size: 7,
            worker_job_capacity: 7,
            device_capabilities: DeviceCapabilities::default(),
            cache_cap_bytes: 0,
        })
        .unwrap_err();
        assert_eq!(slots.fact_value("reason"), Some("below_required_slot_capacity"));
    }

    #[test]
    fn frozen_capability_metadata_requires_exact_matches() {
        let required = ExecutionCapability::new("test_operator");
        let other = ExecutionCapability::new("other_operator");
        let restricted = DeviceCapabilities::only([DeviceCapability::new("test_operator")]);

        assert!(restricted.supports(&required));
        assert!(!restricted.supports(&other));
        assert!(!DeviceCapabilities::only(std::iter::empty::<DeviceCapability>()).supports(&required));
    }

    #[test]
    fn derives_default_query_limit_from_parallelism_target_and_cache_share() {
        // `floor((M - K) / N)`: the plan's `M = 24, K = 8, N = 2` fixture
        // yields 8, so two defaults sum to the query share.
        assert_eq!(DeviceResourceProfile::derive_default_query_limit_bytes(0, 24, 8, 2).unwrap(), 8);
        assert_eq!(DeviceResourceProfile::derive_default_query_limit_bytes(0, 10, 0, 3).unwrap(), 3);
        assert_eq!(DeviceResourceProfile::derive_default_query_limit_bytes(0, 1_000, 0, 1).unwrap(), 1_000);

        let zero_share = DeviceResourceProfile::derive_default_query_limit_bytes(0, 10, 9, 3).unwrap_err();
        assert_eq!(zero_share.fact_value("reason"), Some("derived_default_query_limit_is_zero"));

        let no_share = DeviceResourceProfile::derive_default_query_limit_bytes(0, 8, 8, 2).unwrap_err();
        assert_eq!(no_share.fact_value("reason"), Some("cache_cap_exceeds_managed_capacity"));

        let no_parallelism = DeviceResourceProfile::derive_default_query_limit_bytes(0, 24, 8, 0).unwrap_err();
        assert_eq!(no_parallelism.fact_value("reason"), Some("zero"));
    }

    #[test]
    fn query_share_subtracts_the_cache_share() {
        let envelope = |cache_cap_bytes, default_query_limit_bytes| DeviceResourceEnvelope {
            device_ordinal: 0,
            configured_limit_bytes: 1_000,
            headroom_bytes: 0,
            backend_reserve_bytes: 0,
            default_query_limit_bytes,
            max_active_attempts: 2,
            source_work_per_attempt: 1,
            stream_pool_size: 4,
            worker_job_capacity: 4,
            device_capabilities: DeviceCapabilities::default(),
            cache_cap_bytes,
        };
        let profile = DeviceResourceProfile::resolve(envelope(300, 700)).unwrap();
        assert_eq!(profile.query_share_bytes(), 700);

        let beyond_share = DeviceResourceProfile::resolve(envelope(300, 701)).unwrap_err();
        assert_eq!(beyond_share.fact_value("reason"), Some("default_query_limit_exceeds_managed_capacity"));

        let no_share = DeviceResourceProfile::resolve(envelope(1_000, 1)).unwrap_err();
        assert_eq!(no_share.fact_value("reason"), Some("cache_cap_exceeds_managed_capacity"));
    }
}