ferrum-interfaces 0.8.4

Core trait contracts for the Ferrum LLM inference engine
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
use serde::{Deserialize, Serialize};
use std::collections::BTreeSet;
use std::fmt;

use super::{
    AllocationKind, AllocationLifetime, BufferDescriptor, BufferUsage, CapacityDomainId,
    DeviceDescriptor, DeviceId, ElementType, FailureDomain, FailureEnvelope, NodeId, PlanHash,
    PlanId, RequestIdentity, ResourceAllocation, ResourceId, RunId, TransactionId, VNextError,
};

pub const MAX_RESOURCE_TRANSITION_RECEIPT_WIRE_BYTES: usize = 4 * 1024 * 1024;
pub const MAX_RESOURCE_LEASE_RECEIPT_WIRE_BYTES: usize = 4 * 1024 * 1024;
pub(super) const SEQUENCE_DISPATCH_POISONED_BIT: u64 = 1 << 63;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StateInitialization {
    /// Core does not initialize the backing. The first consumer must fully
    /// define every byte before it is read.
    None,
    /// Core zeroes each exact Sequence backing acquisition before its first
    /// state consumer in the same ordered submission. Request-scope zeroing is
    /// reserved until initialization dependencies can defer sibling sequences.
    Zero,
}

pub(super) fn invalid_resource(reason: impl Into<String>) -> VNextError {
    VNextError::InvalidExecutionPlan {
        reason: reason.into(),
    }
}

pub(super) fn core_resource_failure(
    code: &'static str,
    message: impl Into<String>,
    retryable: bool,
) -> FailureEnvelope {
    FailureEnvelope::new(FailureDomain::Resource, code, message, retryable)
        .expect("core-generated resource failure must be valid")
}

