tenferro-runtime 0.7.0

Concrete tensor helpers, traced tensors, graph execution, and extension runtime support for tenferro.
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
use std::any::TypeId;
use std::fmt;
use std::num::NonZeroU64;
use std::sync::Arc;

use super::{IdentityError, IdentityKind};

/// Opaque identity allocated for one [`Runtime`](super::Runtime) instance.
///
/// The runtime uses this value to namespace snapshots, event domains, and
/// prepared execution. Construction and numeric access remain crate-private so
/// callers can compare identities without manufacturing one.
///
/// # Examples
///
/// ```
/// use std::fmt::Debug;
/// use tenferro_runtime::RuntimeId;
///
/// fn requires_debug<T: Debug>() {}
/// requires_debug::<RuntimeId>();
/// ```
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct RuntimeId(NonZeroU64);

impl RuntimeId {
    // INVARIANT: Runtime construction is the sole production allocator; the
    // crate-private constructor keeps the numeric representation opaque.
    #[allow(dead_code)]
    pub(crate) const fn from_nonzero(value: NonZeroU64) -> Self {
        Self(value)
    }

    // INVARIANT: Runtime internals read the value only to namespace runtime
    // snapshots, event domains, and prepared-work validation.
    #[allow(dead_code)]
    pub(crate) const fn get(self) -> NonZeroU64 {
        self.0
    }
}

/// Opaque monotonically increasing configuration epoch for one runtime.
///
/// A new epoch is published when a runtime reconfiguration changes its
/// execution snapshot; prepared work from an older epoch is rejected.
///
/// # Examples
///
/// ```
/// use std::fmt::Debug;
/// use tenferro_runtime::RuntimeEpoch;
///
/// fn requires_debug<T: Debug>() {}
/// requires_debug::<RuntimeEpoch>();
/// ```
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct RuntimeEpoch(NonZeroU64);

impl RuntimeEpoch {
    // INVARIANT: A newly built runtime starts at epoch one; publication is the
    // only production path that advances it.
    #[allow(dead_code)]
    pub(crate) const fn one() -> Self {
        Self(NonZeroU64::MIN)
    }

    // INVARIANT: Snapshot construction supplies validated nonzero epochs while
    // keeping the representation private to the runtime crate.
    #[allow(dead_code)]
    pub(crate) const fn from_nonzero(value: NonZeroU64) -> Self {
        Self(value)
    }

    // INVARIANT: Runtime snapshot and prepared-work validation are the only
    // production consumers of the numeric epoch.
    #[allow(dead_code)]
    pub(crate) const fn get(self) -> NonZeroU64 {
        self.0
    }

    // INVARIANT: Reconfiguration uses `None` to report epoch exhaustion before
    // publishing a wrapped value.
    #[allow(dead_code)]
    pub(crate) fn checked_next(self) -> Option<Self> {
        self.0
            .get()
            .checked_add(1)
            .and_then(NonZeroU64::new)
            .map(Self)
    }
}

/// Validated namespaced identity of an execution engine.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use tenferro_runtime::EngineId;
///
/// assert_eq!(EngineId::new("tenferro.cpu.v1")?.as_str(), "tenferro.cpu.v1");
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct EngineId(Arc<str>);

impl EngineId {
    /// Validate a lowercase ASCII namespaced engine identifier.
    ///
    /// # Examples
    ///
    /// ```
    /// use tenferro_runtime::EngineId;
    ///
    /// assert!(EngineId::new("tenferro.cpu").is_ok());
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`IdentityError`] with [`IdentityKind::Engine`] when `value`
    /// does not match the lowercase ASCII namespaced identifier grammar.
    pub fn new(value: impl Into<Arc<str>>) -> Result<Self, IdentityError> {
        validate_identifier(value.into(), IdentityKind::Engine).map(Self)
    }

    /// Borrow the validated identifier text.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use tenferro_runtime::EngineId;
    ///
    /// assert_eq!(EngineId::new("tenferro.cpu")?.as_str(), "tenferro.cpu");
    /// # Ok(())
    /// # }
    /// ```
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Validated namespaced identity of a runtime provider.
///
/// A provider ID identifies the implementation namespace in the runtime
/// control plane. It is deliberately distinct from tensor placement metadata.
///
/// # Examples
///
/// ```
/// use tenferro_runtime::ProviderId;
///
/// assert_eq!(ProviderId::new("tenferro.cpu")?.as_str(), "tenferro.cpu");
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct ProviderId(Arc<str>);

