dynamo-llm 1.7.0

Dynamo LLM Library
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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

use std::sync::Arc;
use std::time::Instant;

use axum::{
    Json,
    http::{HeaderValue, StatusCode, header::HeaderName},
    response::{IntoResponse, Response},
};
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use dynamo_decisions::{
    CanonicalRequest, DecisionError, Dialect, QuestionOutcome, Usage, project_response,
    reduce_vocab_logprobs, render_question_prompt,
};
use dynamo_runtime::{
    engine::{AsyncEngineContext, AsyncEngineContextProvider},
    pipeline::{Context, ManyOut},
};
use futures::{StreamExt, stream};
use rand::Rng;
use tokio::sync::{OwnedSemaphorePermit, Semaphore};

use super::{
    decision_lifecycle::{self, run_until_killed, spawn_blocking_with_permit},
    disconnect::create_connection_monitor,
    metrics::{CancellationLabels, Endpoint, Metrics, SystemOnePhase},
    service_v2,
};
use crate::{
    discovery::{SystemOneExecutionSelection, SystemOneSelectionError},
    generate_format::{Bound, ClientRequest, GenerateExchange, Worker},
    protocols::{
        Annotated,
        common::{
            llm_backend::LLMEngineOutput, preprocessor::PreprocessedRequest, timing::RequestTracker,
        },
        response_merge::PREFILL_OUTPUT_ANNOTATION,
        systemone::{build_native_score_request, parse_candidate_scores},
    },
};

#[path = "systemone/abort.rs"]
mod abort;
#[path = "systemone/backend_error.rs"]
mod backend_error;
#[path = "systemone/response.rs"]
mod response;
pub(super) use response::attach_request_ids;
use response::{decision_error, error};

#[path = "systemone/http.rs"]
mod http;
pub use http::router;

pub(super) const DEFAULT_PATH: &str = "/v1/systemone";
pub(super) const DECISIONS_PATH: &str = "/v1/decisions";

// The configured input ceiling and deployment candidate ceiling bound amplification.
const MAX_TOKENIZATION_WORK: usize = 1_048_576 * (255 + 2);
const MAX_TOKENIZATION_TEXT_BYTES: usize = 16 * 1024 * 1024;
const MAX_CONCURRENT_SIBLINGS: usize = 4;

#[derive(Clone, Copy)]
pub(super) struct DecisionCapacityRejection;

fn metric_endpoint(dialect: Dialect) -> Endpoint {
    match dialect {
        Dialect::Jev => Endpoint::SystemOne,
        Dialect::OpenAi => Endpoint::Decisions,
    }
}

struct PreparedBranch {
    index: usize,
    temperature: f64,
    prompt_ids: Vec<u32>,
    label_ids: Vec<u32>,
    native: Option<serde_json::Value>,
}

struct StartedBranch {
    prepared: PreparedBranch,
    tracker: Arc<RequestTracker>,
    stream: ManyOut<Annotated<LLMEngineOutput>>,
    exchange: Box<dyn GenerateExchange>,
}

struct BranchResult {
    index: usize,
    answer: QuestionOutcome,
    input_tokens: usize,
    cached_tokens: Option<usize>,
    placement: Placement,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Placement {
    worker_id: u64,
    dp_rank: u32,
}

#[derive(Debug)]
struct DispatchError {
    status: StatusCode,
    public_message: &'static str,
    detail: String,
    retry_after: bool,
    is_capacity_exhausted: bool,
}

impl DispatchError {
    fn cancelled() -> Self {
        Self {
            status: StatusCode::from_u16(499).unwrap_or(StatusCode::BAD_REQUEST),
            public_message: "request was cancelled",
            detail: "parent request context was cancelled".to_string(),
            retry_after: false,
            is_capacity_exhausted: false,
        }
    }

    fn unavailable(detail: impl Into<String>) -> Self {
        Self {
            status: StatusCode::SERVICE_UNAVAILABLE,
            public_message: "SGLang scoring worker is unavailable",
            detail: detail.into(),
            retry_after: false,
            is_capacity_exhausted: false,
        }
    }

