orchestrator.cpp

src/inference/orchestrator.cpp

@file orchestrator.cpp @brief ModelOrchestrator implementation.

Owners: @tvanfossen

activate_default_tier

bool entropic::ModelOrchestrator::activate_default_tier(const ParsedConfig &config)

Activate the default tier (and load if not yet loaded).

src/inference/orchestrator.cpp:146

Show on the map →

Called by initialize

Calls get_model

Source · 20 lines
bool ModelOrchestrator::activate_default_tier(const ParsedConfig& config) {
    // gh#157: `models.defer_load` leaves the default tier COLD until the
    // first caller needs it. Two idle hosts previously held two copies of
    // the same 4.8 GB GGUF in VRAM without ever being sent a run.
    const bool skip = config.models.defer_load
        || tiers_.find(default_tier_) == tiers_.end();
    if (skip) {
        if (config.models.defer_load) {
            logger->info("[residency] models.defer_load=true — default tier "
                         "'{}' loads on first use", default_tier_);
        }
        return true;
    }
    if (get_model(default_tier_) == nullptr) {
        logger->error("Failed to activate default tier: {}", default_tier_);
        return false;
    }
    logger->info("Activated default tier: {}", default_tier_);
    return true;
}
Activity · 10 steps
lines 150–151const bool skip = config.models.defer_load || tiers_.find(default_tier_) == tiers_.end();lines 152–152◇ if (skip)lines 153–153◇ if (config.models.defer_load)lines 154–155logger->info("[residency] models.defer_load=true — default tier " "'{}' loads on first use", default_tier_);lines 157–157return true;lines 159–159◇ if (get_model(default_tier_) == nullptr)lines 160–160logger->error("Failed to activate default tier: {}", default_tier_);lines 161–161return false;lines 163–163logger->info("Activated default tier: {}", default_tier_);lines 164–164return true;

Requirements

REQ-INFER-019

activate_draft

void entropic::ModelOrchestrator::activate_draft(const ParsedConfig &config)

Activate the speculative-draft model if configured.

src/inference/orchestrator.cpp:198

Source · 19 lines
void ModelOrchestrator::activate_draft(const ParsedConfig& config) {
    const auto& spec = config.inference.speculative;
    if (!spec.enabled || spec.draft.path.empty()) { return; }
    // gh#106 (v2.9.0): under MTP the target owns the head (lazily, via
    // generate_mtp → setup_mtp_draft). Loading draft.path as a standalone
    // secondary backend here would double-load the head GGUF and never use
    // it — skip the gh#36 separate-draft activation entirely.
    if (spec.mtp) {
        logger->info("Speculative MTP: head '{}' is target-owned; skipping "
                     "separate draft activation", spec.draft.path.string());
        return;
    }
    // Full ModelConfig comes from the YAML's
    // `inference.speculative.draft:` block — every llama.cpp knob is
    // consumer-tunable. Defaults come from
    // `make_default_draft_model_config()` (gpu_layers=0,
    // flash_attn=false, context_length=8192, n_threads=4).
    secondary_loader_.ensure_loaded("draft", spec.draft);
}
Activity · 7 steps
lines 199–199const auto& spec = config.inference.speculative;lines 200–200◇ if (!spec.enabled || spec.draft.path.empty())lines 200–200return;lines 205–205◇ if (spec.mtp)lines 206–207logger->info("Speculative MTP: head '{}' is target-owned; skipping " "separate draft activation", spec.draft.path.string());lines 208–208return;lines 215–215secondary_loader_.ensure_loaded("draft", spec.draft);

Requirements

REQ-INFER-020

activate_router

void entropic::ModelOrchestrator::activate_router(const ParsedConfig &config)

Activate the router model if configured.

src/inference/orchestrator.cpp:178

Source · 6 lines
void ModelOrchestrator::activate_router(const ParsedConfig& config) {
    if (!config.models.router) { return; }
    // Lifecycle now lives on SecondaryModelLoader (gh#27, v2.1.11).
    // Diagnostic-level logging is emitted by the loader itself.
    secondary_loader_.ensure_loaded("router", *config.models.router);
}
Activity · 3 steps
lines 179–179◇ if (!config.models.router)lines 179–179return;lines 182–182secondary_loader_.ensure_loaded("router", *config.models.router);

Requirements

REQ-INFER-020

announce_eviction

void entropic::ModelOrchestrator::announce_eviction(const InferenceBackend *backend)