impl ProviderId {
    /// Validate a lowercase ASCII namespaced provider identifier.
    ///
    /// # Errors
    ///
    /// Returns [`IdentityError`] with [`IdentityKind::Provider`] when `value`
    /// does not match the lowercase ASCII namespaced identifier grammar.
    ///
    /// # Examples
    ///
    /// ```
    /// use tenferro_runtime::ProviderId;
    ///
    /// assert!(ProviderId::new("tenferro.cuda").is_ok());
    /// ```
    pub fn new(value: impl Into<Arc<str>>) -> Result<Self, IdentityError> {
        validate_identifier(value.into(), IdentityKind::Provider).map(Self)
    }

    /// Borrow the validated provider identifier text.
    ///
    /// # Examples
    ///
    /// ```
    /// use tenferro_runtime::ProviderId;
    ///
    /// assert_eq!(ProviderId::new("tenferro.cuda")?.as_str(), "tenferro.cuda");
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Immutable runtime-control-plane binding of a provider to one physical target.
///
/// The target identity is opaque to the runtime and is canonicalized by the
/// provider. It is not [`tenferro_tensor::DeviceId`] or tensor placement data.
/// This immutable provider/target pair is the durable identity carried by
/// runtime snapshots, execution locations, and transfer requests.
/// Because this value appears in structured diagnostics and debug output, it
/// accepts nonempty ASCII graphic text (no controls, whitespace, or Unicode
/// confusables). Providers that need byte-level or Unicode identities must
/// first canonicalize them into an escaped diagnostic-safe ASCII form.
/// Equality, ordering, and hashing include both the provider and target.
///
/// # Examples
///
/// ```
/// use tenferro_runtime::{ProviderDeviceIdentity, ProviderId};
///
/// let identity = ProviderDeviceIdentity::new(ProviderId::new("tenferro.cuda")?, "device-0")?;
/// assert_eq!(identity.provider_id().as_str(), "tenferro.cuda");
/// assert_eq!(identity.target_identity(), "device-0");
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct ProviderDeviceIdentity {
    provider_id: ProviderId,
    target_identity: Arc<str>,
}

impl ProviderDeviceIdentity {
    /// Construct a provider binding from a validated provider and opaque target.
    ///
    /// # Errors
    ///
    /// Returns [`IdentityError`] with [`IdentityKind::ProviderTarget`] when the
    /// provider-canonical target identity is empty or is not ASCII graphic
    /// text. Target text is deliberately diagnostic-safe; opaque
    /// provider-specific byte or Unicode identities must be encoded by the
    /// provider before construction.
    ///
    /// # Examples
    ///
    /// ```
    /// use tenferro_runtime::{ProviderDeviceIdentity, ProviderId};
    ///
    /// let identity = ProviderDeviceIdentity::new(
    ///     ProviderId::new("tenferro.cpu")?,
    ///     "host-0",
    /// )?;
    /// assert_eq!(identity.target_identity(), "host-0");
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn new(
        provider_id: ProviderId,
        target_identity: impl Into<Arc<str>>,
    ) -> Result<Self, IdentityError> {
        let target_identity = target_identity.into();
        if target_identity.is_empty()
            || !target_identity
                .chars()
                .all(|character| character.is_ascii_graphic())
        {
            return Err(IdentityError::malformed(IdentityKind::ProviderTarget));
        }
        Ok(Self {
            provider_id,
            target_identity,
        })
    }

    /// Return the validated provider namespace.
    ///
    /// # Examples
    ///
    /// ```
    /// use tenferro_runtime::{ProviderDeviceIdentity, ProviderId};
    ///
    /// let provider = ProviderId::new("tenferro.cpu")?;
    /// let identity = ProviderDeviceIdentity::new(provider.clone(), "host-0")?;
    /// assert_eq!(identity.provider_id(), &provider);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn provider_id(&self) -> &ProviderId {
        &self.provider_id
    }

    /// Return the provider-canonical opaque target identity.
    ///
    /// # Examples
    ///
    /// ```
    /// use tenferro_runtime::{ProviderDeviceIdentity, ProviderId};
    ///
    /// let identity = ProviderDeviceIdentity::new(ProviderId::new("tenferro.cpu")?, "host-0")?;
    /// assert_eq!(identity.target_identity(), "host-0");
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn target_identity(&self) -> &str {
        &self.target_identity
    }
}

/// Validated namespaced identity of a hardware class.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use tenferro_runtime::HardwareClassId;
///
/// assert_eq!(HardwareClassId::new("tenferro.cpu.host")?.as_str(), "tenferro.cpu.host");
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct HardwareClassId(Arc<str>);