    fn malformed(detail: impl Into<String>) -> Self {
        Self {
            status: StatusCode::INTERNAL_SERVER_ERROR,
            public_message: "malformed SGLang scoring response",
            detail: detail.into(),
            retry_after: false,
            is_capacity_exhausted: false,
        }
    }
}

fn acquire_admission(
    admission: Arc<Semaphore>,
    branches: u32,
    limit: usize,
    dialect: Dialect,
) -> Result<OwnedSemaphorePermit, Box<Response>> {
    decision_lifecycle::acquire_admission(admission, branches, limit).map_err(|cause| {
        let response = match cause {
            decision_lifecycle::AdmissionError::InvalidBranchCount => error(
                dialect,
                StatusCode::UNPROCESSABLE_ENTITY,
                "decision requests require at least one question",
            ),
            decision_lifecycle::AdmissionError::AdmissionClosed => error(
                dialect,
                StatusCode::SERVICE_UNAVAILABLE,
                "decision admission is closed",
            ),
            decision_lifecycle::AdmissionError::RequestTooLarge => error(
                dialect,
                StatusCode::UNPROCESSABLE_ENTITY,
                format!(
                    "request needs {branches} branches; the System One branch limit is {limit}"
                ),
            ),
            decision_lifecycle::AdmissionError::CapacityExhausted => response::capacity_error(
                dialect,
                super::error::overload_status_code(),
                "System One request capacity is exhausted",
            ),
        };
        Box::new(response)
    })
}

fn resolve_dp_rank(reported: Option<u32>, start_rank: u32, size: u32) -> Option<u32> {
    reported.or_else(|| (size == 1).then_some(start_rank))
}

fn add_input_tokens(total: usize, next: usize, limit: usize) -> Result<usize, String> {
    let expanded = total
        .checked_add(next)
        .ok_or_else(|| "request expands beyond the System One input-token limit".to_string())?;
    if expanded > limit {
        return Err(format!(
            "request expands to {expanded} prompt tokens; the System One limit is {limit}"
        ));
    }
    Ok(expanded)
}

fn encoding_prompt_limit(remaining_work: usize, candidates: usize) -> usize {
    remaining_work / (candidates + 2)
}

fn tokenization_work_limit(input_tokens: usize, candidates: usize) -> Option<usize> {
    input_tokens
        .checked_mul(candidates.checked_add(2)?)
        .filter(|work| *work <= MAX_TOKENIZATION_WORK)
}

fn pin_to_placement(preprocessed: &mut PreprocessedRequest, placement: Placement) {
    let routing = preprocessed.routing.get_or_insert_default();
    routing.backend_instance_id = Some(placement.worker_id);
    routing.dp_rank = Some(placement.dp_rank);
}

async fn handle_request(
    state: Arc<service_v2::State>,
    request_id: String,
    request: CanonicalRequest,
) -> Response {
    let dialect = request.dialect;
    if request.questions.is_empty() {
        return decision_error(DecisionError::validation(
            dialect,
            "request must contain at least one question",
        ));
    }
    let deadline = tokio::time::Instant::now() + state.systemone_request_timeout();
    if super::openai::check_ready(&state).is_err() {
        return error(
            dialect,
            StatusCode::SERVICE_UNAVAILABLE,
            "service is not ready",
        );
    }

    let selection = match state
        .manager()
        .get_systemone_execution_selection(&request.model)
    {
        Ok(selection) => selection,
        Err(SystemOneSelectionError::NotFound) => {
            return error(dialect, StatusCode::NOT_FOUND, "model is not registered");
        }
        Err(SystemOneSelectionError::Unavailable) => {
            return error(
                dialect,
                StatusCode::SERVICE_UNAVAILABLE,
                "model has no eligible aggregate SGLang worker",
            );
        }
        Err(SystemOneSelectionError::Unsupported) => {
            return error(
                dialect,
                StatusCode::BAD_REQUEST,
                "model does not support aggregate SGLang scoring",
            );
        }
    };
    if let Err(cause) = request.validate_capabilities(&selection.decision_capabilities()) {
        return decision_error(cause);
    }

    let branch_count = u32::try_from(request.questions.len()).unwrap_or(u32::MAX);
    let admission_permit = match acquire_admission(
        state.systemone_admission(),
        branch_count,
        state.systemone_max_inflight_branches(),
        dialect,
    ) {
        Ok(permit) => permit,
        Err(response) => return *response,
    };

    let max_input_tokens = state.systemone_max_input_tokens();
    let preflight_permit = match state.systemone_preflight_admission().try_acquire_owned() {
        Ok(permit) => permit,
        Err(_) => {
            return response::capacity_error(
                dialect,
                super::error::overload_status_code(),
                "System One preprocessing capacity is exhausted",
            );
        }
    };
    let preflight_started = Instant::now();
    let selection_for_preflight = selection.clone();
    let request = Arc::new(request);
    let preflight_request = request.clone();
    let (branches, admission_permit) = match tokio::time::timeout_at(
        deadline,
        spawn_blocking_with_permit(admission_permit, move || {
            let _preflight_permit = preflight_permit;
            prepare_branches(
                &preflight_request,
                &selection_for_preflight,
                max_input_tokens,
            )
        }),
    )
    .await
    {
        Ok(Ok(Ok(prepared))) => prepared,
        Ok(Ok(Err((status, message)))) => return error(dialect, status, message),
        Err(_) => {
            return error(
                dialect,
                StatusCode::GATEWAY_TIMEOUT,
                "decision request deadline exceeded",
            );
        }
        Ok(Err(cause)) => {
            tracing::error!(error = %cause, "System One preflight task failed");
            return error(
                dialect,
                StatusCode::INTERNAL_SERVER_ERROR,
                "internal server error",
            );
        }
    };

    let metrics = state.metrics_clone();
    let metric_model = state.manager().metric_model_for(&selection.canonical_model);
    metrics.observe_systemone_phase(
        metric_model,
        SystemOnePhase::Preflight,
        preflight_started.elapsed().as_secs_f64(),
    );
    metrics.observe_systemone_work(
        metric_model,
        branches.len(),
        branches.iter().map(|branch| branch.prompt_ids.len()).sum(),
        branches.iter().map(|branch| branch.label_ids.len()).sum(),
    );

    let parent = Context::with_id_and_metadata((), request_id.clone(), Default::default());
    let parent_context = parent.context();
    let cancellation_labels = CancellationLabels {
        model: state
            .manager()
            .metric_model_for(&selection.canonical_model)
            .to_string(),
        endpoint: metric_endpoint(dialect).to_string(),
        request_type: "unary".to_string(),
    };
    let (mut connection_handle, _stream_handle) = create_connection_monitor(
        parent_context.clone(),
        Some(state.metrics_clone()),
        cancellation_labels,
    )
    .await;
    let task = tokio::spawn(dispatch(
        selection,
        branches,
        request_id.clone(),
        parent_context.clone(),
        admission_permit,
        metrics,
        request,
    ));
    let response = response::dispatch_with_deadline(task, deadline, parent_context, dialect).await;
    connection_handle.disarm();
    response
}

fn prepare_branches(
    request: &CanonicalRequest,
    selection: &SystemOneExecutionSelection,
    max_input_tokens: usize,
) -> Result<Vec<PreparedBranch>, (StatusCode, String)> {
    let context_length = selection.card.effective_context_length() as usize;
    let mut total_input_tokens = 0_usize;
    let mut remaining_tokenization_work = tokenization_work_limit(
        max_input_tokens,
        selection.decision_capabilities().max_candidates,
    )
    .ok_or_else(|| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            "System One tokenization work configuration exceeds its supported limit".to_string(),
        )
    })?;
    let mut remaining_encoding_bytes = MAX_TOKENIZATION_TEXT_BYTES;
    let mut branches = Vec::with_capacity(request.questions.len());
    for question in &request.questions {
        let index = question.ordinal;
        let question_id = question.id.as_deref().unwrap_or("unnamed");
        let rendered = render_question_prompt(&request.input, question)
            .map_err(|cause| (StatusCode::UNPROCESSABLE_ENTITY, cause.to_string()))?;
        let remaining_tokens = max_input_tokens.saturating_sub(total_input_tokens);
        let max_prompt_tokens = if context_length == 0 {
            remaining_tokens
        } else {
            remaining_tokens.min(context_length.saturating_sub(1))
        }
        .min(encoding_prompt_limit(
            remaining_tokenization_work,
            rendered.labels.len(),
        ));
        let (prompt_ids, label_ids, encoding_bytes) = selection
            .preprocessor
            .render_systemone_question(
                &selection.canonical_model,
                &rendered.content,
                Some(&request.chat_template_kwargs),
                &rendered.labels,
                (max_prompt_tokens, remaining_encoding_bytes),
            )
            .map_err(|cause| {
                if let Some(oversized) =
                    cause.downcast_ref::<crate::preprocessor::SystemOnePromptTooLong>()
                {
                    return (
                        StatusCode::UNPROCESSABLE_ENTITY,
                        format!("question {question_id:?}: {oversized}"),
                    );
                }
                if let Some(oversized) =
                    cause.downcast_ref::<crate::preprocessor::SystemOneEncodingTooLarge>()
                {
                    return (
                        StatusCode::UNPROCESSABLE_ENTITY,
                        format!("question {question_id:?}: {oversized}"),
                    );
                }
                if let Some(incompatible) = cause
                    .downcast_ref::<crate::preprocessor::SystemOneCandidateLabelsIncompatible>()
                {
                    return (
                        StatusCode::UNPROCESSABLE_ENTITY,
                        format!("question {question_id:?}: {incompatible}"),
                    );
                }
                let reason = if let Some(incompatible) =
                    cause.downcast_ref::<crate::preprocessor::SystemOneModelIncompatible>()
                {
                    incompatible.0
                } else if super::error::find_canonical_error_in_chain(cause.as_ref())
                    .is_some_and(|error| {
                        error.class() == dynamo_runtime::error::ErrorClass::InvalidRequest
                    })
                {
                    "chat template or tokenizer failed"
                } else {
                    tracing::error!("System One prompt tokenization failed");
                    return (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        "internal server error".to_string(),
                    );
                };
                tracing::warn!(reason, "System One prompt rendering failed");
                (
                    StatusCode::UNPROCESSABLE_ENTITY,
                    format!(
                        "question {question_id:?}: tokenizer or chat template could not render this request"
                    ),
                )
            })?;
        total_input_tokens =
            add_input_tokens(total_input_tokens, prompt_ids.len(), max_input_tokens)
                .map_err(|message| (StatusCode::UNPROCESSABLE_ENTITY, message))?;
        remaining_tokenization_work -= prompt_ids.len() * (rendered.labels.len() + 2);
        remaining_encoding_bytes -= encoding_bytes;
        let native =
            build_native_score_request(&prompt_ids, &label_ids, "validation").map_err(|cause| {
                tracing::error!(error = %cause, "failed to build System One native request");
                (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    "internal server error".to_string(),
                )
            })?;
        branches.push(PreparedBranch {
            index,
            temperature: request.temperature,
            prompt_ids,
            label_ids,
            native: Some(native),
        });
    }
    Ok(branches)
}