pub(crate) fn validate_runtime_descriptor_for_admission(
    descriptor: &DeviceDescriptor,
    admission: &StaticProvisioningBinding,
    context: &'static str,
) -> Result<(), VNextError> {
    descriptor.validate()?;
    if &descriptor.id != admission.device_id()
        || descriptor.runtime_implementation_fingerprint
            != admission.device_runtime_implementation_fingerprint()
        || descriptor.total_memory_bytes != admission.device_capacity_bytes()
    {
        return Err(invalid_resource(format!(
            "{context} runtime device, runtime implementation, or capacity differs from admission"
        )));
    }
    Ok(())
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ResourceTransactionIdentity {
    pub(super) pool_id: ResourcePoolId,
    pub(super) run_id: RunId,
    pub(super) transaction_id: TransactionId,
    pub(super) request_id: RequestIdentity,
}

impl ResourceTransactionIdentity {
    pub fn for_admission(
        admission: &StaticProvisioningBinding,
        run_id: RunId,
        transaction_id: TransactionId,
    ) -> Self {
        Self {
            pool_id: admission.pool_id(),
            run_id,
            transaction_id,
            request_id: admission.request_id().clone(),
        }
    }

    pub const fn pool_id(&self) -> ResourcePoolId {
        self.pool_id
    }

    pub fn run_id(&self) -> &RunId {
        &self.run_id
    }

    pub fn transaction_id(&self) -> &TransactionId {
        &self.transaction_id
    }

    pub fn request_id(&self) -> &RequestIdentity {
        &self.request_id
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResourceDriverFailure {
    failure: FailureEnvelope,
}

impl ResourceDriverFailure {
    pub fn new(failure: FailureEnvelope) -> Result<Self, VNextError> {
        failure.validate()?;
        if failure.domain() != FailureDomain::Resource {
            return Err(invalid_resource(
                "resource driver failure must use the resource failure domain",
            ));
        }
        Ok(Self { failure })
    }

    pub fn failure(&self) -> &FailureEnvelope {
        &self.failure
    }

    pub fn into_failure(self) -> FailureEnvelope {
        self.failure
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ResourceTransactionState {
    New,
    Reserved,
    Committed,
    RolledBack,
    Released,
    Quarantined,
}

impl ResourceTransactionState {
    pub fn transition(
        self,
        resource_id: &ResourceId,
        action: ResourceTransactionAction,
    ) -> Result<Self, VNextError> {
        expected_transition(action, self).ok_or_else(|| VNextError::InvalidResourceTransition {
            resource_id: resource_id.to_string(),
            from: self.as_str(),
            action: action.as_str(),
        })
    }

    pub const fn as_str(self) -> &'static str {
        match self {
            Self::New => "new",
            Self::Reserved => "reserved",
            Self::Committed => "committed",
            Self::RolledBack => "rolled_back",
            Self::Released => "released",
            Self::Quarantined => "quarantined",
        }
    }

    pub(super) const fn is_live(self) -> bool {
        matches!(self, Self::New | Self::Reserved | Self::Committed)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ResourceTransactionAction {
    Reserve,
    Commit,
    Rollback,
    Release,
    Quarantine,
}

impl ResourceTransactionAction {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Reserve => "reserve",
            Self::Commit => "commit",
            Self::Rollback => "rollback",
            Self::Release => "release",
            Self::Quarantine => "quarantine",
        }
    }
}

pub(super) const fn expected_transition(
    action: ResourceTransactionAction,
    before: ResourceTransactionState,
) -> Option<ResourceTransactionState> {
    match (before, action) {
        (ResourceTransactionState::New, ResourceTransactionAction::Reserve) => {
            Some(ResourceTransactionState::Reserved)
        }
        (ResourceTransactionState::Reserved, ResourceTransactionAction::Commit) => {
            Some(ResourceTransactionState::Committed)
        }
        (ResourceTransactionState::Reserved, ResourceTransactionAction::Rollback) => {
            Some(ResourceTransactionState::RolledBack)
        }
        (ResourceTransactionState::Committed, ResourceTransactionAction::Release) => {
            Some(ResourceTransactionState::Released)
        }
        (
            ResourceTransactionState::New
            | ResourceTransactionState::Reserved
            | ResourceTransactionState::Committed,
            ResourceTransactionAction::Quarantine,
        ) => Some(ResourceTransactionState::Quarantined),
        _ => None,
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ResourceCompensationAction {
    UndoReserve,
    UndoCommit,
}

impl ResourceCompensationAction {
    pub(super) const fn for_prepare_action(action: ResourceTransactionAction) -> Option<Self> {
        match action {
            ResourceTransactionAction::Reserve => Some(Self::UndoReserve),
            ResourceTransactionAction::Commit => Some(Self::UndoCommit),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ResourceRecoveryStrategy {
    ReverseCompensation,
    ForwardCompletion,
    ReconcileOrQuarantine,
}

/// Core-owned retention policy derived from `AllocationLifetime`. A backend or
/// scheduler may decide when to act on it, but may not rewrite it after
/// admission.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ResourceRetentionPolicy {
    Plan,
    Request,
    Sequence,
    Step,
    Invocation,
}

impl From<AllocationLifetime> for ResourceRetentionPolicy {
    fn from(lifetime: AllocationLifetime) -> Self {
        match lifetime {
            AllocationLifetime::Plan => Self::Plan,
            AllocationLifetime::Request => Self::Request,
            AllocationLifetime::Sequence => Self::Sequence,
            AllocationLifetime::Step => Self::Step,
            AllocationLifetime::Invocation => Self::Invocation,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ResourceRetentionDecision {
    Retain,
    ReturnRequested,
}

/// Process-local identity of one provisioned resource pool. It is independent
/// from both the request that provisioned the pool and requests that later use
/// one of its active-sequence slots.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(try_from = "u64", into = "u64")]
pub struct ResourcePoolId(u64);

impl ResourcePoolId {
    pub(super) fn issue(generation: u64) -> Result<Self, VNextError> {
        Self::try_from(generation)
    }

    pub const fn get(self) -> u64 {
        self.0
    }
}

impl TryFrom<u64> for ResourcePoolId {
    type Error = VNextError;

    fn try_from(value: u64) -> Result<Self, Self::Error> {
        if value == 0 {
            return Err(invalid_resource("resource pool id must be non-zero"));
        }
        Ok(Self(value))
    }
}

impl From<ResourcePoolId> for u64 {
    fn from(value: ResourcePoolId) -> Self {
        value.0
    }
}

impl fmt::Display for ResourcePoolId {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "resource-pool:{}", self.0)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ResourcePoolIdentity {
    pub(super) pool_id: ResourcePoolId,
    pub(super) plan_id: PlanId,
    pub(super) plan_hash: PlanHash,
    pub(super) device_id: DeviceId,
    pub(super) device_runtime_implementation_fingerprint: String,
    pub(super) admission_generation: u64,
}

impl ResourcePoolIdentity {
    pub const fn pool_id(&self) -> ResourcePoolId {
        self.pool_id
    }

    pub fn plan_id(&self) -> &PlanId {
        &self.plan_id
    }

    pub fn plan_hash(&self) -> &PlanHash {
        &self.plan_hash
    }

    pub fn device_id(&self) -> &DeviceId {
        &self.device_id
    }

    pub fn device_runtime_implementation_fingerprint(&self) -> &str {
        &self.device_runtime_implementation_fingerprint
    }

    pub const fn admission_generation(&self) -> u64 {
        self.admission_generation
    }
}

/// Immutable identity and capacity envelope signed into an admission permit.
/// This is trusted output and intentionally cannot be deserialized directly.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct StaticProvisioningBinding {
    pub(super) pool_identity: ResourcePoolIdentity,
    pub(super) plan_id: PlanId,
    pub(super) plan_hash: PlanHash,
    pub(super) request_id: RequestIdentity,
    pub(super) device_id: DeviceId,
    pub(super) device_runtime_implementation_fingerprint: String,
    pub(super) device_capacity_bytes: u64,
    pub(super) usable_capacity_bytes: u64,
    pub(super) plan_static_bytes: u64,
    pub(super) admitted_bytes: u64,
    pub(super) maximum_active_sequences: u32,
    pub(super) admission_generation: u64,
}

impl StaticProvisioningBinding {
    pub fn pool_identity(&self) -> &ResourcePoolIdentity {
        &self.pool_identity
    }

    pub const fn pool_id(&self) -> ResourcePoolId {
        self.pool_identity.pool_id
    }
    pub fn plan_id(&self) -> &PlanId {
        &self.plan_id
    }

    pub fn plan_hash(&self) -> &PlanHash {
        &self.plan_hash
    }

    pub fn request_id(&self) -> &RequestIdentity {
        &self.request_id
    }

    pub fn device_id(&self) -> &DeviceId {
        &self.device_id
    }

    pub fn device_runtime_implementation_fingerprint(&self) -> &str {
        &self.device_runtime_implementation_fingerprint
    }

    pub const fn device_capacity_bytes(&self) -> u64 {
        self.device_capacity_bytes
    }

    pub const fn usable_capacity_bytes(&self) -> u64 {
        self.usable_capacity_bytes
    }

    pub const fn plan_static_bytes(&self) -> u64 {
        self.plan_static_bytes
    }

    pub const fn admitted_bytes(&self) -> u64 {
        self.admitted_bytes
    }

    pub const fn maximum_active_sequences(&self) -> u32 {
        self.maximum_active_sequences
    }

    pub const fn admission_generation(&self) -> u64 {
        self.admission_generation
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ResourceReservation {
    pub(super) resource_id: ResourceId,
    pub(super) request_id: RequestIdentity,
    pub(super) owner_node_id: Option<NodeId>,
    pub(super) size_bytes: u64,
    pub(super) alignment_bytes: u64,
    pub(super) usage: BufferUsage,
    pub(super) element_type: ElementType,
    pub(super) retention_policy: ResourceRetentionPolicy,
    pub(super) backing_domain_id: Option<CapacityDomainId>,
    pub(super) generation: u64,
}

impl ResourceReservation {
    fn from_allocation(
        allocation: &ResourceAllocation,
        request_id: &RequestIdentity,
        generation: u64,
    ) -> Result<Self, VNextError> {
        let owner_node_id = match allocation.kind() {
            AllocationKind::Value | AllocationKind::InitializationScratch => None,
            AllocationKind::Scratch { node_id, .. }
            | AllocationKind::Binding { node_id, .. }
            | AllocationKind::Persistent { node_id, .. } => Some(node_id.clone()),
        };
        if allocation.size_bytes() == 0
            || allocation.alignment_bytes() == 0
            || !allocation.alignment_bytes().is_power_of_two()
            || generation == 0
        {
            return Err(invalid_resource(format!(
                "allocation `{}` cannot be admitted",
                allocation.resource_id()
            )));
        }
        Ok(Self {
            resource_id: allocation.resource_id().clone(),
            request_id: request_id.clone(),
            owner_node_id,
            size_bytes: allocation.size_bytes(),
            alignment_bytes: allocation.alignment_bytes(),
            usage: allocation.usage(),
            element_type: allocation.element_type(),
            retention_policy: allocation.lifetime().into(),
            backing_domain_id: None,
            generation,
        })
    }

    pub fn resource_id(&self) -> &ResourceId {
        &self.resource_id
    }

    pub fn request_id(&self) -> &RequestIdentity {
        &self.request_id
    }

    pub fn owner_node_id(&self) -> Option<&NodeId> {
        self.owner_node_id.as_ref()
    }

    pub const fn size_bytes(&self) -> u64 {
        self.size_bytes
    }

    pub const fn alignment_bytes(&self) -> u64 {
        self.alignment_bytes
    }

    pub const fn usage(&self) -> BufferUsage {
        self.usage
    }

    pub const fn element_type(&self) -> ElementType {
        self.element_type
    }

    pub const fn retention_policy(&self) -> ResourceRetentionPolicy {
        self.retention_policy
    }

    pub const fn backing_domain_id(&self) -> Option<CapacityDomainId> {
        self.backing_domain_id
    }

    pub const fn generation(&self) -> u64 {
        self.generation
    }

    pub(super) fn matches_descriptor(&self, descriptor: &BufferDescriptor) -> bool {
        descriptor.resource_id == self.resource_id
            && descriptor.size_bytes == self.size_bytes
            && descriptor.alignment_bytes == self.alignment_bytes
            && descriptor.usage == self.usage
            && descriptor.element_type == self.element_type
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ResourceReservationBatch {
    request_id: RequestIdentity,
    pub(super) reservations: Vec<ResourceReservation>,
    plan_static_size_bytes: u64,
    total_size_bytes: u64,
}

impl ResourceReservationBatch {
    pub(super) fn from_allocations(
        request_id: &RequestIdentity,
        allocations: &[ResourceAllocation],
        generation: u64,
    ) -> Result<Self, VNextError> {
        let mut ids = BTreeSet::new();
        let mut reservations = Vec::with_capacity(allocations.len());
        let mut plan_static_size_bytes = 0_u64;
        for allocation in allocations {
            if !ids.insert(allocation.resource_id().clone()) {
                return Err(invalid_resource(format!(
                    "resource `{}` is duplicated in admission",
                    allocation.resource_id()
                )));
            }
            plan_static_size_bytes = plan_static_size_bytes
                .checked_add(allocation.size_bytes())
                .ok_or_else(|| invalid_resource("admitted resource bytes overflow u64"))?;
            reservations.push(ResourceReservation::from_allocation(
                allocation, request_id, generation,
            )?);
        }
        let total_size_bytes = plan_static_size_bytes;
        Ok(Self {
            request_id: request_id.clone(),
            reservations,
            plan_static_size_bytes,
            total_size_bytes,
        })
    }

    pub fn request_id(&self) -> &RequestIdentity {
        &self.request_id
    }

    pub fn reservations(&self) -> &[ResourceReservation] {
        &self.reservations
    }

    pub fn resource_ids(&self) -> impl Iterator<Item = &ResourceId> {
        self.reservations
            .iter()
            .map(ResourceReservation::resource_id)
    }

    pub const fn total_size_bytes(&self) -> u64 {
        self.total_size_bytes
    }

    pub const fn plan_static_size_bytes(&self) -> u64 {
        self.plan_static_size_bytes
    }
}