impl HardwareClassId {
    /// Validate a lowercase ASCII namespaced hardware-class identifier.
    ///
    /// # Examples
    ///
    /// ```
    /// use tenferro_runtime::HardwareClassId;
    ///
    /// assert!(HardwareClassId::new("tenferro.cpu").is_ok());
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`IdentityError`] with [`IdentityKind::HardwareClass`] when
    /// `value` does not match the lowercase ASCII namespaced identifier grammar.
    pub fn new(value: impl Into<Arc<str>>) -> Result<Self, IdentityError> {
        validate_identifier(value.into(), IdentityKind::HardwareClass).map(Self)
    }

    /// Borrow the validated identifier text.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use tenferro_runtime::HardwareClassId;
    ///
    /// assert_eq!(HardwareClassId::new("tenferro.cpu")?.as_str(), "tenferro.cpu");
    /// # Ok(())
    /// # }
    /// ```
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Opaque runtime-local identity assigned to one frozen engine registration.
///
/// The identity is part of the durable registration contract: it is preserved
/// when the same registration is carried into a later snapshot, changes when
/// that registration is replaced, and participates in event-domain identity.
/// Its equality, ordering, and hashing include the private issuer and ordinal;
/// debug output exposes only the useful ordinal.
///
/// # Examples
///
/// ```
/// use std::fmt::Debug;
/// use tenferro_runtime::RegistrationIdentity;
///
/// fn requires_debug<T: Debug>() {}
/// requires_debug::<RegistrationIdentity>();
/// ```
#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct RegistrationIdentity {
    issuer: NonZeroU64,
    ordinal: NonZeroU64,
}

impl RegistrationIdentity {
    // INVARIANT: The runtime registration allocator is the sole production
    // issuer; callers receive and compare the opaque identity only.
    #[allow(dead_code)]
    pub(crate) const fn new(issuer: NonZeroU64, ordinal: NonZeroU64) -> Self {
        Self { issuer, ordinal }
    }

    /// Return this registration's runtime-local ordinal.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt::Debug;
    /// use tenferro_runtime::RegistrationIdentity;
    ///
    /// fn requires_debug<T: Debug>() {}
    /// requires_debug::<RegistrationIdentity>();
    /// ```
    pub fn ordinal(self) -> NonZeroU64 {
        self.ordinal
    }
}

impl fmt::Debug for RegistrationIdentity {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("RegistrationIdentity")
            .field("ordinal", &self.ordinal)
            .finish()
    }
}

/// Type identity of an execution context without retaining a context value.
///
/// # Examples
///
/// ```
/// use tenferro_runtime::ExecutionContextIdentity;
///
/// assert_eq!(ExecutionContextIdentity::of::<u64>().type_name(), std::any::type_name::<u64>());
/// ```
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct ExecutionContextIdentity {
    type_id: TypeId,
    type_name: &'static str,
}

impl ExecutionContextIdentity {
    /// Return the identity of a `'static` context type.
    ///
    /// # Examples
    ///
    /// ```
    /// use tenferro_runtime::ExecutionContextIdentity;
    ///
    /// assert_eq!(ExecutionContextIdentity::of::<u64>(), ExecutionContextIdentity::of::<u64>());
    /// ```
    pub fn of<T: 'static>() -> Self {
        Self {
            type_id: TypeId::of::<T>(),
            type_name: std::any::type_name::<T>(),
        }
    }

    /// Return the diagnostic name of the context type.
    ///
    /// # Examples
    ///
    /// ```
    /// use tenferro_runtime::ExecutionContextIdentity;
    ///
    /// assert_eq!(ExecutionContextIdentity::of::<u64>().type_name(), std::any::type_name::<u64>());
    /// ```
    pub fn type_name(&self) -> &'static str {
        self.type_name
    }
}

pub(super) fn validate_identifier(
    value: Arc<str>,
    kind: IdentityKind,
) -> Result<Arc<str>, IdentityError> {
    let valid = value.is_ascii()
        && value.split('.').count() >= 2
        && value.split('.').all(valid_identifier_component);
    valid
        .then_some(value)
        .ok_or_else(|| IdentityError::malformed(kind))
}

fn valid_identifier_component(component: &str) -> bool {
    let bytes = component.as_bytes();
    match bytes {
        [single] => single.is_ascii_lowercase() || single.is_ascii_digit(),
        [first, middle @ .., last] => {
            (first.is_ascii_lowercase() || first.is_ascii_digit())
                && (last.is_ascii_lowercase() || last.is_ascii_digit())
                && middle.iter().all(|byte| {
                    byte.is_ascii_lowercase()
                        || byte.is_ascii_digit()
                        || matches!(byte, b'-' | b'_')
                })
        }
        [] => false,
    }
}