async fn dispatch(
    selection: SystemOneExecutionSelection,
    mut branches: Vec<PreparedBranch>,
    request_id: String,
    parent_context: Arc<dyn AsyncEngineContext>,
    _admission_permit: OwnedSemaphorePermit,
    metrics: Arc<Metrics>,
    request: Arc<CanonicalRequest>,
) -> Response {
    let dialect = request.dialect;
    let mut salt_bytes = [0_u8; 16];
    // Share sibling prefixes, but isolate requests until a trusted tenant scope exists.
    // Client metadata and request IDs are not authenticated cache identities.
    rand::rng().fill(&mut salt_bytes);
    let cache_salt = URL_SAFE_NO_PAD.encode(salt_bytes);
    let first = branches.remove(0);
    let first_started = Instant::now();
    let first_result = match run_branch(
        selection.clone(),
        first,
        request_id.clone(),
        cache_salt.clone(),
        None,
        parent_context.clone(),
        metrics.clone(),
    )
    .await
    {
        Ok(result) => result,
        Err(cause) => return dispatch_error(&request_id, &parent_context, cause, dialect),
    };
    metrics.observe_systemone_phase(
        &selection.canonical_model,
        SystemOnePhase::FirstBranch,
        first_started.elapsed().as_secs_f64(),
    );
    let placement = first_result.placement;
    let mut results = Vec::with_capacity(branches.len() + 1);
    results.push(first_result);

    let fanout_started = Instant::now();
    let mut siblings = stream::iter(branches.into_iter().map(|branch| {
        run_branch(
            selection.clone(),
            branch,
            request_id.clone(),
            cache_salt.clone(),
            Some(placement),
            parent_context.clone(),
            metrics.clone(),
        )
    }))
    .buffer_unordered(MAX_CONCURRENT_SIBLINGS);
    let mut failure = None;
    while let Some(result) = siblings.next().await {
        if failure.is_some() {
            continue;
        }
        match result {
            Ok(result) if result.placement == placement => results.push(result),
            Ok(result) => {
                parent_context.kill();
                failure = Some(DispatchError::unavailable(format!(
                    "branch {} was routed to {:?}, expected {:?}",
                    result.index, result.placement, placement
                )));
            }
            Err(cause) => {
                parent_context.kill();
                failure = Some(cause);
            }
        }
    }
    drop(siblings);
    if let Some(cause) = failure {
        return dispatch_error(&request_id, &parent_context, cause, dialect);
    }

    metrics.observe_systemone_phase(
        &selection.canonical_model,
        SystemOnePhase::Fanout,
        fanout_started.elapsed().as_secs_f64(),
    );

    results.sort_by_key(|result| result.index);
    let mut outcomes = Vec::with_capacity(results.len());
    let mut usage = Usage {
        cached_tokens: Some(0),
        ..Default::default()
    };
    for result in results {
        usage.input_tokens += result.input_tokens as u64;
        usage.cached_tokens = usage
            .cached_tokens
            .zip(result.cached_tokens)
            .map(|(total, next)| total + next as u64);
        outcomes.push(result.answer);
    }
    let mut response =
        match project_response(&request, &selection.canonical_model, &outcomes, &usage) {
            Ok(body) => Json(body).into_response(),
            Err(cause) => decision_error(cause),
        };
    attach_request_ids(&mut response, &request_id);
    response.headers_mut().insert(
        HeaderName::from_static("x-dynamo-systemone-version"),
        HeaderValue::from_static("1"),
    );
    response
}