Fire Evicted for every tier backed by backend (gh#164), and clear the active-tier record when it names one of them.

src/inference/orchestrator.cpp:2012

Show on the map →

Called by release_backend

Calls fire_residency_observer

Source · 16 lines
void ModelOrchestrator::announce_eviction(const InferenceBackend* backend) {
    for (const auto& [name, bound] : tiers_) {
        if (bound.get() != backend) { continue; }
        auto cfg_it = config_.models.tiers.find(name);
        std::string path = cfg_it != config_.models.tiers.end()
            ? cfg_it->second.path.string() : "";
        auto fp_it = tier_footprint_bytes_.find(name);
        size_t footprint = fp_it != tier_footprint_bytes_.end()
            ? fp_it->second : 0;
        // Leave no stale incumbent: the next activation reads this to
        // decide whether a swap-out is needed.
        if (loaded_main_tier_ == name) { loaded_main_tier_.clear(); }
        fire_residency_observer(ResidencyEvent::Evicted, name, path,
                                footprint);
    }
}
Activity · 10 steps
lines 2013–2013◇ for (const auto& [name, bound] : tiers_)lines 2014–2014◇ if (bound.get() != backend)lines 2014–2014continue;lines 2015–2015auto cfg_it = config_.models.tiers.find(name);lines 2016–2017std::string path = cfg_it != config_.models.tiers.end() ? cfg_it->second.path.string() : "";lines 2018–2018auto fp_it = tier_footprint_bytes_.find(name);lines 2019–2020size_t footprint = fp_it != tier_footprint_bytes_.end() ? fp_it->second : 0;lines 2023–2023◇ if (loaded_main_tier_ == name)lines 2023–2023loaded_main_tier_.clear();lines 2024–2025fire_residency_observer(ResidencyEvent::Evicted, name, path, footprint);

Requirements

REQ-INFER-019

apply_adapter_parse

static void entropic::apply_adapter_parse(InferenceBackend *model, ChatAdapter *adapter, GenerationResult &result)

Split tool calls out of a result (gh#87: common_chat or adapter).

src/inference/orchestrator.cpp:602

Source · 13 lines
static void apply_adapter_parse(InferenceBackend* model,
                                ChatAdapter* adapter,
                                GenerationResult& result) {
    if (result.content.empty()) { return; }
    result.raw_content = result.content;
    // gh#108 (v2.10.3): one template-first/adapter-second rule, shared with
    // interface_factory. See response_parse.h for why content composes and
    // tool calls do not.
    auto parsed = parse_model_response(
        dynamic_cast<LlamaCppBackend*>(model), adapter, result.content);
    result.content = std::move(parsed.content);
    result.tool_calls = std::move(parsed.tool_calls);
}
Activity · 6 steps
lines 605–605◇ if (result.content.empty())lines 605–605return;lines 606–606result.raw_content = result.content;lines 610–611auto parsed = parse_model_response( dynamic_cast<LlamaCppBackend*>(model), adapter, result.content);lines 612–612result.content = std::move(parsed.content);lines 613–613result.tool_calls = std::move(parsed.tool_calls);

Requirements

REQ-INFER-010

apply_if_default

void entropic::anonymous_namespace{orchestrator.cpp}::apply_if_default(T &field, const std::optional< T > &ov, T dflt)

Apply a tier override iff set AND the field is still at its GenerationParams default (preserving a per-call override).

src/inference/orchestrator.cpp:2627

Source · 3 lines
inline void apply_if_default(T& field, const std::optional<T>& ov, T dflt) {
    if (ov.has_value() && field == dflt) { field = *ov; }
}
Activity · 2 steps
lines 2628–2628◇ if (ov.has_value() && field == dflt)lines 2628–2628field = *ov;

Requirements

REQ-INFER-021

apply_tier_sampler_defaults

void entropic::ModelOrchestrator::apply_tier_sampler_defaults(GenerationParams &params, const std::string &tier_name)

Apply per-tier sampler config to params.

src/inference/orchestrator.cpp:2674

Show on the map →

Called by apply_tier_sampler_defaults_for_test, resolve_and_stage

Calls apply_tier_sampler_overrides

Source · 29 lines
void ModelOrchestrator::apply_tier_sampler_defaults(
    GenerationParams& params, const std::string& tier_name)
{
    auto it = config_.models.tiers.find(tier_name);
    if (it == config_.models.tiers.end()) { return; }
    const auto& tier = it->second;
    TierSamplerOverrides ov;
    ov.temperature       = tier.temperature;
    ov.max_output_tokens = tier.max_output_tokens;
    ov.top_p             = tier.top_p;              // gh#85
    ov.top_k             = tier.top_k;              // gh#85
    ov.min_p             = tier.min_p;              // gh#85
    ov.presence_penalty  = tier.presence_penalty;   // gh#85
    ov.frequency_penalty = tier.frequency_penalty;  // gh#85
    ov.repeat_penalty    = tier.repeat_penalty;     // gh#86
    ov.enable_thinking   = tier.enable_thinking;    // gh#86
    ov.tool_call_mode    = tier.tool_call_mode;     // gh#103
    float before_temp = params.temperature;
    int before_max = params.max_tokens;
    apply_tier_sampler_overrides(params, ov);
    if (params.temperature != before_temp) {
        logger->info("Tier '{}' temperature applied: {}",
                     tier_name, params.temperature);
    }
    if (params.max_tokens != before_max) {
        logger->info("Tier '{}' max_output_tokens applied: {}",
                     tier_name, params.max_tokens);
    }
}
Activity · 22 steps
lines 2677–2677auto it = config_.models.tiers.find(tier_name);lines 2678–2678◇ if (it == config_.models.tiers.end())lines 2678–2678return;lines 2679–2679const auto& tier = it->second;lines 2680–2680TierSamplerOverrides ov;lines 2681–2681ov.temperature = tier.temperature;lines 2682–2682ov.max_output_tokens = tier.max_output_tokens;lines 2683–2683ov.top_p = tier.top_p;lines 2684–2684ov.top_k = tier.top_k;lines 2685–2685ov.min_p = tier.min_p;lines 2686–2686ov.presence_penalty = tier.presence_penalty;lines 2687–2687ov.frequency_penalty = tier.frequency_penalty;lines 2688–2688ov.repeat_penalty = tier.repeat_penalty;lines 2689–2689ov.enable_thinking = tier.enable_thinking;lines 2690–2690ov.tool_call_mode = tier.tool_call_mode;lines 2691–2691float before_temp = params.temperature;lines 2692–2692int before_max = params.max_tokens;lines 2693–2693apply_tier_sampler_overrides(params, ov);lines 2694–2694◇ if (params.temperature != before_temp)lines 2695–2696logger->info("Tier '{}' temperature applied: {}", tier_name, params.temperature);lines 2698–2698◇ if (params.max_tokens != before_max)lines 2699–2700logger->info("Tier '{}' max_output_tokens applied: {}", tier_name, params.max_tokens);

Requirements

REQ-INFER-021

apply_tier_sampler_overrides

void entropic::apply_tier_sampler_overrides(GenerationParams &params, const TierSamplerOverrides &ov)

Apply per-tier sampler overrides to params.

src/inference/orchestrator.cpp:2644

Source · 15 lines
void apply_tier_sampler_overrides(
    GenerationParams& params, const TierSamplerOverrides& ov)
{
    // GenerationParams struct defaults (see types/config.h).
    apply_if_default(params.temperature,       ov.temperature,       0.7f);
    apply_if_default(params.max_tokens,        ov.max_output_tokens, 4096);
    apply_if_default(params.top_p,             ov.top_p,             0.9f);
    apply_if_default(params.top_k,             ov.top_k,             40);
    apply_if_default(params.min_p,             ov.min_p,             0.0f);
    apply_if_default(params.presence_penalty,  ov.presence_penalty,  0.0f);
    apply_if_default(params.frequency_penalty, ov.frequency_penalty, 0.0f);
    apply_if_default(params.repeat_penalty,    ov.repeat_penalty,    1.1f);  // gh#86
    apply_if_default(params.enable_thinking,   ov.enable_thinking,   true);  // gh#86
    apply_if_default(params.tool_call_mode,    ov.tool_call_mode, std::string{});  // gh#103
}
Activity · 10 steps
lines 2648–2648apply_if_default(params.temperature, ov.temperature, 0.7f);lines 2649–2649apply_if_default(params.max_tokens, ov.max_output_tokens, 4096);lines 2650–2650apply_if_default(params.top_p, ov.top_p, 0.9f);lines 2651–2651apply_if_default(params.top_k, ov.top_k, 40);lines 2652–2652apply_if_default(params.min_p, ov.min_p, 0.0f);lines 2653–2653apply_if_default(params.presence_penalty, ov.presence_penalty, 0.0f);lines 2654–2654apply_if_default(params.frequency_penalty, ov.frequency_penalty, 0.0f);lines 2655–2655apply_if_default(params.repeat_penalty, ov.repeat_penalty, 1.1f);lines 2656–2656apply_if_default(params.enable_thinking, ov.enable_thinking, true);lines 2657–2657apply_if_default(params.tool_call_mode, ov.tool_call_mode, std::string{});

Requirements

REQ-INFER-021

build_routing_tables

void entropic::ModelOrchestrator::build_routing_tables(const ParsedConfig &config)

Build routing maps (tier_map_, handoff_rules_) from config.

src/inference/orchestrator.cpp:117

Show on the map →

Called by initialize

Calls none

Source · 9 lines
void ModelOrchestrator::build_routing_tables(const ParsedConfig& config) {
    for (const auto& [digit, tier_name] : config.routing.tier_map) {
        tier_map_[digit] = tier_name;
    }
    for (const auto& [src, targets] : config.routing.handoff_rules) {
        handoff_rules_[src] = std::unordered_set<std::string>(
            targets.begin(), targets.end());
    }
}
Activity · 4 steps
lines 118–118◇ for (const auto& [digit, tier_name] : config.routing.tier_map)lines 119–119tier_map_[digit] = tier_name;lines 121–121◇ for (const auto& [src, targets] : config.routing.handoff_rules)lines 122–123handoff_rules_[src] = std::unordered_set<std::string>( targets.begin(), targets.end());

Requirements

REQ-INFER-020

can_handoff

bool entropic::ModelOrchestrator::can_handoff(const std::string &from, const std::string &to) const

Check if handoff is permitted.

src/inference/orchestrator.cpp:2054

Show on the map →

Called by SCENARIO, TEST_CASE

Calls none

Source · 9 lines
bool ModelOrchestrator::can_handoff(
    const std::string& from, const std::string& to) const
{
    auto it = handoff_rules_.find(from);
    if (it == handoff_rules_.end()) {
        return false;
    }
    return it->second.count(to) > 0;
}
Activity · 4 steps
lines 2057–2057auto it = handoff_rules_.find(from);lines 2058–2058◇ if (it == handoff_rules_.end())lines 2059–2059return false;lines 2061–2061return it->second.count(to) > 0;

Requirements

REQ-INFER-020

classify_task

std::pair< std::string, std::string > entropic::ModelOrchestrator::classify_task(const std::vector< Message > &messages)

Classify task using router model.

src/inference/orchestrator.cpp:1209

Source · 69 lines
std::pair<std::string, std::string> ModelOrchestrator::classify_task(
    const std::vector<Message>& messages)
{
    // gh#158 (v2.13.0): the router decodes, so this is a generation entry
    // point and takes the same outermost lock. Reached from `route()` inside
    // an already-locked `generate*`, which is exactly why the lock is
    // recursive — see `generation_mutex_` in orchestrator.h.
    std::lock_guard<std::recursive_mutex> gen_lock(generation_mutex_);
    std::string user_msg = extract_latest_user_message(messages);

    GenerationParams router_params;
    router_params.max_tokens = 1;
    router_params.temperature = 0.0f;

    // gh#198: a defer_load handle did not load the router at init. No-op
    // when it is already loaded or not configured; ensure_loaded locks its
    // own slots_mutex_, and this runs under generation_mutex_.
    activate_router(config_);
    auto* router_backend = secondary_loader_.get("router");
    if (router_backend == nullptr) {
        logger->warn("classify_task: router not loaded; returning empty");
        return {"", ""};
    }
    // audit task #71: a non-fine-tuned router fed the bare "<msg> ->" just
    // CONTINUES the text and never emits a routing digit, so classify_task
    // silently always fell back to the default tier. When the deployment
    // configures routing.classification_prompt, prepend it so a general
    // instruct model is actually told the digit scheme. (The trailing " ->"
    // still constrains it to a single digit, per build_classification_prompt.)
    std::string router_prompt = user_msg + " ->";
    const auto& cprompt = config_.routing.classification_prompt;
    if (cprompt.has_value() && !cprompt->empty()) {
        router_prompt = *cprompt + "\n" + user_msg + " ->";
        // A general instruct model emits a leading space before the digit;
        // max_tokens=1 would cut it off. 4 captures "<space>1"; the digit scan
        // below takes the first tier_map char. Only widened on the prompt path
        // so unconfigured deployments keep the original 1-token behavior.
        router_params.max_tokens = 4;
        // v2.8.1 (review #3): classification_prompt was parsed-but-never-read
        // before the v2.8.0 fix. Log when the active (prompt) path is taken so
        // a deployment carrying a stale prompt sees the inert->active switch +
        // the widened token budget instead of a silent behavior change.
        logger->info("classify_task: using configured classification_prompt "
                     "(router instructed; max_tokens widened to 4)");
    }
    auto result = router_backend->complete(router_prompt, router_params);
    std::string raw = result.content;

    // Trim whitespace
    auto start = raw.find_first_not_of(" \t\n\r");
    if (start != std::string::npos) {
        raw = raw.substr(start);
    }

    // Find matching tier
    for (char c : raw) {
        std::string digit(1, c);
        auto it = tier_map_.find(digit);
        if (it != tier_map_.end()) {
            logger->info("Route: digit='{}' -> tier='{}'",
                         digit, it->second);
            return {it->second, digit};
        }
    }

    logger->warn("Route: no valid digit in '{}', defaulting to {}",
                 raw, default_tier_);
    return {default_tier_, ""};
}
Activity · 29 steps
lines 1216–1216std::lock_guard<std::recursive_mutex> gen_lock(generation_mutex_);lines 1217–1217std::string user_msg = extract_latest_user_message(messages);lines 1219–1219GenerationParams router_params;lines 1220–1220router_params.max_tokens = 1;lines 1221–1221router_params.temperature = 0.0f;lines 1226–1226activate_router(config_);lines 1227–1227auto* router_backend = secondary_loader_.get("router");lines 1228–1228◇ if (router_backend == nullptr)lines 1229–1229logger->warn("classify_task: router not loaded; returning empty");lines 1230–1230return {"", ""};lines 1238–1238std::string router_prompt = user_msg + " ->";lines 1239–1239const auto& cprompt = config_.routing.classification_prompt;lines 1240–1240◇ if (cprompt.has_value() && !cprompt->empty())lines 1241–1241router_prompt = *cprompt + "\n" + user_msg + " ->";lines 1246–1246router_params.max_tokens = 4;lines 1251–1252logger->info("classify_task: using configured classification_prompt " "(router instructed; max_tokens widened to 4)");lines 1254–1254auto result = router_backend->complete(router_prompt, router_params);lines 1255–1255std::string raw = result.content;lines 1258–1258auto start = raw.find_first_not_of(" \t\n\r");lines 1259–1259◇ if (start != std::string::npos)lines 1260–1260raw = raw.substr(start);lines 1264–1264◇ for (char c : raw)lines 1265–1265std::string digit(1, c);lines 1266–1266auto it = tier_map_.find(digit);lines 1267–1267◇ if (it != tier_map_.end())lines 1268–1269logger->info("Route: digit='{}' -> tier='{}'", digit, it->second);lines 1270–1270return {it->second, digit};lines 1274–1275logger->warn("Route: no valid digit in '{}', defaulting to {}", raw, default_tier_);lines 1276–1276return {default_tier_, ""};

Requirements

REQ-INFER-020

clear_all_prompt_caches

void entropic::ModelOrchestrator::clear_all_prompt_caches()

Invalidate prompt/KV caches across every pooled backend.

src/inference/orchestrator.cpp:2249

Show on the map →

Called by SCENARIO, SCENARIO, TEST_CASE, init_engine_and_interfaces

Tested by

1 teststestCaseStarting

Calls clear_all_prompt_caches, clear_prompt_cache

Source · 8 lines
void ModelOrchestrator::clear_all_prompt_caches() {
    for (auto& [_, backend] : model_pool_) {
        if (backend) { backend->clear_prompt_cache(); }
    }
    secondary_loader_.clear_all_prompt_caches();
    logger->info("Prompt caches invalidated across all backends "
                 "(identity change)");
}
Activity · 5 steps
lines 2250–2250◇ for (auto& [_, backend] : model_pool_)lines 2251–2251◇ if (backend)lines 2251–2251backend->clear_prompt_cache();lines 2253–2253secondary_loader_.clear_all_prompt_caches();lines 2254–2255logger->info("Prompt caches invalidated across all backends " "(identity change)");

Requirements

REQ-INFER-020

config_admits

bool entropic::ModelOrchestrator::config_admits(const std::string &tier_name)

Refuse an explicit config that provably cannot work (gh#148).

src/inference/orchestrator.cpp:1528

Source · 36 lines
bool ModelOrchestrator::config_admits(const std::string& tier_name) {
    auto it = config_.models.tiers.find(tier_name);
    if (it == config_.models.tiers.end()) { return true; }
    const auto& cfg = it->second;
    std::error_code ec;
    auto file_bytes = std::filesystem::file_size(cfg.path, ec);
    if (ec) { return true; }

    const uint64_t memlock = host_memlock_limit_bytes();
    bool refused = true;
    // v2.13.1: an expert split leaves expert weights HOST-resident while
    // gpu_layers reports -1, so the pinned bytes are theirs, not the file's.
    const uint64_t host_experts = host_expert_bytes_for(cfg);
    if (mlock_refused(cfg.use_mlock, file_bytes, cfg.gpu_layers, memlock,
                      host_experts)) {
        const uint64_t pinned = host_experts > 0 ? host_experts : file_bytes;
        refuse_residency(tier_name, ENTROPIC_ERROR_MLOCK_LIMIT_EXCEEDED,
            "use_mlock would pin " + std::to_string(pinned)
            + " bytes against an RLIMIT_MEMLOCK of "
            + std::to_string(memlock)
            + " bytes. Pinned pages cannot be reclaimed under pressure, so "
              "a partially offloaded model of this size is killed rather "
              "than paged. Set use_mlock: false for this tier.");
    } else if (gpu_offload_refused(file_bytes, cfg.gpu_layers,
                                   vram_budget_bytes_)) {
        refuse_residency(tier_name, ENTROPIC_ERROR_TIER_MODEL_TOO_LARGE,
            "gpu_layers=" + std::to_string(cfg.gpu_layers) + " cannot fit: "
            + std::to_string(vram_budget_bytes_ / (1024 * 1024))
            + " MiB of free VRAM is not enough for the compute buffers "
              "alone, so no positive layer count can work. Free VRAM, or "
              "set gpu_layers: 0 to run on the CPU.");
    } else {
        refused = false;
    }
    return !refused;
}
Activity · 20 steps
lines 1529–1529auto it = config_.models.tiers.find(tier_name);lines 1530–1530◇ if (it == config_.models.tiers.end())lines 1530–1530return true;lines 1531–1531const auto& cfg = it->second;lines 1532–1532std::error_code ec;lines 1533–1533auto file_bytes = std::filesystem::file_size(cfg.path, ec);lines 1534–1534◇ if (ec)lines 1534–1534return true;lines 1536–1536const uint64_t memlock = host_memlock_limit_bytes();lines 1537–1537bool refused = true;lines 1540–1540const uint64_t host_experts = host_expert_bytes_for(cfg);lines 1541–1542◇ if (mlock_refused(cfg.use_mlock, file_bytes, cfg.gpu_layers, memlock, host_experts))lines 1543–1543const uint64_t pinned = host_experts > 0 ? host_experts : file_bytes;lines 1544–1550refuse_residency(tier_name, ENTROPIC_ERROR_MLOCK_LIMIT_EXCEEDED, "use_mlock would pin " + std::to_string(pinned) + " bytes against an RLIMIT_MEMLOCK of " + std::to_string(memlock) + " bytes. Pinned pages cannot be reclaimed under pressure, so " "a partially offloaded model of this size is killed rather " "than paged. Set use_mlock: false for this tier.");lines 1551–1551elselines 1551–1552◇ if (gpu_offload_refused(file_bytes, cfg.gpu_layers, vram_budget_bytes_))lines 1553–1558refuse_residency(tier_name, ENTROPIC_ERROR_TIER_MODEL_TOO_LARGE, "gpu_layers=" + std::to_string(cfg.gpu_layers) + " cannot fit: " + std::to_string(vram_budget_bytes_ / (1024 * 1024)) + " MiB of free VRAM is not enough for the compute buffers " "alone, so no positive layer count can work. Free VRAM, or " "set gpu_layers: 0 to run on the CPU.");lines 1559–1559elselines 1560–1560refused = false;lines 1562–1562return !refused;

Requirements

REQ-INFER-019

ensure_model

InferenceBackend * entropic::ModelOrchestrator::ensure_model(const std::string &tier_name)

Get a tier's backend, loading it if it is not resident (gh#157).

src/inference/orchestrator.cpp:1932

Show on the map →

Called by SCENARIO, SCENARIO, do_adapter_load, require_ready_backend

Calls get_model

Source · 4 lines
InferenceBackend* ModelOrchestrator::ensure_model(
    const std::string& tier_name) {
    return get_model(tier_name);
}
Activity · 1 steps
lines 1934–1934return get_model(tier_name);

Requirements

REQ-INFER-019

ensure_secondary_roles

void entropic::ModelOrchestrator::ensure_secondary_roles()

Re-ensure the secondary roles (router, draft) after a release (gh#164).

src/inference/orchestrator.cpp:224

Source · 4 lines
void ModelOrchestrator::ensure_secondary_roles() {
    activate_router(config_);
    activate_draft(config_);
}
Activity · 2 steps
lines 225–225activate_router(config_);lines 226–226activate_draft(config_);

Requirements

REQ-INFER-020

ensure_vram_budget

void entropic::ModelOrchestrator::ensure_vram_budget()

Resolve the VRAM budget once, on first need (gh#198).

src/inference/orchestrator.cpp:2749

Source · 10 lines
void ModelOrchestrator::ensure_vram_budget() {
    if (vram_budget_resolved_) { return; }
    const bool from_env = std::getenv("ENTROPIC_VRAM_BUDGET_BYTES") != nullptr;
    vram_budget_bytes_ = resolve_vram_budget_bytes();
    vram_budget_resolved_ = true;
    // The pre-2.14.0 line labelled every budget "(ENTROPIC_VRAM_BUDGET_BYTES)",
    // including the far more common device-measured one.
    logger->info("[residency] VRAM budget: {} bytes ({})", vram_budget_bytes_,
                 from_env ? "ENTROPIC_VRAM_BUDGET_BYTES" : "device free VRAM");
}
Activity · 6 steps
lines 2750–2750◇ if (vram_budget_resolved_)lines 2750–2750return;lines 2751–2751const bool from_env = std::getenv("ENTROPIC_VRAM_BUDGET_BYTES") != nullptr;lines 2752–2752vram_budget_bytes_ = resolve_vram_budget_bytes();lines 2753–2753vram_budget_resolved_ = true;lines 2756–2757logger->info("[residency] VRAM budget: {} bytes ({})", vram_budget_bytes_, from_env ? "ENTROPIC_VRAM_BUDGET_BYTES" : "device free VRAM");

Requirements

REQ-INFER-019

estimate_footprint_bytes

size_t entropic::ModelOrchestrator::estimate_footprint_bytes(const std::string &tier_name) const

Compute the cached/estimated footprint for a tier in bytes.

src/inference/orchestrator.cpp:2789

Show on the map →

Called by record_activation_reuse, residency_admits, residency_snapshot_json, tier_footprint_bytes

Calls estimate_vram_footprint, footprint_inputs_for

Source · 15 lines
size_t ModelOrchestrator::estimate_footprint_bytes(
    const std::string& tier_name) const {
    auto tier_it = config_.models.tiers.find(tier_name);
    if (tier_it == config_.models.tiers.end()) { return 0; }
    const auto& tier_cfg = tier_it->second;
    std::error_code ec;
    auto weights = std::filesystem::file_size(tier_cfg.path, ec);
    if (ec) { return 0; }
    FootprintInputs in = footprint_inputs_for(
        tier_cfg, weights, config_.vram_reserve_mb);
    // gh#142: an unpriceable placement returns 0 = "unknown", which leaves the
    // gate open. Guessing here would refuse working configurations — a 13 GB
    // model at gpu_layers=15 runs fine on an 11 GB card.
    return static_cast<size_t>(estimate_vram_footprint(in).bytes);
}
Activity · 10 steps
lines 2791–2791auto tier_it = config_.models.tiers.find(tier_name);lines 2792–2792◇ if (tier_it == config_.models.tiers.end())lines 2792–2792return 0;lines 2793–2793const auto& tier_cfg = tier_it->second;lines 2794–2794std::error_code ec;lines 2795–2795auto weights = std::filesystem::file_size(tier_cfg.path, ec);lines 2796–2796◇ if (ec)lines 2796–2796return 0;lines 2797–2798FootprintInputs in = footprint_inputs_for( tier_cfg, weights, config_.vram_reserve_mb);lines 2802–2802return static_cast<size_t>(estimate_vram_footprint(in).bytes);

Requirements

REQ-INFER-019

extract_latest_user_message

std::string entropic::anonymous_namespace{orchestrator.cpp}::extract_latest_user_message(const std::vector< Message > &messages)

Extract latest user message from conversation.

src/inference/orchestrator.cpp:53

Source · 8 lines
std::string extract_latest_user_message(const std::vector<Message>& messages) {
    for (auto it = messages.rbegin(); it != messages.rend(); ++it) {
        if (it->role == "user") {
            return it->content;
        }
    }
    return "";
}
Activity · 4 steps
lines 54–54◇ for (auto it = messages.rbegin(); it != messages.rend(); ++it)lines 55–55◇ if (it->role == "user")lines 56–56return it->content;lines 59–59return "";

Requirements

REQ-INFER-020

finish_generation

void entropic::ModelOrchestrator::finish_generation(GenerationResult &result, InferenceBackend *model, const GenerationParams &resolved_params, const std::string &selected, double routing_ms, double swap_ms, std::chrono::steady_clock::time_point t_start)

Shared tail of both non-streaming generate() overloads.

src/inference/orchestrator.cpp:2384

Show on the map →

Called by generate

Calls apply_adapter_parse, elapsed_ms, get_adapter, log_orchestration, now, record_generation, warn_turn_diagnostics

Source · 22 lines
void ModelOrchestrator::finish_generation(
    GenerationResult& result,
    InferenceBackend* model,
    const GenerationParams& resolved_params,
    const std::string& selected,
    double routing_ms,
    double swap_ms,
    std::chrono::steady_clock::time_point t_start)
{
    apply_adapter_parse(model, get_adapter(selected), result);
    // gh#134 (v2.10.4): name a budget-starved mandatory-tool turn.
    warn_turn_diagnostics(result, selected, config_.models.tiers);

    result.routing_ms = routing_ms;
    result.swap_ms = swap_ms;
    result.total_ms = elapsed_ms(t_start, now());
    // gh#154: one record per generation, at the tail every orchestrated
    // path already shares — so a new decode path cannot ship unrecorded.
    record_generation(result, resolved_params, model);
    log_orchestration(result, selected, last_routing_result_.adapter_name,
                      resolved_params, routing_ms, swap_ms);
}
Activity · 7 steps
lines 2393–2393apply_adapter_parse(model, get_adapter(selected), result);lines 2395–2395warn_turn_diagnostics(result, selected, config_.models.tiers);lines 2397–2397result.routing_ms = routing_ms;lines 2398–2398result.swap_ms = swap_ms;lines 2399–2399result.total_ms = elapsed_ms(t_start, now());lines 2402–2402record_generation(result, resolved_params, model);lines 2403–2404log_orchestration(result, selected, last_routing_result_.adapter_name, resolved_params, routing_ms, swap_ms);

Requirements

REQ-INFER-008

forget_session_kv

void entropic::ModelOrchestrator::forget_session_kv(const std::string &session_key)

Drop one session's resident KV on every loaded tier (gh#165).

src/inference/orchestrator.cpp:2902

Show on the map →

Called by session_context_set_inner

Calls forget_session_kv

Source · 13 lines
void ModelOrchestrator::forget_session_kv(const std::string& session_key) {
    // Outermost lock: this mutates the live llama_context's KV cells, which
    // is precisely what a concurrent decode is reading. See the declaration
    // for why api_mutex -> generation_mutex_ closes no cycle.
    std::lock_guard<std::recursive_mutex> gen_lock(generation_mutex_);
    std::unordered_set<const InferenceBackend*> seen;
    for (const auto& [name, backend] : tiers_) {
        (void)name;
        if (!backend || !backend->is_loaded()) { continue; }
        if (!seen.insert(backend.get()).second) { continue; }
        backend->forget_session_kv(session_key);
    }
}
Activity · 9 steps
lines 2906–2906std::lock_guard<std::recursive_mutex> gen_lock(generation_mutex_);lines 2907–2907std::unordered_set<const InferenceBackend*> seen;lines 2908–2908◇ for (const auto& [name, backend] : tiers_)lines 2909–2909(void)name;lines 2910–2910◇ if (!backend || !backend->is_loaded())lines 2910–2910continue;lines 2911–2911◇ if (!seen.insert(backend.get()).second)lines 2911–2911continue;lines 2912–2912backend->forget_session_kv(session_key);

Requirements

REQ-LOOP-010

generate_streaming

GenerationResult entropic::ModelOrchestrator::generate_streaming(const std::vector< Message > &messages, const GenerationParams &params, std::function< void(std::string_view)> on_token, std::atomic< bool > &cancel, const std::string &tier_name="")

Streaming generation.

src/inference/orchestrator.cpp:1074

Show on the map →

Called by SCENARIO, SCENARIO, TEST_CASE, TEST_CASE, TEST_CASE, iface_generate_stream

Calls apply_adapter_parse, flush, generate_streaming, get_adapter, get_model, on_token, on_token, record_generation, refuse_unresolved_tier_grammar, resolve_and_stage, route, stream_token_trampoline

2 moretry_speculative_route_streaming, warn_turn_diagnostics

Source · 70 lines
GenerationResult ModelOrchestrator::generate_streaming(
    const std::vector<Message>& messages,
    const GenerationParams& params,
    std::function<void(std::string_view)> on_token,
    std::atomic<bool>& cancel,
    const std::string& tier_name)
{
    // gh#158 (v2.13.0): one lock, outermost on the generation path.
    // See `generation_mutex_` in orchestrator.h for the full order.
    std::lock_guard<std::recursive_mutex> gen_lock(generation_mutex_);
    std::string selected = tier_name.empty() ? route(messages) : tier_name;

    // gh#154: refuse an unregistered tier grammar before the model is
    // resolved — no swap, no prefill, and not one token streamed.
    GenerationParams resolved_params = params;
    auto refusal = refuse_unresolved_tier_grammar(resolved_params, selected);
    if (refusal.has_value()) { return *refusal; }

    InferenceBackend* model = get_model(selected);

    if (!model) {
        GenerationResult err;
        err.error_code = ENTROPIC_ERROR_GENERATE_FAILED;
        err.error_message = "No model for tier: " + selected;
        err.finish_reason = "error";
        return err;
    }

    resolved_params =
        resolve_and_stage(model, resolved_params, selected);  // gh#87 3b

    // gh#108 (v2.10.3): strip this family's reasoning blocks from the live
    // stream. v2.10.0 added the filter but left it on its hardcoded `<think>`
    // pair, so gemma4's `<|channel>` passed straight through. Markers now come
    // from the resolved adapter, the same source the buffered strip uses.
    //
    // This is not cosmetic: ResponseGenerator::generate_streaming builds
    // result.content from its OWN token accumulator and discards what
    // apply_adapter_parse produced, so on the agent-loop streaming path this
    // filter is the only thing standing between raw reasoning and the
    // conversation history.
    auto* stream_adapter = get_adapter(selected);
    const auto markers = (stream_adapter != nullptr)
        ? stream_adapter->thinking_markers() : ThinkMarkers{};
    StreamThinkFilter filter(stream_token_trampoline, &on_token,
                             markers.open, markers.close);
    auto filtered = [&filter](std::string_view sv) {
        filter.on_token(sv.data(), sv.size());
    };

    GenerationResult result;
    bool routed = config_.inference.speculative.enabled
        && try_speculative_route_streaming(
               model, messages, resolved_params, selected, filtered, cancel,
               result);
    if (!routed) {
        result = model->generate_streaming(
            messages, resolved_params, filtered, cancel);
    }
    filter.flush();
    apply_adapter_parse(model, get_adapter(selected), result);
    // gh#134 (v2.10.4): name a budget-starved mandatory-tool turn.
    warn_turn_diagnostics(result, selected,
                                         config_.models.tiers);
    // gh#154: the streaming path runs the speculative/MTP kernels, so
    // leaving it unrecorded would omit exactly the decodes whose
    // drafted/accepted counts the record exists to carry.
    record_generation(result, resolved_params, model);
    return result;
}
Activity · 27 steps
lines 1083–1083std::lock_guard<std::recursive_mutex> gen_lock(generation_mutex_);lines 1084–1084std::string selected = tier_name.empty() ? route(messages) : tier_name;lines 1088–1088GenerationParams resolved_params = params;lines 1089–1089auto refusal = refuse_unresolved_tier_grammar(resolved_params, selected);lines 1090–1090◇ if (refusal.has_value())lines 1090–1090return *refusal;lines 1092–1092InferenceBackend* model = get_model(selected);lines 1094–1094◇ if (!model)lines 1095–1095GenerationResult err;lines 1096–1096err.error_code = ENTROPIC_ERROR_GENERATE_FAILED;lines 1097–1097err.error_message = "No model for tier: " + selected;lines 1098–1098err.finish_reason = "error";lines 1099–1099return err;lines 1102–1103resolved_params = resolve_and_stage(model, resolved_params, selected);lines 1115–1115auto* stream_adapter = get_adapter(selected);lines 1116–1117const auto markers = (stream_adapter != nullptr) ? stream_adapter->thinking_markers() : ThinkMarkers{};lines 1118–1119StreamThinkFilter filter(stream_token_trampoline, &on_token, markers.open, markers.close);lines 1120–1122auto filtered = [&filter](std::string_view sv) { filter.on_token(sv.data(), sv.size()); };lines 1124–1124GenerationResult result;lines 1125–1128bool routed = config_.inference.speculative.enabled && try_speculative_route_streaming( model, messages, resolved_params, selected, filtered, cancel, result);lines 1129–1129◇ if (!routed)lines 1130–1131result = model->generate_streaming( messages, resolved_params, filtered, cancel);lines 1133–1133filter.flush();lines 1134–1134apply_adapter_parse(model, get_adapter(selected), result);lines 1136–1137warn_turn_diagnostics(result, selected, config_.models.tiers);lines 1141–1141record_generation(result, resolved_params, model);lines 1142–1142return result;

Requirements

REQ-INFER-005 REQ-INFER-007 REQ-INFER-008 REQ-INFER-011

generation_records

std::vector< GenerationRecord > entropic::ModelOrchestrator::generation_records() const

Per-generation metric records, oldest first (gh#154).

src/inference/orchestrator.cpp:2437

Show on the map →

Called by TEST_CASE, generations_json, run_trial

Calls none

Source · 5 lines
std::vector<GenerationRecord> ModelOrchestrator::generation_records() const
{
    std::lock_guard<std::mutex> lock(records_mutex_);
    return generation_records_;
}
Activity · 2 steps
lines 2439–2439std::lock_guard<std::mutex> lock(records_mutex_);lines 2440–2440return generation_records_;

Requirements

REQ-INFER-008

has_vision_capable_tier

bool entropic::ModelOrchestrator::has_vision_capable_tier() const

Return true if any configured tier declares the "vision" capability (gh#41, v2.1.8).

src/inference/orchestrator.cpp:2266

Show on the map →

Called by SCENARIO, SCENARIO, parse_and_check_vision

Calls has_capability

Source · 6 lines
bool ModelOrchestrator::has_vision_capable_tier() const {
    for (const auto& [_, tier] : config_.models.tiers) {
        if (tier.has_capability("vision")) { return true; }
    }
    return false;
}
Activity · 4 steps
lines 2267–2267◇ for (const auto& [_, tier] : config_.models.tiers)lines 2268–2268◇ if (tier.has_capability("vision"))lines 2268–2268return true;lines 2270–2270return false;

Requirements

REQ-INFER-025

last_routing_result

RoutingResult entropic::ModelOrchestrator::last_routing_result() const

Last routing result.

src/inference/orchestrator.cpp:1856

Show on the map →

Called by SCENARIO, SCENARIO, SCENARIO, TEST_CASE

Calls none

Source · 3 lines
RoutingResult ModelOrchestrator::last_routing_result() const {
    return last_routing_result_;
}
Activity · 1 steps
lines 1857–1857return last_routing_result_;

Requirements

REQ-INFER-020

loaded_models

std::vector< std::string > entropic::ModelOrchestrator::loaded_models() const

Currently loaded model tier names.

src/inference/orchestrator.cpp:1881

Show on the map →

Called by SCENARIO, SCENARIO, SCENARIO, SCENARIO, TEST_CASE, TEST_CASE, release_reload_cycle

Calls is_loaded

Source · 12 lines
std::vector<std::string> ModelOrchestrator::loaded_models() const {
    std::vector<std::string> result;
    for (const auto& [name, backend] : tiers_) {
        if (backend->is_loaded()) {
            result.push_back(name);
        }
    }
    if (secondary_loader_.is_loaded("router")) {
        result.push_back("router");
    }
    return result;
}
Activity · 7 steps
lines 1882–1882std::vector<std::string> result;lines 1883–1883◇ for (const auto& [name, backend] : tiers_)lines 1884–1884◇ if (backend->is_loaded())lines 1885–1885result.push_back(name);lines 1888–1888◇ if (secondary_loader_.is_loaded("router"))lines 1889–1889result.push_back("router");lines 1891–1891return result;

Requirements

REQ-INFER-020

log_fit_recommendation

void entropic::ModelOrchestrator::log_fit_recommendation(const std::string &tier_name) const

Log the largest context that would fit a refused tier (gh#142).

src/inference/orchestrator.cpp:1330

Source · 25 lines
void ModelOrchestrator::log_fit_recommendation(
    const std::string& tier_name) const {
    auto tier_it = config_.models.tiers.find(tier_name);
    if (tier_it == config_.models.tiers.end()) { return; }
    const auto& tier_cfg = tier_it->second;
    std::error_code ec;
    auto weights = std::filesystem::file_size(tier_cfg.path, ec);
    if (ec) { return; }
    FootprintInputs in = footprint_inputs_for(
        tier_cfg, weights, config_.vram_reserve_mb);
    int fits = recommend_context_length(in, vram_budget_bytes_);
    if (fits > 0) {
        logger->error("[residency] tier '{}' fits at context_length={} "
                      "(requested {}) — lower it, or reduce gpu_layers to "
                      "keep the requested context",
                      tier_name, fits, tier_cfg.context_length);
    } else {
        logger->error("[residency] tier '{}' does not fit at ANY context "
                      "length: weights{} alone exceed the {} MiB budget. "
                      "Reduce gpu_layers, or use a smaller quantization.",
                      tier_name,
                      in.mmproj_bytes > 0 ? " + vision projector" : "",
                      vram_budget_bytes_ / (1024 * 1024));
    }
}
Activity · 14 steps
lines 1332–1332auto tier_it = config_.models.tiers.find(tier_name);lines 1333–1333◇ if (tier_it == config_.models.tiers.end())lines 1333–1333return;lines 1334–1334const auto& tier_cfg = tier_it->second;lines 1335–1335std::error_code ec;lines 1336–1336auto weights = std::filesystem::file_size(tier_cfg.path, ec);lines 1337–1337◇ if (ec)lines 1337–1337return;lines 1338–1339FootprintInputs in = footprint_inputs_for( tier_cfg, weights, config_.vram_reserve_mb);lines 1340–1340int fits = recommend_context_length(in, vram_budget_bytes_);lines 1341–1341◇ if (fits > 0)lines 1342–1345logger->error("[residency] tier '{}' fits at context_length={} " "(requested {}) — lower it, or reduce gpu_layers to " "keep the requested context", tier_name, fits, tier_cfg.context_length);lines 1346–1346elselines 1347–1352logger->error("[residency] tier '{}' does not fit at ANY context " "length: weights{} alone exceed the {} MiB budget. " "Reduce gpu_layers, or use a smaller quantization.", tier_name, in.mmproj_bytes > 0 ? " + vision projector" : "", vram_budget_bytes_ / (1024 * 1024));

Requirements

REQ-INFER-019

mtp_head_guard_fires

static bool entropic::mtp_head_guard_fires(LlamaCppBackend *draft, GenerationResult &result)

gh#107: return true (and populate result) when draft looks like an MTP head GGUF routed to the classical separate-draft path.

src/inference/orchestrator.cpp:453

Show on the map →

Called by try_speculative_route_streaming

Calls llama_model_ptr, looks_like_mtp_head, mtp_head_classical_path_error

Source · 11 lines
static bool mtp_head_guard_fires(LlamaCppBackend* draft,
                                 GenerationResult& result) {
    auto* dm = draft->llama_model_ptr();
    if (dm == nullptr) { return false; }
    int n = llama_model_n_layer(dm);
    if (!looks_like_mtp_head(n)) { return false; }
    result.error_code = ENTROPIC_ERROR_SPECULATIVE_INCOMPATIBLE_CONFIG;
    result.error_message = mtp_head_classical_path_error(n);
    result.finish_reason = "error";
    return true;
}
Activity · 10 steps
lines 455–455auto* dm = draft->llama_model_ptr();lines 456–456◇ if (dm == nullptr)lines 456–456return false;lines 457–457int n = llama_model_n_layer(dm);lines 458–458◇ if (!looks_like_mtp_head(n))lines 458–458return false;lines 459–459result.error_code = ENTROPIC_ERROR_SPECULATIVE_INCOMPATIBLE_CONFIG;lines 460–460result.error_message = mtp_head_classical_path_error(n);lines 461–461result.finish_reason = "error";lines 462–462return true;

Requirements

REQ-INFER-015

normalize_grammar_key

static std::string entropic::normalize_grammar_key(const std::string &grammar_value)

Normalize a frontmatter grammar value to a registry key.

src/inference/orchestrator.cpp:2454

Source · 7 lines
static std::string normalize_grammar_key(const std::string& grammar_value) {
    std::filesystem::path p(grammar_value);
    if (p.extension() == ".gbnf") {
        return p.stem().string();
    }
    return grammar_value;
}
Activity · 4 steps
lines 2455–2455std::filesystem::path p(grammar_value);lines 2456–2456◇ if (p.extension() == ".gbnf")lines 2457–2457return p.stem().string();lines 2459–2459return grammar_value;

Requirements

REQ-INFER-007

preload_adapters_for_model

void entropic::ModelOrchestrator::preload_adapters_for_model(InferenceBackend *backend)

Preload the LoRA adapters of every tier sharing one backend, at that backend's activation (gh#157).

src/inference/orchestrator.cpp:2164

Show on the map →

Called by activate_and_track

Calls llama_model_ptr, load, state

Source · 23 lines
void ModelOrchestrator::preload_adapters_for_model(
    InferenceBackend* backend) {
    auto* llama_backend = dynamic_cast<LlamaCppBackend*>(backend);
    if (!llama_backend || !llama_backend->llama_model_ptr()) { return; }

    int loaded = 0;
    for (const auto& [name, tier_cfg] : config_.models.tiers) {
        auto tier_it = tiers_.find(name);
        bool mine = tier_cfg.adapter_path.has_value()
            && tier_it != tiers_.end()
            && tier_it->second.get() == backend
            && lora_manager_.state(name) == AdapterState::COLD;
        if (mine && lora_manager_.load(name, *tier_cfg.adapter_path,
                                       llama_backend->llama_model_ptr(),
                                       tier_cfg.adapter_scale)) {
            ++loaded;
        }
    }

    if (loaded > 0) {
        logger->info("Preloaded {} LoRA adapter(s) to WARM", loaded);
    }
}
Activity · 11 steps
lines 2166–2166auto* llama_backend = dynamic_cast<LlamaCppBackend*>(backend);lines 2167–2167◇ if (!llama_backend || !llama_backend->llama_model_ptr())lines 2167–2167return;lines 2169–2169int loaded = 0;lines 2170–2170◇ for (const auto& [name, tier_cfg] : config_.models.tiers)lines 2171–2171auto tier_it = tiers_.find(name);lines 2172–2175bool mine = tier_cfg.adapter_path.has_value() && tier_it != tiers_.end() && tier_it->second.get() == backend && lora_manager_.state(name) == AdapterState::COLD;lines 2176–2178◇ if (mine && lora_manager_.load(name, *tier_cfg.adapter_path, llama_backend->llama_model_ptr(), tier_cfg.adapter_scale))lines 2179–2179++loaded;lines 2183–2183◇ if (loaded > 0)lines 2184–2184logger->info("Preloaded {} LoRA adapter(s) to WARM", loaded);

Requirements

REQ-INFER-023

record_generation

void entropic::ModelOrchestrator::record_generation(GenerationResult &result, const GenerationParams &resolved_params, const InferenceBackend *model)

Attach grammar provenance and append a metric record (gh#154).

src/inference/orchestrator.cpp:2415

Show on the map →

Called by finish_generation, generate_batch, generate_streaming

Calls active_tool_grammar, describe_grammar, make_generation_record

Source · 15 lines
void ModelOrchestrator::record_generation(
    GenerationResult& result,
    const GenerationParams& resolved_params,
    const InferenceBackend* model)
{
    const std::string tool_grammar =
        model != nullptr ? model->active_tool_grammar() : std::string{};
    result.grammar = describe_grammar(resolved_params, tool_grammar);

    std::lock_guard<std::mutex> lock(records_mutex_);
    if (generation_records_.size() >= kMaxGenerationRecords) {
        generation_records_.erase(generation_records_.begin());
    }
    generation_records_.push_back(make_generation_record(result));
}
Activity · 6 steps
lines 2420–2421const std::string tool_grammar = model != nullptr ? model->active_tool_grammar() : std::string{};lines 2422–2422result.grammar = describe_grammar(resolved_params, tool_grammar);lines 2424–2424std::lock_guard<std::mutex> lock(records_mutex_);lines 2425–2425◇ if (generation_records_.size() >= kMaxGenerationRecords)lines 2426–2426generation_records_.erase(generation_records_.begin());lines 2428–2428generation_records_.push_back(make_generation_record(result));

Requirements

REQ-INFER-008

refuse_residency

void entropic::ModelOrchestrator::refuse_residency(const std::string &tier_name, entropic_error_t code, const std::string &why)

Log a refusal and stash its typed code + message (gh#148).

src/inference/orchestrator.cpp:1574

Source · 7 lines
void ModelOrchestrator::refuse_residency(const std::string& tier_name,
                                         entropic_error_t code,
                                         const std::string& why) {
    logger->error("[residency] tier '{}' refused: {}", tier_name, why);
    last_residency_error_ = code;
    last_residency_message_ = "Tier '" + tier_name + "': " + why;
}
Activity · 3 steps
lines 1577–1577logger->error("[residency] tier '{}' refused: {}", tier_name, why);lines 1578–1578last_residency_error_ = code;lines 1579–1579last_residency_message_ = "Tier '" + tier_name + "': " + why;

Requirements

REQ-INFER-019

refuse_unresolved_batch_grammars

std::optional< GenerationResult > entropic::ModelOrchestrator::refuse_unresolved_batch_grammars(const std::vector< GenerationParams > &params_list, const std::vector< std::string > &tiers, const std::string &lead, std::vector< GenerationParams > &out)

Resolve each batch arm's grammar, refusing the whole batch if any arm's tier grammar is unregistered (gh#154).

src/inference/orchestrator.cpp:2599

Show on the map →

Called by generate_batch

Calls batch_arm_tier, refuse_unresolved_tier_grammar

Source · 19 lines
ModelOrchestrator::refuse_unresolved_batch_grammars(
    const std::vector<GenerationParams>& params_list,
    const std::vector<std::string>& tiers,
    const std::string& lead,
    std::vector<GenerationParams>& out)
{
    out.clear();
    out.reserve(params_list.size());
    for (std::size_t i = 0; i < params_list.size(); ++i) {
        GenerationParams resolved = params_list[i];
        auto refusal = refuse_unresolved_tier_grammar(
            resolved, batch_arm_tier(tiers, i, lead));
        if (refusal.has_value()) {
            return refusal;
        }
        out.push_back(std::move(resolved));
    }
    return std::nullopt;
}
Activity · 9 steps
lines 2605–2605out.clear();lines 2606–2606out.reserve(params_list.size());lines 2607–2607◇ for (std::size_t i = 0; i < params_list.size(); ++i)lines 2608–2608GenerationParams resolved = params_list[i];lines 2609–2610auto refusal = refuse_unresolved_tier_grammar( resolved, batch_arm_tier(tiers, i, lead));lines 2611–2611◇ if (refusal.has_value())lines 2612–2612return refusal;lines 2614–2614out.push_back(std::move(resolved));lines 2616–2616return std::nullopt;

Requirements

REQ-INFER-007

refuse_unresolved_tier_grammar

std::optional< GenerationResult > entropic::ModelOrchestrator::refuse_unresolved_tier_grammar(GenerationParams &params, const std::string &tier_name)

Resolve this dispatch's grammar, refusing an unregistered TIER grammar before anything decodes (gh#154).

src/inference/orchestrator.cpp:2560

Source · 23 lines
ModelOrchestrator::refuse_unresolved_tier_grammar(
    GenerationParams& params, const std::string& tier_name)
{
    resolve_grammar_key(params, tier_name);          // v1.9.3
    if (!tier_grammar_unresolved(params)) {
        return std::nullopt;
    }

    GenerationResult err;
    err.finish_reason = "error";
    err.error_code = ENTROPIC_ERROR_GRAMMAR_NOT_FOUND;
    err.error_message =
        "Tier '" + tier_name + "' declares grammar '"
        + params.resolved_grammar_key + "' and no grammar is registered "
        "under that key. Register it with entropic_grammar_register_file() "
        "or entropic_grammar_register() before running this tier, or place "
        + params.resolved_grammar_key + ".gbnf in a grammar search path. "
        "Refused rather than decoded unconstrained (gh#154): an "
        "unconstrained decode is indistinguishable from a constrained one "
        "in the output.";
    logger->error("{}", err.error_message);
    return err;
}
Activity · 9 steps
lines 2563–2563resolve_grammar_key(params, tier_name);lines 2564–2564◇ if (!tier_grammar_unresolved(params))lines 2565–2565return std::nullopt;lines 2568–2568GenerationResult err;lines 2569–2569err.finish_reason = "error";lines 2570–2570err.error_code = ENTROPIC_ERROR_GRAMMAR_NOT_FOUND;lines 2571–2579err.error_message = "Tier '" + tier_name + "' declares grammar '" + params.resolved_grammar_key + "' and no grammar is registered " "under that key. Register it with entropic_grammar_register_file() " "or entropic_grammar_register() before running this tier, or place " + params.resolved_grammar_key + ".gbnf in a grammar search path. " "Refused rather than decoded unconstrained (gh#154): an " "unconstrained decode is indistinguishable from a constrained one " "in the output.";lines 2580–2580logger->error("{}", err.error_message);lines 2581–2581return err;

Requirements

REQ-INFER-007

release_backend

void entropic::ModelOrchestrator::release_backend(InferenceBackend *backend)

Unload one backend, keeping its adapter registrations (gh#164).

src/inference/orchestrator.cpp:1985

Show on the map →

Called by release_models

Calls announce_eviction, is_loaded, llama_context_ptr, llama_model_ptr, release_handles_for_model, unload

Source · 14 lines
void ModelOrchestrator::release_backend(InferenceBackend* backend) {
    if (backend == nullptr || !backend->is_loaded()) { return; }

    auto* llama_backend = dynamic_cast<LlamaCppBackend*>(backend);
    if (llama_backend != nullptr) {
        // KEEPS the registrations, unlike the swap path's
        // `unload_all_for_model` — see AdapterManager (gh#164).
        lora_manager_.release_handles_for_model(
            llama_backend->llama_model_ptr(),
            llama_backend->llama_context_ptr());
    }
    backend->unload();
    announce_eviction(backend);
}
Activity · 7 steps
lines 1986–1986◇ if (backend == nullptr || !backend->is_loaded())lines 1986–1986return;lines 1988–1988auto* llama_backend = dynamic_cast<LlamaCppBackend*>(backend);lines 1989–1989◇ if (llama_backend != nullptr)lines 1992–1994lora_manager_.release_handles_for_model( llama_backend->llama_model_ptr(), llama_backend->llama_context_ptr());lines 1996–1996backend->unload();lines 1997–1997announce_eviction(backend);

Requirements

REQ-INFER-019

release_models

entropic_error_t entropic::ModelOrchestrator::release_models(const std::string &tier_name)

Release resident model(s), keeping every registration (gh#164).

src/inference/orchestrator.cpp:1945

Show on the map →

Called by SCENARIO, entropic_release_model, release_reload_cycle

Calls release_backend, shutdown

Source · 27 lines
entropic_error_t ModelOrchestrator::release_models(
    const std::string& tier_name) {
    std::lock_guard<std::mutex> lock(swap_mutex_);

    if (!tier_name.empty()) {
        auto it = tiers_.find(tier_name);
        if (it == tiers_.end()) {
            logger->error("[residency] release: unknown tier '{}'",
                          tier_name);
            return ENTROPIC_ERROR_MODEL_NOT_FOUND;
        }
        release_backend(it->second.get());
        return ENTROPIC_OK;
    }

    std::unordered_set<const InferenceBackend*> seen;
    for (const auto& [name, backend] : tiers_) {
        (void)name;
        if (backend && seen.insert(backend.get()).second) {
            release_backend(backend.get());
        }
    }
    // Secondary roles (router, speculative draft). They re-ensure on the
    // next cold activation — see `activate_and_track`.
    secondary_loader_.shutdown();
    return ENTROPIC_OK;
}
Activity · 15 steps
lines 1947–1947std::lock_guard<std::mutex> lock(swap_mutex_);lines 1949–1949◇ if (!tier_name.empty())lines 1950–1950auto it = tiers_.find(tier_name);lines 1951–1951◇ if (it == tiers_.end())lines 1952–1953logger->error("[residency] release: unknown tier '{}'", tier_name);lines 1954–1954return ENTROPIC_ERROR_MODEL_NOT_FOUND;lines 1956–1956release_backend(it->second.get());lines 1957–1957return ENTROPIC_OK;lines 1960–1960std::unordered_set<const InferenceBackend*> seen;lines 1961–1961◇ for (const auto& [name, backend] : tiers_)lines 1962–1962(void)name;lines 1963–1963◇ if (backend && seen.insert(backend.get()).second)lines 1964–1964release_backend(backend.get());lines 1969–1969secondary_loader_.shutdown();lines 1970–1970return ENTROPIC_OK;

Requirements

REQ-INFER-019

residency_admits

bool entropic::ModelOrchestrator::residency_admits(const std::string &tier_name)

Run the VRAM-budget gate for a tier.

src/inference/orchestrator.cpp:1613

Source · 28 lines
bool ModelOrchestrator::residency_admits(const std::string& tier_name) {
    // gh#198: a deferred handle measures here, on its first admission.
    ensure_vram_budget();
    // gh#148: resolve `gpu_layers: auto` and refuse a config that provably
    // cannot work, BEFORE pricing the footprint — both change what is being
    // priced, and both are loud rather than silently corrected.
    resolve_auto_gpu_layers(tier_name);
    if (!config_admits(tier_name)) { return false; }

    size_t footprint = estimate_footprint_bytes(tier_name);
    if (footprint > 0) {
        tier_footprint_bytes_[tier_name] = footprint;
    }
    if (vram_budget_bytes_ > 0 && footprint > vram_budget_bytes_) {
        logger->error("[residency] tier '{}' footprint {} bytes "
                      "exceeds VRAM budget {} bytes — "
                      "TIER_MODEL_TOO_LARGE (gh#57)",
                      tier_name, footprint, vram_budget_bytes_);
        // gh#142: a bare refusal leaves the operator with nothing to act on.
        // Say what WOULD fit, so the answer is a setting they can apply rather
        // than a wall. 0 means even an empty context does not fit, in which
        // case the context length is not the lever and saying so is honest.
        log_fit_recommendation(tier_name);
        last_residency_error_ = ENTROPIC_ERROR_TIER_MODEL_TOO_LARGE;
        return false;
    }
    return true;
}
Activity · 13 steps
lines 1615–1615ensure_vram_budget();lines 1619–1619resolve_auto_gpu_layers(tier_name);lines 1620–1620◇ if (!config_admits(tier_name))lines 1620–1620return false;lines 1622–1622size_t footprint = estimate_footprint_bytes(tier_name);lines 1623–1623◇ if (footprint > 0)lines 1624–1624tier_footprint_bytes_[tier_name] = footprint;lines 1626–1626◇ if (vram_budget_bytes_ > 0 && footprint > vram_budget_bytes_)lines 1627–1630logger->error("[residency] tier '{}' footprint {} bytes " "exceeds VRAM budget {} bytes — " "TIER_MODEL_TOO_LARGE (gh#57)", tier_name, footprint, vram_budget_bytes_);lines 1635–1635log_fit_recommendation(tier_name);lines 1636–1636last_residency_error_ = ENTROPIC_ERROR_TIER_MODEL_TOO_LARGE;lines 1637–1637return false;lines 1639–1639return true;

Requirements

REQ-INFER-019

resolve_and_stage

GenerationParams entropic::ModelOrchestrator::resolve_and_stage(InferenceBackend *model, const GenerationParams &params, const std::string &tier_name)

Apply tier sampler defaults + stage tools for a generate dispatch (gh#87).

src/inference/orchestrator.cpp:743

Source · 22 lines
GenerationParams ModelOrchestrator::resolve_and_stage(
    InferenceBackend* model,
    const GenerationParams& params,
    const std::string& tier_name) {
    GenerationParams resolved = params;
    apply_tier_sampler_defaults(resolved, tier_name);  // gh#82
    // gh#134 (v2.10.4): per-tier, never global — front-office tiers
    // legitimately answer in prose.
    bool require_tc = false;
    if (auto it = config_.models.tiers.find(tier_name);
        it != config_.models.tiers.end()) {
        require_tc = it->second.require_tool_call.value_or(false);
    }
    // v2.14.6: the engine forces the retry after a no-tool-call nudge.
    if (resolved.force_tool_call && !require_tc) {
        logger->info("[tools] tier '{}': tool call FORCED for this generation "
                     "(retry after a no-tool-call nudge)", tier_name);
    }
    require_tc = require_tc || resolved.force_tool_call;
    stage_active_tools(model, resolved, require_tc);   // gh#87 3b, gh#134
    return resolved;
}
Activity · 10 steps
lines 747–747GenerationParams resolved = params;lines 748–748apply_tier_sampler_defaults(resolved, tier_name);lines 751–751bool require_tc = false;lines 752–753◇ if (auto it = config_.models.tiers.find(tier_name); it != config_.models.tiers.end())lines 754–754require_tc = it->second.require_tool_call.value_or(false);lines 757–757◇ if (resolved.force_tool_call && !require_tc)lines 758–759logger->info("[tools] tier '{}': tool call FORCED for this generation " "(retry after a no-tool-call nudge)", tier_name);lines 761–761require_tc = require_tc || resolved.force_tool_call;lines 762–762stage_active_tools(model, resolved, require_tc);lines 763–763return resolved;

Requirements

REQ-INFER-009

resolve_auto_gpu_layers

void entropic::ModelOrchestrator::resolve_auto_gpu_layers(const std::string &tier_name)

Resolve gpu_layers: auto from measured free VRAM (gh#148).

src/inference/orchestrator.cpp:1378

Show on the map →

Called by residency_admits

Calls derive_tier_auto_placement, fall_back_to_weights_estimate, log_auto_placement, resident_draft_bytes

Source · 36 lines
void ModelOrchestrator::resolve_auto_gpu_layers(const std::string& tier_name) {
    auto it = config_.models.tiers.find(tier_name);
    if (it == config_.models.tiers.end() || !it->second.gpu_layers_auto) {
        return;
    }
    std::error_code ec;
    auto file_bytes = std::filesystem::file_size(it->second.path, ec);
    if (ec || vram_budget_bytes_ == 0) {
        logger->warn("[residency] tier '{}': gpu_layers=auto cannot be "
                     "resolved ({}) — keeping gpu_layers={}", tier_name,
                     ec ? "model file unreadable" : "free VRAM unknown",
                     it->second.gpu_layers);
        return;
    }

    // v2.13.1: read the model's actual shape instead of assuming 30 layers
    // and `file_bytes / 30` per layer. A metadata-only open costs the header
    // and the tensor index — no tensor data — regardless of file size.
    GgufShape shape;
    const AutoPlacement placement = derive_tier_auto_placement(
        it->second, static_cast<uint64_t>(file_bytes), vram_budget_bytes_,
        config_.vram_reserve_mb, resident_draft_bytes(), shape);
    if (!placement.known) {
        fall_back_to_weights_estimate(tier_name, file_bytes, placement.reason);
        return;
    }

    log_auto_placement(tier_name, shape, placement, file_bytes);
    it->second.gpu_layers = placement.gpu_layers;
    it->second.cpu_moe_layers = placement.cpu_moe_layers;
    // v2.13.2: only ever LOWERED, and only when that is what bought full
    // residency. 0 means auto did not touch it, so an operator's own value
    // is preserved unless it was the thing standing between them and the
    // whole model on the card.
    if (placement.n_ubatch > 0) { it->second.n_ubatch = placement.n_ubatch; }
}
Activity · 18 steps
lines 1379–1379auto it = config_.models.tiers.find(tier_name);lines 1380–1380◇ if (it == config_.models.tiers.end() || !it->second.gpu_layers_auto)lines 1381–1381return;lines 1383–1383std::error_code ec;lines 1384–1384auto file_bytes = std::filesystem::file_size(it->second.path, ec);lines 1385–1385◇ if (ec || vram_budget_bytes_ == 0)lines 1386–1389logger->warn("[residency] tier '{}': gpu_layers=auto cannot be " "resolved ({}) — keeping gpu_layers={}", tier_name, ec ? "model file unreadable" : "free VRAM unknown", it->second.gpu_layers);lines 1390–1390return;lines 1396–1396GgufShape shape;lines 1397–1399const AutoPlacement placement = derive_tier_auto_placement( it->second, static_cast<uint64_t>(file_bytes), vram_budget_bytes_, config_.vram_reserve_mb, resident_draft_bytes(), shape);lines 1400–1400◇ if (!placement.known)lines 1401–1401fall_back_to_weights_estimate(tier_name, file_bytes, placement.reason);lines 1402–1402return;lines 1405–1405log_auto_placement(tier_name, shape, placement, file_bytes);lines 1406–1406it->second.gpu_layers = placement.gpu_layers;lines 1407–1407it->second.cpu_moe_layers = placement.cpu_moe_layers;lines 1412–1412◇ if (placement.n_ubatch > 0)lines 1412–1412it->second.n_ubatch = placement.n_ubatch;

Requirements

REQ-INFER-019

resolve_grammar_key

void entropic::ModelOrchestrator::resolve_grammar_key(GenerationParams &params, const std::string &tier_name)

Resolve grammar_key to grammar content string.

src/inference/orchestrator.cpp:2491

Source · 45 lines
void ModelOrchestrator::resolve_grammar_key(
    GenerationParams& params, const std::string& tier_name)
{
    if (!params.grammar.empty()) {
        return;
    }

    // Try explicit grammar_key
    std::string key = params.grammar_key;

    // Fall back to tier config grammar field (frontmatter)
    if (key.empty()) {
        auto it = config_.models.tiers.find(tier_name);
        if (it != config_.models.tiers.end() && it->second.grammar) {
            key = normalize_grammar_key(it->second.grammar->string());
            // gh#154: remember WHERE the key came from. All three
            // request-side sources arrive as params.grammar, so without
            // this the result cannot say whether the tier asked or the
            // caller did.
            params.grammar_from_tier = true;
        }
    }

    if (key.empty()) {
        return;
    }

    // Recorded BEFORE the lookup, so a key that resolves to nothing is
    // still named on the result. A missing grammar leaves the decode
    // unconstrained (REQ-INFER-007) and the absence of a log line was,
    // until gh#154, the only signal that it had happened.
    params.resolved_grammar_key = key;

    std::string content = grammar_registry_.get(key);
    if (content.empty()) {
        logger->warn("Grammar key '{}' not found in registry — this decode "
                     "is UNCONSTRAINED; read generations[].grammar.resolved "
                     "from entropic_metrics_json to detect it", key);
        return;
    }

    logger->info("Grammar resolved: key='{}', {} bytes",
                 key, content.size());
    params.grammar = std::move(content);
}
Activity · 17 steps
lines 2494–2494◇ if (!params.grammar.empty())lines 2495–2495return;lines 2499–2499std::string key = params.grammar_key;lines 2502–2502◇ if (key.empty())lines 2503–2503auto it = config_.models.tiers.find(tier_name);lines 2504–2504◇ if (it != config_.models.tiers.end() && it->second.grammar)lines 2505–2505key = normalize_grammar_key(it->second.grammar->string());lines 2510–2510params.grammar_from_tier = true;lines 2514–2514◇ if (key.empty())lines 2515–2515return;lines 2522–2522params.resolved_grammar_key = key;lines 2524–2524std::string content = grammar_registry_.get(key);lines 2525–2525◇ if (content.empty())lines 2526–2528logger->warn("Grammar key '{}' not found in registry — this decode " "is UNCONSTRAINED; read generations[].grammar.resolved " "from entropic_metrics_json to detect it", key);lines 2529–2529return;lines 2532–2533logger->info("Grammar resolved: key='{}', {} bytes", key, content.size());lines 2534–2534params.grammar = std::move(content);

Requirements

REQ-INFER-007

resolve_mtp_effective

bool entropic::ModelOrchestrator::resolve_mtp_effective(const std::string &tier_name) const

Resolve whether MTP should be attempted for this tier+request (gh#108, v2.9.4): a tier's speculative_mtp override wins over the global speculative.mtp flag when set; the request-level grammar safety net (a dynamic params.grammar on an MTP-effective tier) is applied by the caller, not here.

src/inference/orchestrator.cpp:359

Show on the map →

Called by try_speculative_route_streaming

Calls none

Source · 7 lines
bool ModelOrchestrator::resolve_mtp_effective(const std::string& tier_name) const {
    auto it = config_.models.tiers.find(tier_name);
    if (it != config_.models.tiers.end() && it->second.speculative_mtp) {
        return *it->second.speculative_mtp;
    }
    return config_.inference.speculative.mtp;
}
Activity · 4 steps
lines 360–360auto it = config_.models.tiers.find(tier_name);lines 361–361◇ if (it != config_.models.tiers.end() && it->second.speculative_mtp)lines 362–362return *it->second.speculative_mtp;lines 364–364return config_.inference.speculative.mtp;

Requirements

REQ-INFER-015

resolve_vram_budget_bytes

size_t entropic::ModelOrchestrator::resolve_vram_budget_bytes()

Resolve the VRAM budget at initialize time.

src/inference/orchestrator.cpp:2720

Source · 22 lines
size_t ModelOrchestrator::resolve_vram_budget_bytes() {
    const char* env = std::getenv("ENTROPIC_VRAM_BUDGET_BYTES");
    if (env == nullptr) {
        // Not set at all: fall through to the device.
        return static_cast<size_t>(query_device_free_vram_bytes());
    }
    // SET, so it takes control — including when it is empty or unparseable,
    // which resolve to 0 and therefore DISABLE the gate. That is the escape
    // hatch for an operator who wants the pre-gh#142 behaviour back, and it is
    // what the v2.3.10 contract already specified; the device fallback must not
    // quietly override an explicit setting.
    size_t budget = 0;
    if (*env != '\0') {
        try {
            long long v = std::stoll(env);
            budget = (v < 0) ? 0 : static_cast<size_t>(v);
        } catch (...) {
            budget = 0;
        }
    }
    return budget;
}
Activity · 7 steps
lines 2721–2721const char* env = std::getenv("ENTROPIC_VRAM_BUDGET_BYTES");lines 2722–2722◇ if (env == nullptr)lines 2724–2724return static_cast<size_t>(query_device_free_vram_bytes());lines 2731–2731size_t budget = 0;lines 2732–2732◇ if (*env != '\0')lines 2733–2738try { long long v = std::stoll(env); budget = (v < 0) ? 0 : static_cast<size_t>(v); } catch (...) { budget = 0; }lines 2740–2740return budget;

Requirements

REQ-INFER-019

route

std::string entropic::ModelOrchestrator::route(const std::vector< Message > &messages)

Route to tier using router model.

src/inference/orchestrator.cpp:1164

Show on the map →

Called by SCENARIO, SCENARIO, SCENARIO, TEST_CASE, TEST_CASE, generate, generate_streaming, iface_route

Calls classify_task

Source · 21 lines
std::string ModelOrchestrator::route(const std::vector<Message>& messages) {
    if (!config_.routing.enabled
        || !config_.models.router.has_value()) {
        logger->info("Route: routing disabled, using default '{}'",
                     default_tier_);
        last_routing_result_ = {default_tier_, "", "", "none", 0.0};
        return default_tier_;
    }

    auto [tier, raw] = classify_task(messages);
    last_routing_result_ = {tier, loaded_main_tier_, raw, "none", 0.0};

    // Track history
    tier_history_.push_back(tier);
    if (tier_history_.size() > 5) {
        tier_history_.erase(tier_history_.begin());
    }

    logger->info("[ROUTER] {} | raw='{}'", tier, raw);
    return tier;
}
Activity · 11 steps
lines 1165–1166◇ if (!config_.routing.enabled || !config_.models.router.has_value())lines 1167–1168logger->info("Route: routing disabled, using default '{}'", default_tier_);lines 1169–1169last_routing_result_ = {default_tier_, "", "", "none", 0.0};lines 1170–1170return default_tier_;lines 1173–1173auto [tier, raw] = classify_task(messages);lines 1174–1174last_routing_result_ = {tier, loaded_main_tier_, raw, "none", 0.0};lines 1177–1177tier_history_.push_back(tier);lines 1178–1178◇ if (tier_history_.size() > 5)lines 1179–1179tier_history_.erase(tier_history_.begin());lines 1182–1182logger->info("[ROUTER] {} | raw='{}'", tier, raw);lines 1183–1183return tier;

Requirements

REQ-INFER-020

select_vision_tier

std::string entropic::ModelOrchestrator::select_vision_tier() const

Pick the canonical vision-capable tier name (gh#41).

src/inference/orchestrator.cpp:2280

Show on the map →

Called by SCENARIO

Calls has_capability

Source · 6 lines
std::string ModelOrchestrator::select_vision_tier() const {
    for (const auto& [name, tier] : config_.models.tiers) {
        if (tier.has_capability("vision")) { return name; }
    }
    return "";
}
Activity · 4 steps
lines 2281–2281◇ for (const auto& [name, tier] : config_.models.tiers)lines 2282–2282◇ if (tier.has_capability("vision"))lines 2282–2282return name;lines 2284–2284return "";

Requirements

REQ-INFER-025

shutdown

void entropic::ModelOrchestrator::shutdown()

Shutdown — unload all models.

src/inference/orchestrator.cpp:317

Show on the map →

Called by SCENARIO, SCENARIO, SCENARIO, TEST_CASE, TEST_CASE, TEST_CASE, TEST_CASE, release_reload_cycle, ~ModelOrchestrator

Tested by

2 teststestRunEnded, testRunEnded

Calls shutdown

Source · 11 lines
void ModelOrchestrator::shutdown() {
    logger->info("Shutting down model orchestrator");

    for (auto& [path, backend] : model_pool_) {
        if (backend->is_loaded()) {
            backend->unload();
        }
    }

    secondary_loader_.shutdown();
}
Activity · 5 steps
lines 318–318logger->info("Shutting down model orchestrator");lines 320–320◇ for (auto& [path, backend] : model_pool_)lines 321–321◇ if (backend->is_loaded())lines 322–322backend->unload();lines 326–326secondary_loader_.shutdown();

Requirements

REQ-INFER-002 REQ-INFER-020

stage_active_tools

static void entropic::stage_active_tools(InferenceBackend *model, const GenerationParams &params, bool require_tool_call)

Stage the turn's tool defs on the backend for common_chat (gh#87).

src/inference/orchestrator.cpp:577

Source · 8 lines
static void stage_active_tools(InferenceBackend* model,
                               const GenerationParams& params,
                               bool require_tool_call) {
    if (auto* llama = dynamic_cast<LlamaCppBackend*>(model)) {
        llama->set_active_tools(params.tools);
        llama->set_require_tool_call(require_tool_call);  // gh#134 (v2.10.4)
    }
}
Activity · 3 steps
lines 580–580◇ if (auto* llama = dynamic_cast<LlamaCppBackend*>(model))lines 581–581llama->set_active_tools(params.tools);lines 582–582llama->set_require_tool_call(require_tool_call);

Requirements

REQ-INFER-009

tier_declares_vision

bool entropic::ModelOrchestrator::tier_declares_vision(const std::string &tier_name) const

Whether a tier is configured for vision, per CONFIG (gh#157).

src/inference/orchestrator.cpp:2037

Show on the map →

Called by SCENARIO, entropic_model_has_vision

Calls has_capability

Source · 7 lines
bool ModelOrchestrator::tier_declares_vision(
    const std::string& tier_name) const {
    auto it = config_.models.tiers.find(tier_name);
    if (it == config_.models.tiers.end()) { return false; }
    return it->second.has_capability("vision")
        || !it->second.mmproj_path.empty();
}
Activity · 4 steps
lines 2039–2039auto it = config_.models.tiers.find(tier_name);lines 2040–2040◇ if (it == config_.models.tiers.end())lines 2040–2040return false;lines 2041–2042return it->second.has_capability("vision") || !it->second.mmproj_path.empty();

Requirements

REQ-INFER-025

try_mtp_route

bool entropic::ModelOrchestrator::try_mtp_route(InferenceBackend *model, const std::vector< Message > &messages, const GenerationParams &params, std::function< void(std::string_view)> on_token, std::atomic< bool > &cancel, GenerationResult &result)

Route a generate call through the target-owned MTP kernel (gh#106).

src/inference/orchestrator.cpp:411

Show on the map →

Called by try_speculative_route_streaming

Calls generate_mtp

Source · 25 lines
bool ModelOrchestrator::try_mtp_route(
    InferenceBackend* model,
    const std::vector<Message>& messages,
    const GenerationParams& params,
    std::function<void(std::string_view)> on_token,
    std::atomic<bool>& cancel,
    GenerationResult& result)
{
    auto* llama_target = dynamic_cast<LlamaCppBackend*>(model);
    if (llama_target == nullptr) {
        // Fail loud — no silent plain-decode fallback (gh#108).
        result = GenerationResult{};
        result.error_code = ENTROPIC_ERROR_NOT_SUPPORTED;
        result.error_message = "speculative.mtp enabled but the target backend "
                               "is not llama.cpp; disable speculative.mtp";
        result.finish_reason = "error";
        logger->error("{}", result.error_message);
    } else {
        result = llama_target->generate_mtp(
            messages, params, on_token, cancel,
            config_.inference.speculative.draft.path.string(),
            config_.inference.speculative.n_draft);
    }
    return true;  // MTP owns the outcome — never fall back to plain decode
}
Activity · 10 steps
lines 419–419auto* llama_target = dynamic_cast<LlamaCppBackend*>(model);lines 420–420◇ if (llama_target == nullptr)lines 422–422result = GenerationResult{};lines 423–423result.error_code = ENTROPIC_ERROR_NOT_SUPPORTED;lines 424–425result.error_message = "speculative.mtp enabled but the target backend " "is not llama.cpp; disable speculative.mtp";lines 426–426result.finish_reason = "error";lines 427–427logger->error("{}", result.error_message);lines 428–428elselines 429–432result = llama_target->generate_mtp( messages, params, on_token, cancel, config_.inference.speculative.draft.path.string(), config_.inference.speculative.n_draft);lines 434–434return true;

Requirements

REQ-INFER-015

warn_if_content_vanished

static void entropic::warn_if_content_vanished(const GenerationResult &result)

Explain a turn that produced tokens but delivered no content (gh#137).

src/inference/orchestrator.cpp:643

Source · 13 lines
static void warn_if_content_vanished(const GenerationResult& result) {
    const auto cause = diagnose_empty_content(
        result.content.empty(), !result.raw_content.empty(),
        result.finish_reason, !result.tool_calls.empty());
    if (cause == EmptyContentCause::not_empty) { return; }
    if (cause == EmptyContentCause::tool_call_only) {
        logger->info("Turn delivered {} tool call(s) and no prose. {}",
                     result.tool_calls.size(), explain_empty_content(cause));
        return;
    }
    logger->warn("Turn produced {} raw chars but delivered no content. {}",
                 result.raw_content.size(), explain_empty_content(cause));
}
Activity · 7 steps
lines 644–646const auto cause = diagnose_empty_content( result.content.empty(), !result.raw_content.empty(), result.finish_reason, !result.tool_calls.empty());lines 647–647◇ if (cause == EmptyContentCause::not_empty)lines 647–647return;lines 648–648◇ if (cause == EmptyContentCause::tool_call_only)lines 649–650logger->info("Turn delivered {} tool call(s) and no prose. {}", result.tool_calls.size(), explain_empty_content(cause));lines 651–651return;lines 653–654logger->warn("Turn produced {} raw chars but delivered no content. {}", result.raw_content.size(), explain_empty_content(cause));

Requirements

REQ-INFER-010

warn_turn_diagnostics

static void entropic::warn_turn_diagnostics(const GenerationResult &result, const std::string &tier_name, const std::unordered_map< std::string, TierConfig > &tiers)

Report every post-turn diagnostic from one call site (gh#137).

src/inference/orchestrator.cpp:711

Show on the map →

Called by finish_generation, generate_streaming

Calls warn_if_budget_starved_required_turn, warn_if_content_vanished

Source · 7 lines
static void warn_turn_diagnostics(
    const GenerationResult& result,
    const std::string& tier_name,
    const std::unordered_map<std::string, TierConfig>& tiers) {
    warn_if_content_vanished(result);
    warn_if_budget_starved_required_turn(result, tier_name, tiers);
}
Activity · 2 steps
lines 715–715warn_if_content_vanished(result);lines 716–716warn_if_budget_starved_required_turn(result, tier_name, tiers);

Requirements

REQ-INFER-010

~ModelOrchestrator

entropic::ModelOrchestrator::~ModelOrchestrator()

Destructor — invokes shutdown() and AdapterManager::unload_all() .

src/inference/orchestrator.cpp:339

The index is older than this file: the lines it records no longer hold this function. Refresh the index to bundle its body.

Requirements

REQ-INFER-002