inferlab-protocol 0.1.0

Wire types for the Inferlab framework-integration protocol: strict, versioned one-shot JSON adapter operations.
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
//! The versioned wire types of the framework integration protocol
//! ([[RFC-0006:C-INTEGRATIONS]]): the one-shot stdin/stdout JSON contract for
//! the plan/render serve operations, plus the client request/result surfaces
//! the release-owned Eval and Bench measurement runtimes exchange with their
//! clients. [`AdapterProtocol`] is the schema root from which the committed
//! JSON schema and the Python SDK models are generated.

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::PathBuf;

/// The adapter protocol version an integration speaks. The only accepted value
/// is `3` (serialized as the string `"3"`); a mismatch is rejected before
/// lowering.
#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
pub enum ProtocolVersion {
    /// Protocol version 3.
    #[serde(rename = "3")]
    V3,
}

/// The one JSON request an integration reads from stdin, tagged by the
/// requested operation.
#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
#[serde(tag = "operation", rename_all = "snake_case", deny_unknown_fields)]
pub enum AdapterRequest {
    /// Plan a serve topology: declare roles, per-replica requirements, links,
    /// and endpoint requirements from the requested shape.
    PlanServe {
        protocol_version: ProtocolVersion,
        input: PlanServeInput,
    },
    /// Render final process invocations for a planned topology, given the
    /// control plane's concrete process allocations.
    RenderServe {
        protocol_version: ProtocolVersion,
        input: RenderServeInput,
    },
}

impl AdapterRequest {
    /// The protocol version carried by this request, regardless of operation.
    #[must_use]
    pub const fn protocol_version(&self) -> ProtocolVersion {
        match self {
            Self::PlanServe {
                protocol_version, ..
            }
            | Self::RenderServe {
                protocol_version, ..
            } => *protocol_version,
        }
    }
}

/// The requested serve shape a `PlanServe` operation lowers into a topology.
#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlanServeInput {
    pub model: ServeModelInput,
    pub topology: ServeTopology,
    pub routing_backend: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kv_transfer: Option<KvTransferMechanism>,
    pub parallelism: Parallelism,
    pub settings: BTreeMap<String, SettingValue>,
    pub roles: Vec<ServeRoleInput>,
    #[serde(default)]
    pub profiling: bool,
}

/// The planned topology plus the control plane's concrete allocations that a
/// `RenderServe` operation turns into final process invocations.
#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RenderServeInput {
    pub model: ServeModelInput,
    pub topology: ServeTopology,
    pub routing_backend: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kv_transfer: Option<KvTransferMechanism>,
    pub parallelism: Parallelism,
    pub settings: BTreeMap<String, SettingValue>,
    pub roles: Vec<ServeRoleResult>,
    pub links: Vec<ServeRoleLink>,
    pub allocations: Vec<ServeProcessAllocation>,
    #[serde(default)]
    pub profiling: bool,
}

/// The serving deployment topology.
#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ServeTopology {
    /// One aggregated serving role.
    Single,
    /// Disaggregated prefill and decode roles.
    PrefillDecode,
}

/// The logical role a replica plays in a serve topology.
#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ServeRoleKind {
    /// Aggregated serving role of a single topology.
    Serve,
    /// Prefill role of a disaggregated topology.
    Prefill,
    /// Decode role of a disaggregated topology.
    Decode,
    /// Request-routing role that does not execute model inference.
    Router,
}

/// The KV-transfer mechanism connecting prefill and decode.
#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum KvTransferMechanism {
    /// Mooncake KV-cache transfer.
    Mooncake,
    /// NIXL KV-cache transfer.
    Nixl,
}

/// A requested serving role: its identity, kind, replica cardinality, and
/// declared (not-yet-completed) parallelism and settings.
#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ServeRoleInput {
    pub id: String,
    pub kind: ServeRoleKind,
    pub replica_count: u32,
    pub parallelism: Parallelism,
    pub settings: BTreeMap<String, SettingValue>,
}