fn dispatch_error(
    request_id: &str,
    parent_context: &Arc<dyn AsyncEngineContext>,
    cause: DispatchError,
    dialect: Dialect,
) -> Response {
    parent_context.kill();
    if cause.status.as_u16() == 499 {
        tracing::debug!(%request_id, "System One request cancelled");
    } else {
        tracing::error!(%request_id, error = %cause.detail, "System One scoring failed");
    }
    if cause.is_capacity_exhausted {
        return response::capacity_error(dialect, cause.status, cause.public_message);
    }
    let mut response = error(dialect, cause.status, cause.public_message);
    if cause.retry_after {
        response.headers_mut().insert(
            axum::http::header::RETRY_AFTER,
            HeaderValue::from_static("1"),
        );
    }
    response
}

async fn run_branch(
    selection: SystemOneExecutionSelection,
    mut prepared: PreparedBranch,
    request_id: String,
    cache_salt: String,
    pinned: Option<Placement>,
    parent_context: Arc<dyn AsyncEngineContext>,
    metrics: Arc<Metrics>,
) -> Result<BranchResult, DispatchError> {
    selection
        .validate_dispatch(pinned.map(|placement| placement.worker_id))
        .map_err(|_| {
            DispatchError::unavailable("selected worker revision is no longer available")
        })?;
    let mut native = prepared
        .native
        .take()
        .ok_or_else(|| DispatchError::malformed("native request was already consumed"))?;
    native["cache_salt"] = serde_json::Value::String(cache_salt);
    let branch_id = format!("{request_id}-{}", prepared.index);
    let Bound {
        request: mut preprocessed,
        exchange,
    } = bind_native(
        &selection.canonical_model,
        selection.card.kv_cache_block_size,
        &native,
        &branch_id,
    )
    .map_err(|cause| DispatchError::malformed(format!("native request: {cause:#}")))?;
    preprocessed
        .routing
        .get_or_insert_default()
        .expected_output_tokens = Some(0);
    let tracker = Arc::new(RequestTracker::new());
    tracker.record_isl(prepared.prompt_ids.len(), None);
    if let Some(placement) = pinned {
        pin_to_placement(&mut preprocessed, placement);
    }
    preprocessed.tracker = Some(tracker.clone());
    let context: Context<PreprocessedRequest> =
        Context::with_id_and_metadata(preprocessed, branch_id, Default::default());
    let branch_context = context.context();
    parent_context.link_child(branch_context.clone());
    if parent_context.is_killed() {
        branch_context.kill();
        return Err(DispatchError::cancelled());
    }
    let stream = run_until_killed(parent_context.as_ref(), selection.engine.generate(context))
        .await
        .ok_or_else(DispatchError::cancelled)?
        .map_err(|cause| backend_error::classify(cause.as_ref()))?;
    let stream_context = stream.context();
    parent_context.link_child(stream_context.clone());
    if parent_context.is_killed() {
        stream_context.kill();
        return Err(DispatchError::cancelled());
    }
    let result = finish_branch(
        StartedBranch {
            prepared,
            tracker,
            stream,
            exchange,
        },
        selection.card.runtime_config.data_parallel_start_rank,
        selection.card.runtime_config.data_parallel_size,
        parent_context,
    )
    .await?;
    if let Some(cached_tokens) = result.cached_tokens {
        metrics.observe_systemone_branch(&selection.canonical_model, cached_tokens);
    }
    Ok(result)
}

