sokr 0.3.0

SOKR core — immutable C ABI surface for substrate plugins
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
//! C ABI type definitions for SOKR core.
//!
//! All types are `#[repr(C)]` for stable C ABI compatibility.

use core::ffi::{c_char, c_void};

/// Version handshake struct for plugin compatibility negotiation.
///
/// ## Version Compatibility Rules
///
/// | Core Version | Plugin Version | Compatible? | Reason |
/// |--------------|----------------|-------------|--------|
/// | 1.2.3 | 1.1.0 | ✅ Yes | Same major, plugin minor ≤ core minor |
/// | 1.2.3 | 1.2.0 | ✅ Yes | Same major, same minor |
/// | 1.2.3 | 1.3.0 | ❌ No | Plugin minor > core minor |
/// | 1.2.3 | 2.0.0 | ❌ No | Major version mismatch |
/// | 1.2.3 | 0.9.0 | ❌ No | Major version mismatch |
///
/// ## Negotiation Sequence
///
/// 1. Core sends its version pointer as first argument to `capability_fn`
/// 2. Plugin inspects core version and determines compatibility
/// 3. Plugin returns `VersionMismatch` if incompatible (never panics)
/// 4. On success, plugin fills response and returns `Ok`
///
/// ## Forward Compatibility
///
/// - Newer plugin on older core: Plugin must check and return `VersionMismatch`
/// - Older plugin on newer core: Allowed if major matches and plugin minor ≤ core minor
///
/// ## Version Bump Triggers
///
/// - **Major**: Any breaking change to C ABI (struct layout, function signatures)
/// - **Minor**: New features, new result codes, new optional fields (backwards compatible)
/// - **Patch**: Documentation fixes, implementation corrections (no ABI change)
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SokrVersion {
    /// Major version - must match between core and plugin.
    pub major: u32,
    /// Minor version - plugin must be ≤ core.
    pub minor: u32,
    /// Patch version - informational only.
    pub patch: u32,
}

impl SokrVersion {
    /// Current SOKR core ABI version (0.3.0).
    pub const CURRENT: Self = Self {
        major: 0,
        minor: 3,
        patch: 0,
    };

    /// Check if this plugin version is compatible with the given core version.
    ///
    /// Returns `SokrResult::Ok` if compatible, `SokrResult::VersionMismatch` otherwise.
    /// This function never panics - incompatible versions are handled gracefully.
    ///
    /// # Compatibility Rules
    /// - `plugin.major` must equal `core.major`
    /// - `plugin.minor` must be ≤ `core.minor`
    /// - `patch` is ignored for compatibility (informational only)
    #[must_use]
    pub const fn check_compatible(self, core: Self) -> SokrResult {
        if self.major != core.major {
            return SokrResult::VersionMismatch;
        }
        if self.minor > core.minor {
            return SokrResult::VersionMismatch;
        }
        SokrResult::Ok
    }
}

/// Static export of current SOKR version for C FFI.
///
/// This is exported as `extern const` (valid at file scope in C),
/// unlike the `SokrVersion_CURRENT` macro which uses compound literals.
// SAFETY: #[no_mangle] on a static is required for C FFI symbol export.
// Symbol collision risk is mitigated by the unique `SOKR_VERSION_CURRENT` name.
#[allow(unsafe_code)]
#[no_mangle]
pub static SOKR_VERSION_CURRENT: SokrVersion = SokrVersion {
    major: 0,
    minor: 3,
    patch: 0,
};

/// Result codes for SOKR operations.
#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SokrResult {
    /// Operation succeeded.
    Ok = 0,
    /// Substrate cannot fulfill this computation.
    CapabilityDenied = 1,
    /// Dispatch failed at runtime.
    DispatchFailed = 2,
    /// Operation timed out.
    Timeout = 3,
    /// Plugin ABI version incompatible with core.
    VersionMismatch = 4,
    /// No registered substrate can fulfill this computation.
    NoCapableSubstrate = 5,
    /// Invalid input parameters.
    InvalidInput = 6,
    /// Invalid IR format.
    InvalidIR = 7,
    /// Resource not found.
    NotFound = 8,
    /// Plugin registry is full.
    RegistryFull = 9,
}

impl SokrResult {
    /// Returns true if the result indicates success.
    #[must_use]
    pub const fn is_ok(self) -> bool {
        matches!(self, Self::Ok)
    }

    /// Returns true if the result indicates an error.
    #[must_use]
    pub const fn is_err(self) -> bool {
        !self.is_ok()
    }
}