/// A role as the integration resolved it: preserved identity and cardinality
/// with the complete effective settings and parallelism.
#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ServeRoleResult {
    pub id: String,
    pub kind: ServeRoleKind,
    pub replica_count: u32,
    pub effective_settings: BTreeMap<String, SettingValue>,
    pub effective_parallelism: Parallelism,
}

/// Framework-neutral component-aware parallelism ([[RFC-0003:C-SERVE-PARALLELISM]]).
/// Every component is optional so an operator can override one without
/// repeating the rest; omitted components are filled by the integration into a
/// complete effective shape.
#[derive(Clone, Debug, Default, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct Parallelism {
    /// Outer deployment parallelism shared by attention and experts.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub outer: Option<ParallelismOuter>,
    /// Attention-block parallelism.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attention: Option<ParallelismAttention>,
    /// MoE expert parallelism.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub experts: Option<ParallelismExperts>,
}

impl Parallelism {
    /// Overlay the components present in `other` onto `self`, leaving
    /// components `other` omits untouched (the per-component precedence merge).
    pub fn merge_from(&mut self, other: &Self) {
        if let Some(other) = &other.outer {
            self.outer.get_or_insert_default().merge_from(other);
        }
        if let Some(other) = &other.attention {
            self.attention.get_or_insert_default().merge_from(other);
        }
        if let Some(other) = &other.experts {
            self.experts.get_or_insert_default().merge_from(other);
        }
    }
}

/// Outer deployment parallelism: tensor and pipeline degrees.
#[derive(Clone, Debug, Default, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct ParallelismOuter {
    #[schemars(range(min = 1))]
    pub tensor_parallel_size: Option<u32>,
    #[schemars(range(min = 1))]
    pub pipeline_parallel_size: Option<u32>,
}

impl ParallelismOuter {
    fn merge_from(&mut self, other: &Self) {
        if other.tensor_parallel_size.is_some() {
            self.tensor_parallel_size = other.tensor_parallel_size;
        }
        if other.pipeline_parallel_size.is_some() {
            self.pipeline_parallel_size = other.pipeline_parallel_size;
        }
    }
}

/// Attention-block parallelism: tensor, data, and context degrees.
#[derive(Clone, Debug, Default, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct ParallelismAttention {
    #[schemars(range(min = 1))]
    pub tensor_parallel_size: Option<u32>,
    #[schemars(range(min = 1))]
    pub data_parallel_size: Option<u32>,
    #[schemars(range(min = 1))]
    pub context_parallel_size: Option<u32>,
}

impl ParallelismAttention {
    fn merge_from(&mut self, other: &Self) {
        if other.tensor_parallel_size.is_some() {
            self.tensor_parallel_size = other.tensor_parallel_size;
        }
        if other.data_parallel_size.is_some() {
            self.data_parallel_size = other.data_parallel_size;
        }
        if other.context_parallel_size.is_some() {
            self.context_parallel_size = other.context_parallel_size;
        }
    }
}

/// MoE expert parallelism: tensor, data, expert, and dense-tensor degrees.
#[derive(Clone, Debug, Default, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct ParallelismExperts {
    #[schemars(range(min = 1))]
    pub tensor_parallel_size: Option<u32>,
    #[schemars(range(min = 1))]
    pub data_parallel_size: Option<u32>,
    #[schemars(range(min = 1))]
    pub expert_parallel_size: Option<u32>,
    #[schemars(range(min = 1))]
    pub dense_tensor_parallel_size: Option<u32>,
}

impl ParallelismExperts {
    fn merge_from(&mut self, other: &Self) {
        if other.tensor_parallel_size.is_some() {
            self.tensor_parallel_size = other.tensor_parallel_size;
        }
        if other.data_parallel_size.is_some() {
            self.data_parallel_size = other.data_parallel_size;
        }
        if other.expert_parallel_size.is_some() {
            self.expert_parallel_size = other.expert_parallel_size;
        }
        if other.dense_tensor_parallel_size.is_some() {
            self.dense_tensor_parallel_size = other.dense_tensor_parallel_size;
        }
    }
}