/// Build a scoring branch through SGLang's native `/generate` format.
fn bind_native(
    model: &str,
    kv_cache_block_size: u32,
    native: &serde_json::Value,
    request_id: &str,
) -> anyhow::Result<Bound> {
    let format = crate::generate_format::named("sglang")?;
    let body = serde_json::to_vec(native)?;
    let mut headers = axum::http::HeaderMap::new();
    headers.insert(
        axum::http::header::CONTENT_TYPE,
        HeaderValue::from_static("application/json"),
    );
    let opened = format
        .open(ClientRequest {
            body: &body,
            headers: &headers,
            default_request_id: request_id,
        })
        .map_err(|error| anyhow::anyhow!(error.message))?;
    opened
        .validation
        .map_err(|error| anyhow::anyhow!(error.message))?;
    (opened.bind)(&Worker {
        model,
        kv_cache_block_size,
        lora_name: None,
        tower_connector_lora_enabled: false,
    })
    .map_err(|error| anyhow::anyhow!(error.message))
}

fn stream_error(cause: dynamo_runtime::error::DynamoError) -> DispatchError {
    if cause.class() == dynamo_runtime::error::ErrorClass::BackendProtocol {
        DispatchError::malformed("invalid native scoring stream")
    } else {
        backend_error::classify(&cause)
    }
}