/// Opaque 128-bit identifier for a computation unit.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SokrComputationId {
    /// High 64 bits of the identifier.
    pub high: u64,
    /// Low 64 bits of the identifier.
    pub low: u64,
}

/// Computation descriptor for capability queries.
#[repr(C)]
pub struct SokrCapabilityQuery {
    /// Computation to query capability for.
    pub computation_id: SokrComputationId,
    /// IR format identifier (null-terminated C string).
    pub ir_format: *const c_char,
    /// Pointer to IR data.
    pub ir_data_ptr: *const c_void,
    /// Length of IR data in bytes.
    pub ir_data_len: usize,
    /// Reserved padding for ABI alignment.
    pub padding: [u8; 8],
}

/// Response from a capability query.
#[repr(C)]
pub struct SokrCapabilityResponse {
    /// Result of the capability query.
    pub result: SokrResult,
    /// Reserved padding for ABI alignment.
    pub padding: u32,
    /// Substrate that can fulfill this computation (if capable).
    pub substrate_id: u64,
    /// Estimated latency in nanoseconds (0 if unknown).
    pub estimated_latency_ns: u64,
}

/// Dispatch payload struct.
#[repr(C)]
pub struct SokrDispatchRequest {
    /// Computation to dispatch.
    pub computation_id: SokrComputationId,
    /// Substrate to dispatch to.
    pub substrate_id: u64,
    /// Pointer to IR data.
    pub ir_data_ptr: *const c_void,
    /// Length of IR data in bytes.
    pub ir_data_len: usize,
    /// Pointer to dispatch parameters.
    pub params_ptr: *const c_void,
    /// Length of parameters in bytes.
    pub params_len: usize,
    /// Reserved padding for ABI alignment and future extension.
    pub padding: [u8; 16],
}

/// Response from a dispatch request.
#[repr(C)]
pub struct SokrDispatchResponse {
    /// Result of the dispatch request.
    pub result: SokrResult,
    /// Reserved padding for ABI alignment.
    pub padding: u32,
    /// Token to query completion status.
    pub completion_token: SokrCompletionToken,
}

/// Opaque 64-bit completion handle.
///
/// ## Valid Token Contract
/// - `handle = 0` is reserved as the "invalid / unset" sentinel
/// - Valid tokens are always non-zero (assigned by substrate on successful dispatch)
/// - Callers receiving `handle = 0` on error should not use it for completion queries
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SokrCompletionToken {
    /// Opaque handle identifying this completion.
    /// Value of 0 indicates an invalid or unset token.
    pub handle: u64,
}

/// Query for completion status.
#[repr(C)]
pub struct SokrCompletionQuery {
    /// Completion token to query.
    pub completion_token: SokrCompletionToken,
    /// Timeout in nanoseconds (0 for no timeout).
    pub timeout_ns: u64,
    /// Reserved padding for ABI alignment.
    pub padding: [u8; 8],
}

/// Completion status signal.
#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SokrCompletionSignal {
    /// Operation is still pending.
    Pending = 0,
    /// Operation completed successfully.
    Complete = 1,
    /// Operation failed.
    Failed = 2,
    /// Operation timed out.
    TimedOut = 3,
}

/// Capability query function pointer type.
///
/// # Pointer contract
/// All pointers are valid and non-null for the duration of the call.
/// Implementations MUST NOT retain any pointer past return.
/// Return `SokrResult::CapabilityDenied` to disclaim the computation
/// without claiming ownership; any other non-`Ok` result is propagated
/// to the caller as a hard failure.
pub type SokrCapabilityFn = extern "C" fn(
    version: *const SokrVersion,
    query: *const SokrCapabilityQuery,
    response: *mut SokrCapabilityResponse,
) -> SokrResult;

/// Dispatch function pointer type.
///
/// # Pointer contract
/// All pointers are valid and non-null for the duration of the call.
/// Implementations MUST NOT retain any pointer past return.
/// On non-`Ok` return the core zeroes `response`; any error is propagated
/// verbatim to the caller.
pub type SokrDispatchFn = extern "C" fn(
    request: *const SokrDispatchRequest,
    response: *mut SokrDispatchResponse,
) -> SokrResult;

/// Completion query function pointer type.
///
/// # Pointer contract
/// All pointers are valid and non-null for the duration of the call.
/// Implementations MUST NOT retain any pointer past return.
/// Return `SokrResult::NotFound` to disclaim the token without claiming
/// ownership; any other non-`Ok` result is propagated to the caller as
/// a hard failure and `signal` is set to `SokrCompletionSignal::Failed`.
pub type SokrCompletionFn = extern "C" fn(
    query: *const SokrCompletionQuery,
    signal: *mut SokrCompletionSignal,
) -> SokrResult;