/// The model to serve: its resolved locator and the name it is served under.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ServeModelInput {
    pub locator: String,
    pub served_name: String,
}

/// A concrete host/port endpoint the control plane allocated for a process.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct EndpointAssignment {
    pub host: String,
    pub port: u16,
}

/// The public workload endpoint an Eval or Bench client connects to.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ClientEndpointInput {
    pub protocol: EndpointProtocol,
    pub host: String,
    pub port: u16,
    pub api_path: String,
}

/// The measurement an Eval client runs against the workload endpoint.
#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum EvalDefinitionInput {
    /// A single-prompt liveness check.
    #[serde(rename = "openai_smoke")]
    OpenAiSmoke {
        prompt: String,
        max_tokens: u32,
        timeout_seconds: u64,
    },
    /// An lm-eval task run with a pass threshold on the chosen metric.
    LmEval {
        task: String,
        dataset: Option<String>,
        split: Option<String>,
        limit: Option<u32>,
        few_shot: Option<u32>,
        seed: Option<u64>,
        max_tokens: Option<u32>,
        concurrency: Option<u32>,
        metric: String,
        threshold: f64,
        timeout_seconds: u64,
    },
}

/// The workload shape a Bench client drives, shared across its load cases.
#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct BenchDefinitionInput {
    pub input_tokens: u32,
    pub output_tokens: u32,
    pub seed: u64,
    pub temperature: f64,
    pub timeout_seconds: u64,
    #[serde(default)]
    pub reset_prefix_cache: bool,
}

/// A framework-specific server setting value carried as structured JSON data
/// (never a pre-rendered shell fragment) across the integration boundary.
#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
#[serde(untagged)]
pub enum SettingValue {
    /// A JSON boolean.
    Bool(bool),
    /// A JSON integer.
    Integer(i64),
    /// A JSON floating-point number.
    Float(f64),
    /// A JSON string.
    String(String),
    /// A JSON array of setting values.
    Array(Vec<SettingValue>),
    /// A JSON object of named setting values.
    Object(BTreeMap<String, SettingValue>),
}

/// The one JSON response an integration writes to stdout, tagged by outcome.
#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
#[serde(tag = "status", rename_all = "snake_case", deny_unknown_fields)]
pub enum AdapterResponse {
    /// The operation succeeded and carries its result.
    Ok {
        protocol_version: ProtocolVersion,
        result: Box<AdapterResult>,
    },
    /// The operation was rejected with a structured error.
    Error {
        protocol_version: ProtocolVersion,
        error: AdapterError,
    },
}

impl AdapterResponse {
    /// The protocol version carried by this response, regardless of outcome.
    #[must_use]
    pub const fn protocol_version(&self) -> ProtocolVersion {
        match self {
            Self::Ok {
                protocol_version, ..
            }
            | Self::Error {
                protocol_version, ..
            } => *protocol_version,
        }
    }
}

/// The successful result of an [`AdapterRequest`], tagged by the operation it
/// answers.
#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
#[serde(tag = "operation", rename_all = "snake_case", deny_unknown_fields)]
pub enum AdapterResult {
    /// The planned topology from a `PlanServe` request.
    PlanServe { output: Box<PlanServeResult> },
    /// The rendered process invocations from a `RenderServe` request.
    RenderServe { output: Box<RenderServeResult> },
}

/// The lowered topology returned by a `PlanServe`: the effective server-level
/// shape, per-role resolution, whole-replica requirements, role links, and the
/// public and per-role endpoint requirements the control plane then allocates.
#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PlanServeResult {
    pub integration: IntegrationIdentity,
    pub effective_settings: BTreeMap<String, SettingValue>,
    pub effective_parallelism: Parallelism,
    pub roles: Vec<ServeRoleResult>,
    pub replicas: Vec<ServeReplicaRequirement>,
    pub links: Vec<ServeRoleLink>,
    pub public_endpoint: PublicEndpointRequirement,
    pub endpoint: EndpointRequirement,
}