fn accept_frame(
    frame: serde_json::Value,
    terminal: &mut Option<serde_json::Value>,
) -> Result<(), DispatchError> {
    let finish = frame
        .get("meta_info")
        .and_then(|meta| meta.get("finish_reason"));
    if let Some(cause) = finish.and_then(abort::classify) {
        return Err(cause);
    }
    if finish.is_some_and(|finish| !finish.is_null()) && terminal.replace(frame).is_some() {
        return Err(DispatchError::malformed(
            "multiple terminal SGLang scoring frames",
        ));
    }
    Ok(())
}

async fn finish_branch(
    started: StartedBranch,
    data_parallel_start_rank: u32,
    data_parallel_size: u32,
    parent_context: Arc<dyn AsyncEngineContext>,
) -> Result<BranchResult, DispatchError> {
    let result = read_branch(
        started,
        data_parallel_start_rank,
        data_parallel_size,
        parent_context.clone(),
    )
    .await;
    if parent_context.is_killed() {
        return Err(DispatchError::cancelled());
    }
    result
}

async fn read_branch(
    started: StartedBranch,
    data_parallel_start_rank: u32,
    data_parallel_size: u32,
    parent_context: Arc<dyn AsyncEngineContext>,
) -> Result<BranchResult, DispatchError> {
    let StartedBranch {
        prepared,
        tracker,
        mut stream,
        mut exchange,
    } = started;
    let mut terminal = None;
    let mut frames = Vec::new();
    loop {
        let delta = run_until_killed(parent_context.as_ref(), stream.next())
            .await
            .ok_or_else(DispatchError::cancelled)?;
        let Some(delta) = delta else { break };
        let prefill = delta.event.as_deref() == Some(PREFILL_OUTPUT_ANNOTATION);
        if let Some(output) = delta.into_data().map_err(stream_error)? {
            exchange
                .chunk(output, prefill, &mut |frame| frames.push(frame.clone()))
                .map_err(stream_error)?;
        }
        for frame in frames.drain(..) {
            accept_frame(frame, &mut terminal)?;
        }
    }
    if let Some(frame) = exchange.finish().map_err(stream_error)? {
        accept_frame(frame, &mut terminal)?;
    }
    let terminal = terminal
        .ok_or_else(|| DispatchError::malformed("missing terminal SGLang scoring frame"))?;
    let placement = tracker
        .get_worker_info()
        .and_then(|worker| {
            worker
                .decode_worker_id
                .or(worker.prefill_worker_id)
                .map(|worker_id| {
                    resolve_dp_rank(
                        worker.decode_dp_rank.or(worker.prefill_dp_rank),
                        data_parallel_start_rank,
                        data_parallel_size,
                    )
                    .map(|dp_rank| Placement { worker_id, dp_rank })
                })
        })
        .flatten()
        .ok_or_else(|| {
            DispatchError::unavailable("Dynamo did not report an unambiguous scoring worker rank")
        })?;
    let scores = parse_candidate_scores(&terminal, &prepared.label_ids)
        .map_err(|cause| DispatchError::malformed(cause.to_string()))?;
    let answer = QuestionOutcome::Answer(
        reduce_vocab_logprobs(&scores, prepared.temperature)
            .map_err(|cause| DispatchError::malformed(cause.to_string()))?,
    );
    let input_tokens = prepared.prompt_ids.len();
    let cached_tokens = measured_cached_tokens(&terminal, input_tokens)?;
    Ok(BranchResult {
        index: prepared.index,
        answer,
        input_tokens,
        cached_tokens,
        placement,
    })
}

fn measured_cached_tokens(
    response: &serde_json::Value,
    input_tokens: usize,
) -> Result<Option<usize>, DispatchError> {
    let Some(count) = response
        .get("meta_info")
        .and_then(|meta| meta.get("cached_tokens"))
    else {
        return Ok(None);
    };
    let count = count
        .as_u64()
        .and_then(|value| usize::try_from(value).ok())
        .filter(|value| *value <= input_tokens)
        .ok_or_else(|| DispatchError::malformed("invalid cache-read token count"))?;
    Ok(Some(count))
}

#[cfg(test)]
#[path = "systemone/tests.rs"]
mod tests;