/// Cleanup function called when a plugin is deregistered.
pub type SokrDestroyFn = extern "C" fn();

/// `VTable` struct for substrate plugins.
#[repr(C)]
pub struct SokrSubstratePlugin {
    /// Plugin ABI version for compatibility check.
    pub version: SokrVersion,
    /// Capability query function pointer.
    pub capability_fn: SokrCapabilityFn,
    /// Dispatch function pointer.
    pub dispatch_fn: SokrDispatchFn,
    /// Completion query function pointer.
    pub completion_fn: SokrCompletionFn,
    /// Cleanup function called on deregistration.
    pub destroy_fn: SokrDestroyFn,
    /// Unique identifier for this substrate plugin.
    pub substrate_id: u64,
    /// Reserved padding for ABI alignment.
    pub padding: [u8; 8],
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn version_compatible_same() {
        let v = SokrVersion::CURRENT;
        assert!(v.check_compatible(v).is_ok());
    }

    #[test]
    fn test_version_incompatible_major_higher() {
        let core = SokrVersion::CURRENT;
        let plugin = SokrVersion {
            major: core.major + 1,
            minor: 0,
            patch: 0,
        };
        assert!(plugin.check_compatible(core).is_err());
    }

    #[test]
    fn test_version_incompatible_major_lower() {
        let plugin = SokrVersion {
            major: 0,
            minor: 0,
            patch: 0,
        };
        let core = SokrVersion {
            major: 1,
            minor: 0,
            patch: 0,
        };
        // Major version differs (0 vs 1), should be incompatible
        assert!(plugin.check_compatible(core).is_err());
    }

    #[test]
    fn version_incompatible_major_mismatch() {
        let plugin = SokrVersion {
            major: 1,
            minor: 0,
            patch: 0,
        };
        let core = SokrVersion {
            major: 0,
            minor: 1,
            patch: 0,
        };
        assert!(plugin.check_compatible(core).is_err());
    }

    #[test]
    fn test_version_compatible_minor_older_plugin() {
        let core = SokrVersion::CURRENT;
        let plugin = SokrVersion {
            major: core.major,
            minor: if core.minor > 0 { core.minor - 1 } else { 0 },
            patch: 0,
        };
        assert!(plugin.check_compatible(core).is_ok());
    }

    #[test]
    fn version_incompatible_plugin_too_new() {
        let plugin = SokrVersion {
            major: 0,
            minor: 5,
            patch: 0,
        };
        let core = SokrVersion {
            major: 0,
            minor: 1,
            patch: 0,
        };
        assert!(plugin.check_compatible(core).is_err());
    }

    #[test]
    fn version_compatible_older_plugin() {
        let plugin = SokrVersion {
            major: 0,
            minor: 0,
            patch: 5,
        };
        let core = SokrVersion {
            major: 0,
            minor: 1,
            patch: 0,
        };
        assert!(plugin.check_compatible(core).is_ok());
    }

    #[test]
    fn version_compatible_patch_ignored() {
        let plugin = SokrVersion {
            major: 0,
            minor: 1,
            patch: 99,
        };
        let core = SokrVersion {
            major: 0,
            minor: 1,
            patch: 0,
        };
        assert!(plugin.check_compatible(core).is_ok());
    }

    #[test]
    fn result_is_ok() {
        assert!(SokrResult::Ok.is_ok());
        assert!(!SokrResult::Ok.is_err());
    }

    #[test]
    fn result_is_err() {
        assert!(SokrResult::VersionMismatch.is_err());
        assert!(!SokrResult::VersionMismatch.is_ok());
    }

    #[test]
    fn computation_id_equality() {
        let id1 = SokrComputationId { high: 1, low: 2 };
        let id2 = SokrComputationId { high: 1, low: 2 };
        let id3 = SokrComputationId { high: 2, low: 1 };
        assert_eq!(id1, id2);
        assert_ne!(id1, id3);
    }

    #[test]
    fn current_version_matches_cargo() {
        // Prevent drift between SokrVersion::CURRENT and Cargo.toml version.
        let current = SokrVersion::CURRENT;
        let cargo = env!("CARGO_PKG_VERSION");
        let expected = format!("{}.{}.{}", current.major, current.minor, current.patch);
        assert_eq!(
            expected, cargo,
            "SokrVersion::CURRENT ({expected}) must match CARGO_PKG_VERSION ({cargo}). \
             Bump both together in Cargo.toml and types.rs."
        );
    }
}