/// A whole-replica resource and readiness requirement the integration declares
/// without choosing placement, ranks, or concrete endpoints.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ServeReplicaRequirement {
    pub id: String,
    pub role_id: String,
    pub replica_index: u32,
    pub accelerator_count: u32,
    pub ports: Vec<String>,
    pub primary_ports: Vec<String>,
    pub primary_readiness: ReadinessProbe,
    pub worker_readiness: ReadinessProbe,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capture_target: Option<CaptureTargetRequirement>,
}

/// One concrete process the control plane placed, supplied to `RenderServe`:
/// its identity, rank, machine, devices, model locator, and allocated
/// endpoints and named ports.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ServeProcessAllocation {
    pub process_id: String,
    pub role_id: String,
    pub replica_id: String,
    pub replica_index: u32,
    pub rank: u32,
    pub machine_id: String,
    pub model_locator: String,
    pub runtime_cache_root: String,
    pub devices: Vec<u32>,
    pub endpoint: EndpointAssignment,
    pub ports: BTreeMap<String, EndpointAssignment>,
}

/// A directed link between serve roles the integration declares as part of the
/// topology.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum ServeRoleLink {
    /// The source role routes requests to the target roles.
    RequestRouting {
        source: String,
        targets: Vec<String>,
    },
    /// KV cache is transferred from source to target over `mechanism`.
    KvTransfer {
        source: String,
        target: String,
        mechanism: KvTransferMechanism,
    },
    /// The source discovers the target through a bootstrap port.
    Bootstrap {
        source: String,
        target: String,
        port: String,
    },
    /// The source and target exchange out-of-band data over a side-channel port.
    SideChannel {
        source: String,
        target: String,
        port: String,
    },
}

/// How the topology's public workload endpoint is exposed.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum PublicEndpointRequirement {
    /// The endpoint is served directly by a single replica.
    Replica { replica_id: String },
    /// The endpoint is fronted by an Inferlab-owned built-in proxy routing
    /// across the named prefill and decode roles.
    BuiltinProxy {
        process_id: String,
        role_id: String,
        prefill_role: String,
        decode_role: String,
        readiness: ReadinessProbe,
    },
}

/// Marks a replica as a profiling capture target and carries its window
/// control ([[RFC-0004:C-WORKLOAD-PROFILING]]).
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct CaptureTargetRequirement {
    pub control: CaptureControlRequirement,
}

/// The HTTP paths a capture target exposes to open and close a capture window.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct CaptureControlRequirement {
    pub start_path: String,
    pub stop_path: String,
}

/// The final process invocations returned by a `RenderServe`, one per supplied
/// allocation.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RenderServeResult {
    pub integration: IntegrationIdentity,
    pub processes: Vec<RenderedServeProcess>,
}

/// A rendered process bound to the allocation `id` it was produced for.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RenderedServeProcess {
    pub id: String,
    pub process: ProcessSpec,
}

/// An HTTP action (method and path) invoked against the workload endpoint.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct HttpActionSpec {
    pub method: HttpMethod,
    pub path: String,
}

/// The HTTP method of an [`HttpActionSpec`].
#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum HttpMethod {
    /// HTTP POST.
    Post,
}

/// The integration's identity recorded on its results: adapter id, adapter
/// version, and the framework it lowers to.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct IntegrationIdentity {
    pub adapter_id: String,
    pub adapter_version: String,
    pub framework: String,
}

/// A launchable process: its argument vector and environment.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ProcessSpec {
    pub argv: Vec<String>,
    pub env: BTreeMap<String, String>,
}

/// How the control plane decides a process is ready.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum ReadinessProbe {
    /// Ready when an HTTP GET of `path` succeeds.
    Http { path: String },
    /// Ready as soon as the process is alive.
    ProcessAlive,
}

/// The workload endpoint's protocol and API path, plus an optional
/// prefix-cache-reset action a Bench case can invoke between runs.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct EndpointRequirement {
    pub protocol: EndpointProtocol,
    pub api_path: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prefix_cache_reset: Option<HttpActionSpec>,
}

/// The application protocol a workload endpoint speaks.
#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum EndpointProtocol {
    /// HTTP.
    Http,
}

/// A structured rejection an integration returns in an [`AdapterResponse::Error`].
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct AdapterError {
    pub code: AdapterErrorCode,
    pub message: String,
}

/// Machine-readable failure category an adapter reports in an [`AdapterError`].
#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum AdapterErrorCode {
    /// The request was malformed or missing required fields.
    InvalidRequest,
    /// The request's protocol version is not accepted.
    UnsupportedProtocolVersion,
    /// A framework setting was unknown or invalid.
    InvalidSettings,
    /// An unexpected internal failure occurred in the integration.
    Internal,
    /// The requested operation is not supported by this integration.
    UnsupportedOperation,
}

/// The request the Eval measurement runtime passes to its client: the endpoint
/// to hit, the model, the eval definition, and where to write artifacts.
#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct EvalClientRequest {
    pub protocol_version: ProtocolVersion,
    pub endpoint: ClientEndpointInput,
    pub model: ServeModelInput,
    pub definition: EvalDefinitionInput,
    pub artifact_dir: PathBuf,
}

/// The request the Bench measurement runtime passes to its client: the
/// endpoint, model, bench definition, the load case to run, and the artifact
/// directory.
#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct BenchClientRequest {
    pub protocol_version: ProtocolVersion,
    pub endpoint: ClientEndpointInput,
    pub model: ServeModelInput,
    pub definition: BenchDefinitionInput,
    pub case: BenchCaseInput,
    pub artifact_dir: PathBuf,
}

/// A single Bench case: its load shape and the number of requests to send.
#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct BenchCaseInput {
    pub load_shape: BenchLoadInput,
    pub request_count: u32,
}

/// How a Bench case paces its requests.
#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum BenchLoadInput {
    /// A fixed number of in-flight requests.
    ConcurrencyLimited { concurrency: u32 },
    /// A target arrival rate, optionally shaped by a burstiness factor.
    RequestRateLimited {
        request_rate: f64,
        burstiness: Option<f64>,
    },
    /// All requests issued as fast as possible.
    UnboundedRequestRate,
}

/// The terminal outcome a measurement client reports.
#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ClientStatus {
    /// The client completed its measurement successfully.
    Succeeded,
    /// The client did not complete successfully.
    Failed,
}

/// The result an Eval client writes for the measurement runtime to consume.
#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct EvalClientResult {
    /// Result envelope version; clients write `1`. The measurement runtime
    /// rejects an eval result whose version is not `1`.
    pub schema_version: u32,
    pub status: ClientStatus,
    pub metrics: BTreeMap<String, f64>,
    pub native_command: Vec<String>,
    pub raw_artifacts: Vec<RawArtifact>,
    pub error: Option<String>,
}

/// The result a Bench client writes for the measurement runtime to consume.
#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct BenchClientResult {
    /// Result envelope version; clients write `1`. The measurement runtime
    /// rejects a bench result whose version is not `1`.
    pub schema_version: u32,
    pub status: ClientStatus,
    pub completed_requests: u64,
    pub failed_requests: u64,
    pub normalization_schema: String,
    pub metrics: BTreeMap<String, f64>,
    pub native_command: Vec<String>,
    pub native_exit_code: Option<i32>,
    pub raw_artifacts: Vec<RawArtifact>,
    pub error: Option<String>,
}

/// A raw output file a client produced, retained as workload evidence.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RawArtifact {
    pub name: String,
    pub kind: String,
    pub path: PathBuf,
}

/// The schema root aggregating every wire type. It exists to generate one
/// committed JSON schema (and the Python SDK models); its optional client
/// fields are never all populated in a single message.
#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct AdapterProtocol {
    pub request: AdapterRequest,
    pub response: AdapterResponse,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub eval_client_request: Option<EvalClientRequest>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub eval_client_result: Option<EvalClientResult>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bench_client_request: Option<BenchClientRequest>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bench_client_result: Option<BenchClientResult>,
}