Entropic — C++ Architecture Design¶
Reference architecture for the C++ engine. This document defines the library decomposition, dependency graph, interface contracts, class hierarchy patterns, plugin architecture, and build configuration that constrain feature work.
Status: living design document. The original C++ rewrite from the v1.7.x Python prototype completed at v2.0.0; this file now guides v2.x evolution. Port-era notes referencing the Python behavioral spec have been retained where they document a decision (so the rationale stays visible) but no longer describe in-flight work.
Library Decomposition¶
The engine is a set of shared libraries with explicit dependency boundaries and explicit interface contracts. Each library has a single responsibility. Arrows in the dependency graph point down only — no circular dependencies.
┌─────────────────┐
│ librentropic │ Facade — unified C API
│ (.so) │ (entropic.h)
└───────┬─────────┘
│ links all
┌──────────┬─────────┼──────────┬──────────┐
▼ ▼ ▼ ▼ ▼
┌──────────┐ ┌──────┐ ┌───────┐ ┌──────┐ ┌────────┐
│inference │ │ mcp │ │ core │ │config│ │storage │
│ (.so) │ │(.so) │ │ (.so) │ │(.so) │ │ (.so) │
└────┬─────┘ └──┬───┘ └───┬───┘ └──┬───┘ └───┬────┘
│ │ │ │ │
│ │ ┌────┴────┐ │ │
│ │ │ types │ │ │
│ │ │ (.so) │ │ │
│ │ └─────────┘ │ │
▼ ▼ ▼ ▼
llama.cpp nlohmann/json ryml sqlite3
cpp-httplib spdlog
librentropic-types.so¶
Pure types with zero logic. The universal dependency that every other library links against. Established in v1.8.0.
Message, ToolCall, Directive, GenerationResult
Config structs (ModelConfig, TierConfig, etc.)
Enums (ModelState, AgentState, DirectiveType)
Error types (
entropic_error_t,entropic_last_error(),entropic_error_callback_t)
Message C Representation¶
Messages are JSON strings at .so boundaries, C++ structs internally.
The JSON wire format:
{"role": "user", "content": "...", "metadata": {"source": "user"}, "tool_calls": []}
Within a single .so, messages use the C++ Message struct. Cross-boundary
APIs accept and return const char* messages_json (JSON array of message
objects). Metadata is an arbitrary JSON object — no fixed schema enforced
at the type level.
librentropic-core.so¶
Engine loop, state machine, context management, delegation, directive processing. The operational heart of the engine.
Links: librentropic-types
Zero dependencies on inference, MCP, storage, or config. Communicates with other libraries exclusively through interface contracts.
librentropic-inference-{cuda,vulkan,cpu}.so¶
Inference backend implementations. Each is a separate build of the same source with different compile flags (except AXCL which is different source).
Links: librentropic-types, llama.cpp
Implements: IInferenceBackend interface contract.
librentropic-mcp.so¶
Server base class, tool registry, tool executor, permission manager, transport layer (stdio/SSE for external servers).
Links: librentropic-types, nlohmann/json, cpp-httplib
Implements: IMCPServer interface contract.
librentropic-mcp-{filesystem,bash,git,diagnostics,web,entropic}.so¶
Individual MCP server plugins. Each is a standalone .so loaded at runtime.
A consumer ships only the servers they need.
Links: librentropic-mcp (for MCPServer base class)
Implements: entropic_create_server() factory export.
librentropic-config.so¶
YAML config loader, schema validation, prompt manager, identity/constitution loading, bundled models registry.
Links: librentropic-types, ryml
Implements: IConfigLoader interface contract.
librentropic-storage.so¶
SQLite conversation persistence, session log files, audit log.
Links: librentropic-types, sqlite3, spdlog
Implements: IStorageBackend interface contract.
Note on spdlog: All libraries use spdlog for structured logging (established
in v1.8.0). spdlog is listed under storage in the dependency graph for
simplicity, but it is a universal development dependency linked by every .so
that needs logging.
librentropic.so (Facade)¶
Thin layer linking all libraries. Exposes entropic.h — the unified C API
that most consumers link against.
Interface Contracts¶
Each .so boundary is governed by an explicit interface header in
include/entropic/interfaces/. These are pure C at the plugin boundary.
C++ interfaces are used ONLY within a single compilation unit / library.
The Rule¶
All cross-.so communication uses C types only. No std::string,
std::vector, std::optional, or C++ vtables cross a shared library
boundary. Factory functions return opaque handles. Method calls go through
the C API or through C function pointers.
This prevents ABI incompatibility between different compilers, standard library versions, or C++ standard revisions.
Contract Headers¶
include/entropic/
├── interfaces/ Contract headers (.so API surface)
│ ├── i_inference_backend.h Pure C factory + handle interface
│ ├── i_mcp_server.h Pure C factory + handle interface
│ ├── i_storage_backend.h Pure C factory + handle interface
│ ├── i_config_loader.h Pure C factory + handle interface
│ ├── i_hook_handler.h C function pointer callback types
│ └── i_inference_callbacks.h Function pointer typedefs (core→inference)
├── types/ Shared types (librentropic-types.so)
│ ├── message.h Messages + metadata
│ ├── tool_call.h Tool call + result types
│ ├── directive.h Directive types + wire format
│ ├── generation_result.h Generation output + metrics
│ ├── error.h Error enum + callback types
│ ├── config.h Config structs (ModelConfig, TierConfig, etc.)
│ ├── engine_types.h LoopConfig, LoopContext, AgentState, Metrics
│ ├── generation.h GenerationParams, ResourceProfile
│ ├── identity.h IdentityConfig, PhaseConfig
│ ├── hooks.h Hook point enum, callback types
│ ├── audit.h AuditEntry, AuditLogConfig (v1.9.5)
│ └── validation.h CritiqueResult, Violation (v1.9.8)
├── core/ Engine internals (librentropic-core.so)
├── inference/ Backend impl (inference .so internal)
├── mcp/ MCP impl (mcp .so internal)
└── entropic.h Public C API facade
Plugin ABI Versioning¶
Every plugin .so must export an API version function:
extern "C" int entropic_plugin_api_version();
The loader checks this before calling the factory. If the version doesn’t match the engine’s expected version, the plugin is rejected with a clear error message. New interface capabilities are added via new version numbers, not by modifying existing interfaces.
Symbol Visibility¶
All .so files use explicit symbol visibility. Only factory functions
and the C API are exported. Everything else is hidden.
#if defined(_WIN32)
#define ENTROPIC_EXPORT __declspec(dllexport)
#else
#define ENTROPIC_EXPORT __attribute__((visibility("default")))
#endif
Applied only to:
Factory functions (
entropic_create_server,entropic_create_inference_backend)C API functions in
entropic.hentropic_plugin_api_version()
No Third-Party Headers in Interfaces¶
Interface headers must not include third-party library headers. The json
type from nlohmann/json, YAML::Node from ryml, etc. are implementation
details that do not appear in any header under interfaces/ or types/.
Cross-boundary data uses C types: const char*, size_t, opaque handles.
Example: Plugin C Interface¶
// include/entropic/interfaces/i_mcp_server.h
#pragma once
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
/// @brief Opaque handle to an MCP server instance.
typedef struct entropic_mcp_server* entropic_mcp_server_t;
/// @brief Get the server name.
/// @param server Server handle.
/// @return Null-terminated server name string. Owned by the server.
const char* entropic_mcp_server_name(entropic_mcp_server_t server);
/// @brief List tools as JSON array string.
/// @param server Server handle.
/// @return JSON string of tool definitions. Caller must free with entropic_free().
char* entropic_mcp_server_list_tools(entropic_mcp_server_t server);
/// @brief Execute a tool.
/// @param server Server handle.
/// @param tool_name Tool name (without server prefix).
/// @param args_json JSON string of arguments.
/// @return JSON string of ServerResponse. Caller must free with entropic_free().
///
/// Return format (ServerResponse JSON envelope):
/// @code
/// {
/// "result": "Human-readable result text",
/// "directives": [
/// {"type": "delegate", "target": "eng", "task": "..."},
/// {"type": "stop_processing"}
/// ]
/// }
/// @endcode
///
/// If the tool has no directives, the "directives" array is empty.
/// The engine parses directives from this JSON and dispatches them
/// through the DirectiveProcessor. This is the wire format for
/// tool-to-engine communication across .so boundaries.
char* entropic_mcp_server_execute(
entropic_mcp_server_t server,
const char* tool_name,
const char* args_json);
/// @brief Destroy a server instance.
/// @param server Server handle to destroy.
void entropic_mcp_server_destroy(entropic_mcp_server_t server);
/// @brief Free a string allocated by the server.
/// @param ptr Pointer returned by list_tools or execute.
void entropic_free(void* ptr);
#ifdef __cplusplus
}
#endif
// ── Plugin export requirements ──────────────────────────
// Every MCP server .so must export these two C functions:
//
// extern "C" ENTROPIC_EXPORT int entropic_plugin_api_version();
// extern "C" ENTROPIC_EXPORT entropic_mcp_server_t entropic_create_server();
Inside the .so, the implementation wraps the C handle around the C++ object:
// Inside librentropic-mcp-filesystem.so
#include <entropic/mcp/server_base.h>
#include <entropic/interfaces/i_mcp_server.h>
class FilesystemServer : public entropic::MCPServer { /* C++ internals */ };
extern "C" ENTROPIC_EXPORT int entropic_plugin_api_version() { return 1; }
extern "C" ENTROPIC_EXPORT entropic_mcp_server_t entropic_create_server() {
return reinterpret_cast<entropic_mcp_server_t>(new FilesystemServer());
}
Error Handling Contract¶
Exceptions must NOT cross .so boundaries. All cross-boundary error
reporting uses one of:
Return codes — C API functions return
entropic_error_tenum.Error callbacks — consumer registers a callback for async errors.
Error state on handles —
entropic_last_error(handle)returns the last error message string.
typedef enum {
ENTROPIC_OK = 0,
ENTROPIC_ERROR_INVALID_CONFIG,
ENTROPIC_ERROR_MODEL_NOT_FOUND,
ENTROPIC_ERROR_LOAD_FAILED,
ENTROPIC_ERROR_GENERATE_FAILED,
ENTROPIC_ERROR_TOOL_NOT_FOUND,
ENTROPIC_ERROR_PERMISSION_DENIED,
ENTROPIC_ERROR_PLUGIN_VERSION_MISMATCH,
} entropic_error_t;
/// @brief Get the last error message for a handle.
/// @return Null-terminated string. Owned by the handle, valid until next call.
const char* entropic_last_error(entropic_handle_t handle);
/// @brief Error callback type for async error reporting.
typedef void (*entropic_error_callback_t)(
entropic_error_t code,
const char* message,
void* user_data);
Within a single .so, C++ exceptions are used normally. They are caught
at the .so boundary and converted to error codes/callbacks.
Inference Backend¶
Core Interface (C boundary)¶
// include/entropic/interfaces/i_inference_backend.h
typedef struct entropic_inference_backend* entropic_inference_backend_t;
entropic_error_t entropic_inference_load(
entropic_inference_backend_t backend,
const char* config_json);
entropic_error_t entropic_inference_activate(
entropic_inference_backend_t backend);
entropic_error_t entropic_inference_generate(
entropic_inference_backend_t backend,
const char* messages_json,
const char* params_json,
char** result_json);
entropic_error_t entropic_inference_generate_streaming(
entropic_inference_backend_t backend,
const char* messages_json,
const char* params_json,
void (*on_token)(const char* token, size_t len, void* user_data),
void* user_data,
int* cancel_flag);
/// @brief Raw text completion without chat template.
/// @param backend Backend handle.
/// @param prompt Raw prompt string (no chat formatting applied).
/// @param params_json Generation parameters as JSON.
/// @param result_json Output: JSON result string. Caller must free.
/// @return ENTROPIC_OK on success.
///
/// Used by the router for digit-based classification. Distinct from
/// generate() which applies chat templates. The prompt is passed
/// directly to the model without any template formatting.
entropic_error_t entropic_inference_complete(
entropic_inference_backend_t backend,
const char* prompt,
const char* params_json,
char** result_json);
Internal C++ Implementation (within the .so)¶
// include/entropic/inference/backend.h
// Internal to inference .so — not exposed across boundaries
namespace entropic {
class InferenceBackend {
public:
bool load(const ModelConfig& config);
bool activate();
void deactivate();
void unload();
GenerationResult generate(
const std::vector<Message>& messages,
const GenerationParams& params);
GenerationResult generate_streaming(
const std::vector<Message>& messages,
const GenerationParams& params,
std::function<void(std::string_view token)> on_token,
std::atomic<bool>& cancel);
/// @brief Raw text completion without chat template.
/// Used by the router for digit-based classification.
GenerationResult complete(
const std::string& prompt,
const GenerationParams& params);
ModelState state() const { return state_.load(); }
protected:
virtual bool do_load(const ModelConfig& config) = 0;
virtual bool do_activate() = 0;
virtual void do_deactivate() = 0;
virtual void do_unload() = 0;
virtual GenerationResult do_generate(
const std::vector<Message>& messages,
const GenerationParams& params) = 0;
virtual GenerationResult do_generate_streaming(
const std::vector<Message>& messages,
const GenerationParams& params,
std::function<void(std::string_view token)> on_token,
std::atomic<bool>& cancel) = 0;
virtual GenerationResult do_complete(
const std::string& prompt,
const GenerationParams& params) = 0;
private:
std::atomic<ModelState> state_{ModelState::COLD};
std::filesystem::path model_path_;
std::mutex transition_mutex_; // Guards state TRANSITIONS only
Metrics metrics_;
};
} // namespace entropic
Key differences from earlier design:
state_isstd::atomic— lock-free readstransition_mutex_guards transitions, not queries or generationgenerate_streaming()is a first-class method, not a hook bolted on latercancelisstd::atomic<bool>&— consumer can abort mid-generationC boundary uses raw function pointer for streaming callback (no vtable)
Build Matrix¶
CMake Flag Output
──────────────────────────────────────────────
-DENTROPIC_CUDA=ON librentropic-inference-cuda.so
-DENTROPIC_VULKAN=ON librentropic-inference-vulkan.so
-DENTROPIC_CPU_ONLY=ON librentropic-inference-cpu.so
-DENTROPIC_AXCL=ON librentropic-inference-axcl.so
Runtime Detection¶
entropic_compute_backend_t entropic_detect_backend();
entropic_inference_backend_t entropic_load_inference_backend(
entropic_compute_backend_t backend);
Auto detection order: CUDA → Vulkan → CPU.
User override via config: inference.backend: cuda | vulkan | cpu | auto
When CONFIG_ENTROPIC_CPU_ONLY is set at compile time, detection is
compiled out entirely — detect_backend() returns CPU unconditionally.
Distribution¶
Channel |
Inference .so included |
|---|---|
PyPI wheel |
CUDA + CPU (detect at runtime) |
apt/deb |
Separate packages per backend |
Source build |
User picks via CMake flag |
MCP Server Plugins¶
Built-in MCP servers compile into individual .so files. Third-party
servers use the same plugin interface. A consumer ships only the servers
they need.
librentropic-mcp.so Base + registry + executor + permissions
librentropic-mcp-filesystem.so Filesystem server
librentropic-mcp-bash.so Bash server
librentropic-mcp-git.so Git server
librentropic-mcp-diagnostics.so Diagnostics + LSP client
librentropic-mcp-web.so Web search + fetch
librentropic-mcp-entropic.so Internal tools (todo, delegate, etc.)
Permissions¶
The permission model ships WITH the tool system (not later). Default-deny for all tools. The consumer’s runtime config defines the allow list. Per-identity granularity is added later (v1.9.4) but the enforcement point exists from day one.
Plugin Loading¶
entropic_mcp_server_t entropic_load_mcp_plugin(const char* so_path);
The server manager discovers .so files in a plugin directory. Each must
export entropic_plugin_api_version() and entropic_create_server().
Version mismatch → rejected with ENTROPIC_ERROR_PLUGIN_VERSION_MISMATCH.
Compile-Time Configuration¶
Feature selection at compile time via CMake options. All options are
abstracted through a generated entropic_config.h so the configuration
frontend can be swapped (CMake presets today, Kconfig or menuconfig later)
without changing any source code.
Configuration Flow¶
CMakeLists.txt Reads CMake options
│
▼
entropic_config.h.in Template with @CONFIG_*@ placeholders
│
▼
entropic_config.h (generated) #define CONFIG_ENTROPIC_* values
│
▼
Source code #ifdef CONFIG_ENTROPIC_* guards
Source code ONLY reads #define from entropic_config.h. It never checks
CMake variables directly. This makes the configuration frontend-agnostic.
CMake Options¶
# Build type
option(ENTROPIC_SHARED "Build shared libraries (.so)" ON)
option(ENTROPIC_STATIC "Build static library (.a)" OFF)
# Inference backend
option(ENTROPIC_CUDA "Build CUDA inference backend" ON)
option(ENTROPIC_VULKAN "Build Vulkan inference backend" OFF)
option(ENTROPIC_CPU_ONLY "Build CPU-only inference backend" OFF)
# MCP servers (each is an individual .so or compiled-in for static)
option(ENTROPIC_MCP_FILESYSTEM "Include filesystem MCP server" ON)
option(ENTROPIC_MCP_BASH "Include bash MCP server" ON)
option(ENTROPIC_MCP_GIT "Include git MCP server" ON)
option(ENTROPIC_MCP_DIAGNOSTICS "Include diagnostics MCP server" ON)
option(ENTROPIC_MCP_WEB "Include web MCP server" ON)
option(ENTROPIC_MCP_ENTROPIC "Include entropic MCP server" ON)
# Storage
option(ENTROPIC_STORAGE_SQLITE "Include SQLite storage backend" ON)
# Features
option(ENTROPIC_STREAMING "Include streaming generation API" ON)
Static Build¶
When ENTROPIC_STATIC=ON, the build produces a single librentropic.a.
Plugin loading via dlopen is replaced by a compile-time registry:
// Generated by CMake based on enabled MCP servers
// entropic_static_plugins.cpp
#include <entropic/mcp/server_loader.h>
extern entropic_mcp_server_t entropic_create_filesystem_server();
extern entropic_mcp_server_t entropic_create_bash_server();
// ... only servers enabled in config
static const entropic_plugin_entry_t static_plugins[] = {
{"filesystem", entropic_create_filesystem_server},
{"bash", entropic_create_bash_server},
{nullptr, nullptr} // sentinel
};
const entropic_plugin_entry_t* entropic_get_static_plugins() {
return static_plugins;
}
The server manager checks for static plugins first, falls back to dlopen
discovery only when ENTROPIC_SHARED=ON.
CMake Presets¶
// CMakePresets.json
{
"configurePresets": [
{
"name": "full",
"description": "Full featured CUDA build (TUI developer)",
"cacheVariables": {
"ENTROPIC_CUDA": "ON",
"ENTROPIC_SHARED": "ON"
}
},
{
"name": "minimal-static",
"description": "Minimal static build (embedded consumer)",
"cacheVariables": {
"ENTROPIC_STATIC": "ON",
"ENTROPIC_CPU_ONLY": "ON",
"ENTROPIC_MCP_BASH": "OFF",
"ENTROPIC_MCP_GIT": "OFF",
"ENTROPIC_MCP_WEB": "OFF",
"ENTROPIC_MCP_DIAGNOSTICS": "OFF",
"ENTROPIC_STORAGE_SQLITE": "OFF"
}
},
{
"name": "game",
"description": "Game engine integration (CUDA, minimal servers)",
"cacheVariables": {
"ENTROPIC_CUDA": "ON",
"ENTROPIC_SHARED": "ON",
"ENTROPIC_MCP_BASH": "OFF",
"ENTROPIC_MCP_GIT": "OFF",
"ENTROPIC_MCP_WEB": "OFF"
}
}
]
}
Class Hierarchy Patterns¶
Three-Layer Architecture¶
Every subsystem follows: interface (C contract) → concrete base (80% logic) → implementation (20% specifics).
C interface (i_inference_backend.h) Opaque handle + C functions
└─ InferenceBackend (backend.h) 80% logic: lifecycle, locking, metrics
└─ LlamaCppBackend 20% override: load, generate, stream
C interface (i_mcp_server.h) Opaque handle + C functions
└─ MCPServer (server_base.h) 80% logic: dispatch, permissions
└─ FilesystemServer 20% override: tool handlers
ChatAdapter (adapter_base.h) 80% logic: prompt assembly, think-blocks
└─ Qwen35Adapter 20% override: tool parsing, tags
The C interface is the .so boundary. The C++ classes are internal to
each .so — they never appear in public headers or cross library boundaries.
Config Schema Pattern¶
Structs with defaults + separate validation functions. No metaclass magic. Validation is explicit and testable.
YAML everywhere — config files AND identity frontmatter use YAML,
parsed by ryml (single-header amalgamation via ryml_all.hpp). The
validation layer is built in-house, replacing Pydantic’s cross-field
validators with explicit validate() functions per config struct.
Config resolution order (highest wins):
Compiled defaults (struct initializers)
Global config (
~/.entropic/config.yaml)Project config (
.entropic/config.local.yaml)Environment variables (
ENTROPIC_*)
Bundled data file discovery:
Compile-time
ENTROPIC_DATA_DIRdefine (set by CMake to install path)Overridable at runtime via
config_dirfield in config YAMLUsed for: identity prompts, tool JSONs, grammars,
bundled_models.yaml
/// @brief Model configuration for a single tier.
struct ModelConfig {
std::filesystem::path path; ///< Resolved model path
std::string adapter = "qwen35"; ///< Adapter name
int context_length = 16384; ///< Context window (512–131072)
int gpu_layers = -1; ///< GPU layers (-1 = all)
bool keep_warm = false; ///< Stay WARM on swap-out (NOT startup)
bool use_mlock = true; ///< Lock model in RAM
int cpu_moe_layers = 0; ///< EXPERIMENTAL: layers whose ROUTED
///< EXPERT tensors go to the host
///< (0 = off; see decision #75)
int reasoning_budget = -1; ///< Think token budget (-1 = unlimited)
std::string cache_type_k = "f16"; ///< KV cache key quantization
std::string cache_type_v = "f16"; ///< KV cache value quantization
int n_batch = 512; ///< Batch size for prompt processing
int n_threads = 0; ///< CPU threads (0 = auto)
std::string tensor_split = ""; ///< Multi-GPU tensor split ratios
bool flash_attn = true; ///< Flash attention
std::optional<std::vector<std::string>> allowed_tools; ///< Tool filter
};
/// @brief Validate and transform config.
/// @return Empty string on success, error message on failure.
std::string validate(ModelConfig& config, const BundledModels& registry);
Test Infrastructure¶
Doxygen Standard¶
Code comments ARE the documentation. docs/ holds roadmap, diagrams,
and architecture visuals only. Every public symbol gets a Doxygen block.
Required Elements¶
Element |
Doxygen tags |
|---|---|
Class |
|
Public method |
|
Struct fields |
|
Enum values |
|
File |
|
Interface |
|
External Dependencies¶
Library |
Purpose |
Type |
Cross-platform |
Notes |
|---|---|---|---|---|
llama.cpp |
Inference |
Submodule |
Linux/Mac/Win |
Direct C API |
nlohmann/json |
JSON parse/emit |
Header-only |
Yes |
MIT, de facto standard |
ryml |
YAML config + frontmatter |
Header-only (amalgamation) |
Yes |
|
sqlite3 |
Conversation storage |
System lib |
Yes |
Universal |
spdlog |
Structured logging |
Header-only |
Yes |
|
cpp-httplib |
HTTP/SSE (ext MCP) |
Header-only |
Yes |
|
Test framework |
Unit/integration |
Header-only |
Yes |
Selected in v1.8.0 (Catch2 or GoogleTest, BDD-style preferred) |
No third-party headers appear in interface contracts or types headers.
Dependencies are implementation details of their respective .so files.
Project Structure¶
entropic/
├── CMakeLists.txt
├── CMakePresets.json
├── include/
│ └── entropic/
│ ├── entropic.h Public C API
│ ├── entropic_config.h.in Build config template
│ ├── entropic_export.h ENTROPIC_EXPORT macro
│ ├── interfaces/ C contract headers
│ │ ├── i_inference_backend.h
│ │ ├── i_mcp_server.h
│ │ ├── i_storage_backend.h
│ │ ├── i_config_loader.h
│ │ └── i_hook_handler.h
│ ├── types/ Shared types
│ │ ├── message.h
│ │ ├── tool_call.h
│ │ ├── directive.h
│ │ ├── generation_result.h
│ │ ├── error.h
│ │ └── config.h
│ ├── core/
│ │ ├── engine.h
│ │ ├── context.h
│ │ ├── delegation.h
│ │ └── directives.h
│ ├── inference/
│ │ ├── backend.h
│ │ ├── backend_loader.h
│ │ ├── orchestrator.h
│ │ └── adapters/
│ │ ├── adapter_base.h
│ │ └── qwen35.h
│ ├── mcp/
│ │ ├── server_base.h
│ │ ├── server_loader.h
│ │ ├── tool_registry.h
│ │ └── servers/
│ │ ├── filesystem.h
│ │ ├── bash.h
│ │ └── ...
│ ├── config/
│ │ ├── schema.h
│ │ └── loader.h
│ ├── prompts/
│ │ └── manager.h
│ └── storage/
│ ├── backend.h
│ └── logger.h
├── src/
│ ├── core/
│ ├── inference/
│ ├── mcp/
│ ├── config/
│ ├── prompts/
│ ├── storage/
│ └── facade/ C API wrappers (entropic.h implementations)
├── data/ Bundled assets (unchanged from Python)
│ ├── prompts/identity_*.md
│ ├── tools/**/*.json
│ ├── grammars/*.gbnf
│ ├── bundled_models.yaml
│ └── default_config.yaml
├── tests/
│ ├── unit/
│ └── integration/
├── python/ Auto-generated wrapper
│ └── entropic/
│ └── __init__.py Generated from entropic.h
├── docs/
│ ├── roadmap.md
│ ├── architecture-cpp.md This document
│ ├── diagrams/
│ └── Doxyfile
└── extern/
└── llama.cpp/ Git submodule
Handle Lifecycle¶
entropic_handle_t is an opaque pointer to the engine’s root state object.
It owns all subsystems and controls their creation/destruction order.
Creation order (in entropic_create + entropic_configure):
Types/logging (spdlog init, error state)
Config loader (parse YAML, validate)
Inference backend (default tier loaded here unless
models.defer_load: true, which defers it to first use — gh#157)MCP server manager + built-in servers
Engine core (AgentEngine, ResponseGenerator, ContextManager, DirectiveProcessor)
Storage backend (optional — NULL if not configured)
Hook registry (empty until hooks registered)
Destruction order (in entropic_destroy, reverse of creation):
7 → 1. Each subsystem’s destroy is null-safe.
Optional subsystems:
Storage (
IStorageBackend*) — engine works without it (in-memory only)External MCP servers — engine works with built-in servers only
Hooks — engine works with empty registry
Mandatory subsystems:
Config (must parse successfully)
Inference backend (must have at least one loadable model)
Core engine (state machine, response generator)
Design Rules¶
Arrows point down. No circular dependencies between libraries.
Pure C at
.soboundaries. Opaque handles, C function pointers, C types only. No C++ types cross library boundaries.Plugin ABI versioning. Every plugin exports
entropic_plugin_api_version(). Version mismatch = rejected.Three-layer hierarchy. C interface (contract) → concrete base (80% logic) → implementation (20% specifics).
Exceptions do not cross boundaries. Caught at
.soedge, converted to error codes/callbacks.No third-party headers in interfaces. nlohmann/json, ryml, etc. are implementation details.
Symbol visibility. Only
ENTROPIC_EXPORTsymbols are public. Everything else hidden.Permissions ship with tools. Default-deny from day one. Per-identity granularity added later.
Streaming is first-class.
generate_streaming()in core interface, raw function pointer callback.Atomic state, mutex transitions. State queries are lock-free. Only state changes take locks.
Cancel token on generate. Consumer can abort mid-generation via atomic flag.
Config via generated header.
entropic_config.hgenerated from CMake, source never reads CMake vars directly. Configuration frontend is swappable.Static build supported.
ENTROPIC_STATIC=ONproduces.awith compile-time plugin registry.Data files are shared. Same identity prompts, tool JSONs, grammars as Python.
Auto-generated Python wrapper. C API header → Python bindings, no manual sync.
Directive wire format. MCP server
execute()returns JSON with{"result": "...", "directives": [...]}envelope. Directives are typed JSON objects dispatched by the engine’s DirectiveProcessor.Bundled data discovery. Compile-time
ENTROPIC_DATA_DIR, overridable at runtime via config. Used for prompts, tool schemas, grammars, model registry.Messages are JSON at boundaries.
const char* messages_jsonat C API, C++ structs internally. Metadata is arbitrary JSON.WARM→ACTIVE reloads the model. llama.cpp ties GPU layer offloading to
llama_model_load_from_file(), not context creation. WARM→ACTIVE frees the CPU-only model and reloads withn_gpu_layersfrom config. mlock ensures pages stay resident, so the reload is fast (~1-3s PCIe transfer, no disk I/O). This matches the Python_swap_model()behavior. (v1.8.2)logvariable renamed tologger. All inference.cppfiles useloggerfor the spdlog instance to avoid ambiguity withentropic::lognamespace and::logfrom<cmath>. (v1.8.2)extract_directives()lives in MCP, not core. Core has zero dependency on nlohmann/json. Directive extraction from tool result JSON (parsing_directiveskey) is performed by the MCP layer (v1.8.5), which passes typedDirectivestructs to core’sDirectiveProcessor. Core never touches JSON. (v1.8.4)Core .so uses default symbol visibility.
librentropic-core.sois an internal library, not a plugin boundary. All symbols are visible (CXX_VISIBILITY_PRESET=default) so test executables can link directly. Plugin.sofiles retain hidden visibility with explicitENTROPIC_EXPORT. (v1.8.4)TierResolutionInterfacefor cross-.so tier queries. Core needs tier identity data (auto_chain target, explicit_completion, system prompt) but cannot depend on prompts.so or inference.so. The facade injects aTierResolutionInterface(C++ function pointer struct in engine_types.h) — same pattern asToolExecutionInterface. (v1.8.6)Pending delegation stored as typed structs, not metadata strings.
PendingDelegationandPendingPipelineare optional fields onLoopContext, avoiding JSON serialization in core.so. The metadata map remains for genuinely string-keyed data. (v1.8.6)DelegationManager uses callback indirection. Takes
RunChildLoopFnandSwapDirFncallbacks instead of directAgentEnginereferences. This avoids circular header dependencies and lets the facade control the wiring. The engine exposesrun_loop(LoopContext&)as the public entry point for child loops. (v1.8.6)PermissionPersister uses string-based YAML editing, not ryml. ryml’s static library (
libryml.a) compiles with hidden symbol visibility. When linked PRIVATE intolibrentropic-storage.so, the ryml symbols are stripped, causing unresolved references at test link time. Since PermissionPersister only appends items to a YAML sequence (trivial operation), string-based line editing avoids the dependency entirely. ryml remains the project’s YAML parser for config loading inlibrentropic-config.so. (v1.8.8)Storage .so uses default visibility (same as core).
librentropic-storage.sofollows the same pattern as core (design decision #22) —CXX_VISIBILITY_PRESET=defaultso test executables can link directly. It is not a plugin boundary. (v1.8.8)LoRA adapter API uses
llama_set_adapters_lora()(plural). The pinned llama.cpp b8420 API takes an array of adapters + scales, not a single adapter. Deactivation = call with(nullptr, 0, nullptr). There is nollama_rm_adapter_lora(). KV cache clear after adapter swap usesllama_memory_clear(llama_get_memory(ctx), true). (v1.9.2)AdapterManager is a single concrete class, not a three-layer hierarchy. There is only one implementation (llama.cpp adapters), so no base class / interface layer. Same pattern as HookRegistry. Owned by ModelOrchestrator via composition. (v1.9.2)
Grammar validation uses
llama_sampler_init_grammar(nullptr, gbnf, "root"). GBNF parsing is vocabulary-independent — the grammar parser only needs the grammar string. Passingnullptrfor the vocab parameter is safe for validation: the function returnsnullptron parse failure, or a valid sampler on success (freed immediately). This allowsGrammarRegistry::validate()to work without a loaded model. (v1.9.3)GrammarRegistry follows the same single-class pattern as AdapterManager (decision #29). One implementation, no interface layer. Owned by ModelOrchestrator. Grammar resolution happens in the orchestrator’s generate path, not in the backend. (v1.9.3)
do_backend_name()is the only new pure virtual in v1.9.13. Every other new method has a default implementation. This is a deliberate breaking change — all InferenceBackend subclasses must identify themselves. Mock backends in tests get one-line overrides. The benefit (backend self-identification in logs, diagnostics, and BackendInfo) outweighs the cost. (v1.9.13)do_supports()uses lookup table + dynamic overrides, not switch-per-case. A switch with 14 cases violates the 3-return threshold. Instead, astatic constexpr bool[]table handles always-on capabilities, with a single conditional expression for runtime-dependent capabilities (KV_CACHE, HIDDEN_STATE, VISION, SPECULATIVE_DECODING). (v1.9.13)State management uses
llama_memory_*API (not deprecatedllama_kv_cache_*). The b8420 pinned llama.cpp usesllama_get_memory(ctx)→llama_memory_clear(mem, true)andllama_memory_seq_rm(mem, seq_id, -1, -1). Thedo_clear_state()override maps seq_id=-1 tollama_memory_clear()and specific seq_id tollama_memory_seq_rm(). Works for both transformer and recurrent models since llama.cpp handles both state types internally. (v1.9.13)PromptCache stores prefix-only KV via two-pass prefill.
llama_state_seq_get_datahas no range parameter — whatever is in seq 0 at save time is what gets serialized. On cache miss,run_prefill_cachedtherefore prefills only the system prefix (clearing memory first viarun_prefill), saves that state, then continues prefilling the remaining tokens. This keeps the cache entry honest: restore + auto-positioned decode is correct by construction, no runtime truncation needed. Partial-rangellama_memory_seq_rmafterllama_state_seq_set_datais NOT a viable alternative —state_read_metaallocates non-contiguous cells, and partial removal on that layout returns false (llama.cpp API contract). (v2.0.6)entropic mcp-bridgeis a pure stdio↔unix-socket relay (no engine). Addingentropic_create/ model load to the bridge is forbidden by design. The bridge owns no state beyond two file descriptors; an engine host (TUI, consumer app, future headless server) owns the model and publishes the unix socket. Discovery is deterministic from the canonical project_dir hash (compute_socket_path).--socket PATHoverrides discovery for non-standard layouts and testing. (v2.1.7, gh#34)Unix-socket trust boundary = same uid + file perms. External bridge enforces this via SO_PEERCRED UID check on
accept(),~/.entropic/socks/mode 0700, socket file mode 0600 (explicitchmod, not umask), and symlink-/non-socket-safe bind. A session-token handshake was considered and rejected: same-uid attackers can read the token, cross-uid attackers cannot reach the socket — adds protocol surface without changing the trust boundary. TCP transport is the trigger for proper token / OAuth auth — when/if a TCP transport ships, design auth at that point. Do not retrofit it onto the unix-socket path. (v2.1.7, gh#34)Speculative decoding is decoupled from the router.
inference.speculative.draft_modelandrouting.modelare independent config keys. The fact that a small Qwen happens to be the bundled router AND a candidate draft is incidental, not architectural. The"router"and"draft"roles onSecondaryModelLoader(gh#27) are separately keyed; consumers may point both at the same GGUF if they want, but the engine does not assume or reuse the router handle as the draft. Placement is a config axis (draft_n_gpu_layers: 0 = CPU default, -1 = full GPU, hybrid via partial offload) so the GPU stays saturated on the verifier when VRAM is the binding constraint. (v2.1.11, gh#36)Speculative-decoding recurrent-target gate lives in entropic, not upstream. At pin
253ba110b,extern/llama.cpp/common/speculative.cppdoes NOT self-disable speculative for recurrent / hybrid-Mamba targets (Nemotron-3-Nano-4B, RWKV, etc.) — the architectural rejection has to be applied before reachingcommon_speculative_*.entropic::speculative::check_compatcallsllama_model_is_recurrent(target)first and returns a structured diagnostic (“target model is recurrent … speculative decoding is incompatible”) when applicable. This protects against silent incorrectness on the hybrid-Mamba models bundled in v2.1.9. (v2.1.11, gh#36)Speculative compat is metadata-only and mirrors upstream’s static helper. At pin
253ba110b,common_speculative_is_compatis no longer public — the equivalent check isstatic bool common_speculative_are_compatible(model_tgt, model_dft)insidecommon/speculative.cpp, invoked implicitly from the draft-simple ctor which throwsstd::runtime_erroron mismatch. To preserve the query-without-commit ergonomic the v2.1.11 proposal calls for, entropic mirrors the upstream rules (vocab type, BOS/EOS parity, n_tokens delta ≤ 128, prefix token-text equality from id 5) using only publicllama_vocab_*accessors. The mirror is unit-testable on CPU with mock vocabs — nollama_contextneeded. Drift risk: if a future pin tightens the upstream rules, the mirror needs to be updated. The fixture for this is the bundled regression test (entropic-speculative-compat-tests) plus a comment pointer back to upstreamspeculative.cppin the helper source. (v2.1.11, gh#36)Speculative kernel ships gated + inert at the v2.1.11 pin; bit-identical correctness is structurally unreachable on every bundled primary. Session 5’s Gate A diagnostic (
spec_diag_boundary) dumped top-5 logits at the speculative split-prefill boundary for both the plain and speculative paths on Qwen3.5 and Gemma 4. With identical input tokens, identical n_past, and identical chat templates, the spec-side logits at sequence position N-1 diverged catastrophically (different top-1 token, half the logit magnitude). Root cause: upstream’sspeculative-simple.cppscheme ofprefill[0..N-2]then a separate batch decode of[id_last + drafts]assumes pure-transformer state continuity across ubatch boundaries. At pin253ba110b: (a)llm_arch_is_hybridreturns true for QWEN35, QWEN35MOE, QWEN3NEXT, KIMI_LINEAR, NEMOTRON_H/NEMOTRON_H_MOE, JAMBA, FALCON_H1, PLAMO2, GRANITE_HYBRID, LFM2/LFM2MOE — all of which actively usessm_d_state/ssm_n_group/ssm_dt_rankhparams (llama-model.cpp:1705-1715, 487-493); the arch guard refuses these via the newENTROPIC_ERROR_SPECULATIVE_INCOMPATIBLE_ARCHcode. (b) Gemma 4 (LLM_ARCH_GEMMA4) is NOT inis_hybridbut still allocatesllama_memory_recurrentfor half its layers — the classification is incomplete, so the guard lets Gemma 4 through and the kernel runs but produces divergent state too; additionally, the CPU-resident E2B draft is too slow on a 16 GB GPU to amortize (measured 0.46× speedup). The kernel code, hybrid-inclusive guard, andentropic_speculative_compatC ABI all SHIP in v2.1.11 as the foundation; the model tests SKIP with WARN messages pointing at this entry and the proposal’s Gate A. The kernel becomes useful at a future llama.cpp pin where cross-ubatch SSM state continuity is correct (or when a non-hybrid bundled primary lands). The separately discovered entropic-side off-by-one inspec_trim_*(seq_rm boundary usedn_past + 1where upstream usesn_past) is fixed in this version regardless — it’s a real bug that would still bite a future working pin. (v2.1.11, gh#36)MTP speculative decode is a target-owned, shared-KV path — separate from the gh#36 separate-draft kernel (#38–41), which stays the disabled/legacy path. The MTP head (
mtp-gemma-4-E{2,4}B-it.gguf, archgemma4-assistant, ~57 MB) shares the target trunk’s KV viacparams.ctx_other = ctx_(LLAMA_CONTEXT_TYPE_MTP,n_rs_seq=0). Only the holder ofctx_can create that context, so the target backend owns the head lifecycle:setup_mtp_draftbuilds it lazily against the livectx_;teardown_mtp_draftruns beforectx_is freed indo_deactivate/do_unload(the head borrowsctx_viactx_other, gh#58). The decode loop mirrors llama.cpp’s server MTP consumer: prefill the target only, callingcommon_speculative_processon the prompt batch to seedpending_h, then per rounddraft → llama_decode(ctx_) → common_speculative_process → common_sampler_sample_and_accept_n → common_speculative_accept. The caller never decodes the head context — the impl owns every head decode (shared-KV ⇒process()skips its catch-up decode); no checkpoint dance (shared-KV Gemma 4 is PART-seq_rm). Lossless by construction attemperature=0(only the target’s own greedy argmax is ever accepted). The orchestrator routesinference.speculative.mtpthroughtry_mtp_routebefore the gh#36 compat gate (#39/#41) — MTP tolerates the shared-KV Gemma 4 target the gh#36 gate rejects — andactivate_draftskips the separate-draft secondary backend under MTP.GenerationResult.n_drafted/n_acceptedexpose engagement. MTP is the experimental speculative path. MTP’s win tracks the RESIDENT FRACTION, not the card — measured at last (v2.13.0, gh#153), replacing the superseded Pascal sentence. The old claim — “on Pascal, lossless+functional but bandwidth-bound (low accept-rate, no net throughput win)” — is RETIRED, and it was wrong about its own mechanism as well as its number: the accept rate was healthy in both configurations we measured, so “low accept-rate on Pascal” describes nothing that happens. Configuration, per #59’s first rule: GTX 1080 Ti (Pascal),n_draft=4,flash_attnon,q4_0/q4_0KV,temperature=0, thinking off, one prompt, four arms (plain, an IDENTICALcontrol,mtp,mtp_grammar) on one model load in a Williams-balanced order, 4 measured trials after a discarded warm-up round, every figure taken from the engine’s own generation records. (a) Fully resident — Gemma 4 E4B QAT +mtp_e4b, all 42 layers on the card (3803 MiB VRAM after load),max_tokens=512: plain 53.11, control 53.09, mtp 75.84 tok/s (accept 1170/3532 = 0.331),mtp_grammar75.21 (accept 1187/3456 = 0.343, tier grammargh153_reviewresolved from the records,source=tier). Same-config floor 0.045 %, effect +42.8 %. (b) Partially resident — Gemma 4 26B-A4B QAT +mtp_a4batgpu_layers: auto→ 18 of 30 layers (13588 MiB model, 10448 MiB free VRAM; trunk split CUDA0 7864.78 MiB / CPU_Mapped 6105.11 MiB),max_tokens=256: plain 18.86, control 18.68, mtp 18.68 tok/s (accept 673/1424 = 0.473),mtp_grammar18.16 (accept 664/1464 = 0.454). Floor 1.00 %, effect −0.92 %. So MTP pays fully resident and does not pay under partial offload, and the reason is not drafting. The A4B’s accept rate is HIGHER than the E4B’s: 2.89 target tokens per forward pass against 2.32, which on drafting quality alone makes it the LARGER of the two expected wins (≈ +47 % scaling the E4B point by the draft headroom, and more on an optimistic reading). It measured ≈ 0 %. The leading explanation is a HYPOTHESIS, not a measured mechanism, and is recorded as one: verification cost scales with the drafted batch on CPU-resident layers — a batch ofn_draft + 1is nearly free on GPU-resident layers, where a decode step is bandwidth-bound on the weights and the extra rows ride along in the same read, but costs roughly the batch size on the 13 layers running on the host, and on a MoE the drafted tokens can route to DIFFERENT experts than the single token would have, multiplying the host-side work again. The one part that IS measured is negative: the MTP head was itself fully GPU-resident on that run (5/5 layers offloaded, 144 MiB CPU_Mapped), so a CPU-resident drafter is ruled out. Then_draft× resident-fraction sweep that would confirm or kill the rest is gh#167; until it runs, the claim here is the two numbers and the residency they were taken at, never the reason. What these numbers do NOT cover: (i)throughput_tok_sstamps its clock BEFORE tokenize and prefill on the plain and the MTP path alike, so every figure above is tok/s over the generate call, not a decode rate — the arms are comparable because prefill is identical between them, but the absolute number is not decode-only; (ii) CUDA graphs are forced OFF in every entropic build (ENTROPIC_CUDA_GRAPHSdefaults OFF and forcesGGML_CUDA_GRAPHSoff inextern/CMakeLists.txt), so the MTP draft-path speedup upstream #28549 added — the one #60 bumped the pin partly to reach — is NOT in these numbers, and a graphs-enabled build would have to re-measure; (iii) expert offload (-ncmoe/--n-cpu-moe) exists upstream at this pin and entropic did not expose it when these numbers were taken, so the A4B split moves WHOLE layers, attention included, and says nothing about an experts-only split — thecpu_moe_layersprototype of #75 landed in the same version, default off, and is NOT in any figure above; (iv) 4 trials, one prompt, one card, onen_draft,temperature=0— nothing is claimed about othern_draftvalues, other resident fractions, or other architectures. The suite asserts this under the resident-fraction rule of #74, which is why neither figure can quietly become a hardware property again. Exercised greedy on Q8 E2B and on mobile-QAT TQ2_0 (E2B + E4B). Lossless holds only attemperature=0(greedy argmax accept); see #43 for the v2.9.1 envelope guards that enforce this. (v2.9.0, gh#106; performance record measured and rewritten v2.13.0, gh#153/gh#167)MTP fails fast + loud outside its envelope — never silent fallback (#42 hardening). v2.9.0 let
speculative.mtpsilently bypass grammar / tools / stop-sequences / streaming and run non-lossless at temperature>0. v2.9.1 makesgenerate_mtpvalidate up front (mtp_unsupported_reason, a pure CPU-testable predicate):temperature>0, an active grammar (params.grammar), staged tools (active_tools_json_), or a streaming call (boundon_token) each return the typedENTROPIC_ERROR_SPECULATIVE_INCOMPATIBLE_CONFIGwith an actionable message, andtry_mtp_routepropagates it (returns true, owns the outcome — no plain-decode fallback that would mask the misconfig). Streaming is distinguished by the callback’s bound-ness, sotry_speculative_route(non-streaming) now passes an emptystd::functionrather than a bound no-op lambda. Robustness:n_draft+1 > n_batchand emptydraft.pathfail loud (not a silent clamp, notGGML_ABORT); a zero-draft round skipscommon_speculative_accept(whoseimpl_lastassert would abort) and progresses on the bonus token. Lifecycle: a coarsemtp_mutex_held acrossgenerate_mtpserialises againstteardown_mtp_draftindo_deactivate/do_unload(no deactivate-during-generate UAF; teardown itself must NOT lock — it is reached from the already-locked setup-rebuild path).spec_finalizenow setsthroughput_tok_s. General principle adopted: incompatible config/state for an explicitly-enabled feature fails LOUDLY so it can be corrected — silent fallback masks intent, a crash kills the host. (v2.9.1, gh#108)MTP made usable — tools un-guarded, stops honored, flash guarded (#43 correction). Real-HW (RTX Blackwell) testing showed MTP accelerates ~2.3× and that v2.9.1’s guards left it unreachable + over-broad. v2.9.2: (a) the tools guard is dropped — MTP is lossless at temp=0 and gemma4 tool-calls are parsed post-hoc (not sampler-grammar-constrained, unlike
params.grammarwhichto_common_samplinggenuinely drops), so MTP+tools yields the same call as plain; this makes MTP reachable through the agent loop (which stages meta-tools). (b) The real gap the tools guard masked was stop-handling:spec_emit_tokenonly checked EOS, so MTP over-generated past the gh#103 sequential-tool stop. The MTP run now threadseffective_stop(params)ontoSpeculativeRunState.stopandspec_emit_tokencallscheck_stop_sequences(no-op for the gh#36 path, whosestopis empty). (c)n_draftdefault 16→4 (16 over-drafts the small head → net slowdown). (d)build_cparamssetsswa_full=false—llama_context_default_paramsdefaults it true; correctness-neutral (SWA attention only uses its 512 window), saves ~5 GB at 128k for all Gemma-4 tiers. (e) MTP+flash fails loud (the GQA-2 + head_dim-512 head aborts the flash MMA kernel at this pin) → MTP is locked to f16 KV (quantized KV requires flash); the flash/q-KV speedup awaits an upstreamfattnfix. Grammar + temp>0 + streaming stay guarded (real constraints). (v2.9.2, gh#108)MTP+flash guard dropped — upstream fixed the GQA-2 flash-attn abort (#44e resolved). The
flash_attnbranch ofmtp_unsupported_reason(decision #44e) existed because the gemma4-assistant head (GQA-2, head_dim-512) fell through the flash MMA kernel’sDKQ<=256fallback path andGGML_ABORTed — the kernel only special-cased GQA>2 for head_dim>256. Upstream llama.cpp #25148 (“CUDA: fix Gemma E4B MTP FlashAttention”, merged 2026-06-30, fixes ggml-org/llama.cpp#24400) restores the GQA-1/2 MMA specializations that an earlier compile-time optimization (#21768) had inadvertently disabled.extern/llama.cppbumpedac4cddeb→b9886(20a04b22, 2026-07-06, 294 commits, includes #25148) to pick it up.mtp_unsupported_reasonno longer takes aflash_attnparameter; MTP now runs with flash enabled, which in turn unlocks quantized KV cache (cache_type_k/v) for MTP tiers since llama.cpp requires flash for quantized KV. Temperature and grammar guards are unaffected. (v2.9.3, gh#108)MTP’s
temperature>0guard dropped — the accept step was already lossless at any temperature, not just 0 (#42/#43 correction). #42/#43 assumed rejection sampling was needed for temp>0 losslessness because the accept step is “naive token-equality, not rejection sampling.” Re-derivation found the premise incomplete:common_speculative_impl_draft_mtp::draft()(extern/llama.cpp/common/speculative.cpp) always proposescur_p->data[0].id— the argmax of the (top-k=10-filtered) draft distribution — and never readscur_p->selected, the field a genuine stochastic draw would populate. This holds regardless ofbackend_sampling(confirmed by reading the CUDA/CPU backend-sampler dispatch: when the backend chain lacks a terminaldist/greedyop,common_sampler_sample()falls through to a CPU-sidedistsampler over the backend-filtered top-10 candidates — a real stochastic draw exists, butdraft()discards it and reads the argmax off the candidate list regardless). The draft proposal is therefore a deterministic point mass at every temperature. For a point-mass proposalq(m)=1, the general Leviathan/Chen rejection-sampling accept rule (accept-prob min(1, p_target(t)/p_draft(t)), resample residual on reject) collapses algebraically to exactly whatcommon_sampler_sample_and_accept_nalready does: draw one real samples ~ p_targetthrough the target’s full filter chain, accept iffs == draft[i], else emitsas the correction — lossless at any temperature by construction, not an approximation.mtp_unsupported_reasonno longer takestemperatureas a live guard (kept in the signature, unused, in case a future pin bump reinstates the need). Correctness now depends on an assumption about vendored code (draft()readsdata[0]notselected) that a futureextern/llama.cpppin bump could silently invalidate — the empirical distribution test intest_gh108_mtp_guards.cpp(“MTP is lossless at temperature>0”) is the regression tripwire; if a pin bump makes drafting genuinely stochastic, that test’s tolerance-band check should start failing, and the guard must be reinstated. (v2.9.4, gh#108)MTP grammar handling: per-tier static control + per-request dynamic safety net, not a single dispatch-level bypass (#43 refinement, not violation). Two real-world blockers surfaced once consumers ran realistic multi-tier configs: (a)
speculative.{enabled,mtp}is a single global flag with no way to keep MTP on for most tiers while permanently excluding a grammar-heavy identity/model, and (b) a request-level dynamic grammar (e.g. the constitutional validator’s critique call, which suppliesparams.grammarper-call on an otherwise grammar-free resident tier) hitgenerate_mtp’s loudENTROPIC_ERROR_SPECULATIVE_INCOMPATIBLE_CONFIGinstead of falling back, silently breaking validation (the error was swallowed by the caller, returning an empty critique). Fix has two parts: (1)TierConfig::speculative_mtp(nullopt = inherit global,resolve_mtp_effective(tier_name)applies the precedence) — coarse, static, per-identity/model control, following the same “inherit unless set” pattern asTierConfig::temperature. A tier that statically combinesspeculative_mtp=truewith a staticgrammaris rejected at config-load time (parse_tier_config), not per-request, since that combination would fail every call. (2) A request-level check intry_speculative_route_streaming: even on an MTP-effective tier,params.grammar.empty()gates entry totry_mtp_route— a dynamic grammar on one call falls through to plain decode instead of erroring, without requiring the whole tier to disable MTP. Neither part violates #43’s fail-loud principle: #43 was about MTP silently running in an unsupported config and producing subtly wrong output undetected. Here, (1) turns a would-be-every-request runtime error into a louder, earlier load-time error, and (2) is dispatch selecting the strictly correct decode path using a request property (params.grammar) that is fully known before any MTP-specific work starts — the same way the global on/off flag already silently selects plain decode whenspeculative.enabledis false.generate_mtp’s ownmtp_guard/mtp_unsupported_reasongrammar check is unchanged and still fires for any caller that reaches it directly (e.g. bypassing the orchestrator) — the dispatch-level check only avoids reaching it needlessly through the normal orchestrator path. (v2.9.4, gh#108)MTP was reachable from the orchestrator but structurally unreachable from the agent loop — two independent gates, not one (gh#110, v2.9.6). Gate 1:
build_loop_config()(src/facade/entropic.cpp) hardcodedLoopConfig::stream_output = true, so the agent loop always tookResponseGenerator::generate_streaming(), which unconditionally binds a non-emptyon_tokencallback intoorchestrator->generate_streaming()→try_speculative_route_streaming→try_mtp_route→LlamaCppBackend::generate_mtp’smtp_guard.mtp_guardderives itsstreamingargument tomtp_unsupported_reasonasstatic_cast<bool>(on_token)(llama_cpp_backend.cpp) — a bound callback is indistinguishable from “this is a streaming call,” so every agent-loop turn withspeculative.mtpon failed loud withENTROPIC_ERROR_SPECULATIVE_INCOMPATIBLE_CONFIG, unconditionally. Gate 2: even with streaming disabled,ResponseGenerator::dispatch_batch_generatepreferred the cancel-awareinference_.generate_cancellablebridge whenever wired (which production’sinterface_factory.cppalways does) — its backing call,ModelOrchestrator::generate(messages, params, cancel, tier), deliberately bypassesrun_generate_dispatch(doc comment: “batch only ever calls plain decode”); only the no-cancelModelOrchestrator::generate(messages, params, tier)overload runsrun_generate_dispatch. Existing MTP tests (test_gh106_mtp_route.cpp,test_gh108_agentic_benchmark.cpp) never caught this because they callorchestrator->generate()directly — shaped like the agent loop’s traffic, but never actually routed throughAgentEngine/ResponseGenerator/the facade. Fix: (a)generation.stream_output(newGenerationConfigfield, defaulttrue— no behavior change for existing consumers) threads throughbuild_loop_config()intoLoopConfig::stream_output, making batch mode reachable; (b)LoopConfig::speculative_enabled(mirrorsinference.speculative.enabled— core.so cannot depend on config.so per design rule 2, so the facade plumbs a plain bool same asbudget_mode/budget_limit) makesdispatch_batch_generateprefer the dispatchinginference_.generateovergenerate_cancellablewhenever speculative decoding is on. v1 tradeoff, documented not hidden: a speculative batch turn is not cancellable mid-decode.test_gh110_mtp_agent_loop.cppcloses the coverage gap by driving the realentropic_create/entropic_configure_dir/entropic_runpath withgeneration.stream_output: false+inference.speculative.{enabled,mtp}: true, asserting on the backend’s own"Speculative: generated=..."log line (the only signal that crosses the C-ABI boundary —n_drafted/n_accepteddo not appear inentropic_run’s orentropic_metrics_json’s output). (v2.9.6, gh#110)ExternalBridge
entropic.askis configurable between streaming and non-streaming paths —mcp.external.ask_streaming(gh#115, v2.9.12).handle_askpreviously hard-codedentropic_run_streaming, which (a) bindson_token, tripping the MTP incompatibility guard (mtp_unsupported_reasontreats any bound callback as streaming — decision #43/49), producing 0-char output withaccept_rate=0.000; and (b) callsj.dump()on the streaming-path serialized result without the UTF-8 sanitization applied to theentropic_runpath in v2.9.7–v2.9.11, throwingtype_error.316on MTP-split codepoints. The same root as #49:on_tokenbinding = streaming flag = MTP guard trip. Fix:ExternalMCPConfig.ask_streaming(defaulttrue) threads throughExternalBridge::ask_streaming()getter →dispatch_ask→ eitherhandle_ask_plain(callsentropic_run, extracts final text from result JSON — the path already sanitized and MTP-compatible) orhandle_ask(existing streaming path, unchanged). Consumers running MTP setmcp.external.ask_streaming: false; streaming consumers are unaffected. Asyncentropic.ask(async: true) already usedentropic_runinsiderun_async_ask(#59) and is unaffected by this flag. (v2.9.12, gh#115)looks_like_mtp_headpredicate guards the classical draft path — fail-loud instead of crashing in fattn.cu (#44/#41 routing gap, gh#107, v2.10.0). A Gemma 4 MTP head GGUF (1–2 transformer layers, shared-KV architecture) pointed atdraft.pathwithspeculative.mtp: falsereachedgenerate_speculative_with_draft→ upstreamcommon_speculative_impl_draft_mtp, whichGGML_ABORTed infattn.cu:110(the head’s GQA-2/head_dim-512 geometry was incompatible with the classical DRAFT_SIMPLE path). The crash surfaced when consumers upgraded from a classical draft GGUF to the bundled MTP head without toggling the flag. Fix:looks_like_mtp_head(n_layers)(include/entropic/mcp/mtp_envelope.h) returns true whenn_layers <= 2;mtp_head_classical_path_error(n_layers)returns an actionable message namingspeculative.mtp: true. Intry_speculative_route_streaming, before delegating to the classical path, the draft backend’s layer count is queried — iflooks_like_mtp_head,ENTROPIC_ERROR_SPECULATIVE_INCOMPATIBLE_CONFIGis returned immediately. The predicate and error message are unit-tested inmtp_envelope_test.cppwithout a real GGUF. (v2.10.0, gh#107)MTP grammar guard removed —
to_common_samplingnow propagatesparams.grammarintocommon_params_sampling(#48 superseded, v2.10.0). The v2.9.4 workarounds in decision #48 (dispatch-levelparams.grammar.empty()gate + config-load rejection ofmtp+grammar) were never fixes — the root cause,to_common_sampling(llama_cpp_backend.cpp) not settingcps.grammar = params.grammar, was untouched. Once that line was added, MTP’s own sampler chain enforces the GBNF constraint for every call, making the guards redundant. Both workarounds are removed: the dispatch gate (so grammar calls now route to MTP rather than silently falling through to plain decode) and the config-load static rejection (so consumers can statically configurespeculative_mtp=trueon a grammar-bearing tier).mtp_unsupported_reason’shas_grammarparameter becomes(void)— the function always returns empty for this axis. The per-tierTierConfig::speculative_mtpoverride mechanism from #48 is retained; it remains useful for permanently disabling MTP on a per-tier basis regardless of the grammar state. (v2.10.0, gh#108)generate_streamingwrapson_tokenwithStreamThinkFilterand callsapply_adapter_parse— MTP streaming guard removed (#43/#49 streaming limitation resolved, v2.10.0). The v2.9.1 streaming guard (mtp_unsupported_reasonreturning non-empty whenstreaming=true) existed becausestrip_thinking_channelsis post-buffer only, and the streaming path never calledapply_adapter_parseat all — thinking channel tokens (<|channel>) flowed live to the consumer and persisted unrestripped inresult.content. Fix:generate_streamingwraps the consumeron_tokencallback with aStreamThinkFilterinstance before passing it to bothtry_speculative_route_streamingandmodel->generate_streaming.StreamThinkFiltertakes a C-styleTokenCallback(void (*)(const char*, size_t, void*)) +void*user_data; a static trampoline function (stream_token_trampoline) bridges the orchestrator’sstd::function<void(std::string_view)>consumer. After generation completes on both paths,filter.flush()is called to emit any pending buffered content, thenapply_adapter_parse(model, get_adapter(selected), result)post-processes the accumulatedresult.content(tool-call parsing, adapter scrub) — the same call the non-streaminggeneratealready made atorchestrator.cpp:600. The MTP path receives theStreamThinkFilter-wrapped lambda automatically;mtp_unsupported_reason’sstreamingparameter becomes(void).entropic-coremust be linked explicitly by test binaries that includestream_think_filter.h—entropic-inference-cpuis an OBJECT library whose PRIVATE deps do not auto-propagate to consumers. (v2.10.0, gh#108)MCP server plugins load as a third routing peer, not as an
MCPServerBasesubclass (gh#133, v2.10.1).i_mcp_server.hdocumented a dlopen plugin contract from v1.8.5 onward while no loader existed —grep -rn "dlopen\|dlsym" src/returned zero hits, for the MCP boundary and for the inference-backend boundary that mandates the sameentropic_plugin_api_version()export. The obvious implementation, aPluginServerAdapter : MCPServerBaseforwarding virtuals to the C ABI, does not work:MCPServerBase::list_tools()(server_base.h:96) and::execute()(:110) are non-virtual concrete methods iterating the server’s ownregistry_, so an adapter cannot intercept them —ServerManagerwould see an empty registry instead of the plugin’s tools. Making them virtual would change theMCPServerBasevtable, which this header explicitly defines as requiring anENTROPIC_MCP_PLUGIN_API_VERSIONbump, and would break any consumer already subclassing the default-visibility, installed base. Instead plugins mirror the existingExternalMCPClientpattern: external servers are likewise notMCPServerBasesubclasses but a parallelstd::mapwith their own branch inroute_tool_call.PluginServer(RAII over the dlopen handle + nine resolved entry points, destroying the instance beforedlclosesince the destructor lives inside the library) becomes the third such peer, withplugin_servers_and matching branches inlist_tools/server_names/list_server_info/shutdown/get_tool_schema. Consequences worth recording: (a)get_tool_schemahad to grow a plugin branch —ToolExecutor::check_schemaskips validation on an empty schema, so without it plugin tools would silently forgo the argument checking every built-in tool gets; (b) plugin output is untrusted input — a malformed tool list or response envelope is caught per-plugin rather than throwing through the agent loop; (c) plugins load after builtins in the facade so a name collision is rejected instead of shadowing a built-in server; (d)RTLD_LOCALkeeps two plugins’ identically-named entry points from colliding; (e) returned strings are freed via that plugin’sentropic_free, not the engine allocator. Separately, addingENTROPIC_EXPORTto the nine declarations is load-bearing, not cosmetic: measured on GCC 11.4 under-fvisibility=hidden, a plugin defining its entry points bare (inheriting visibility from the header, the normal way to implement a C API) exports 0 symbols without it and all 9 with it. The consumer report’s stated mechanism for this — that GCC warns and silently ignores avisibility("default")attribute on a definition whose declaration lacked one — does not reproduce; a definition-site attribute is honored, with no warning. The test fixture therefore defines its entry points bare deliberately, so it stays a genuine RED control for the header fix rather than passing either way. (v2.10.1, gh#133)Thinking-block removal is an adapter-owned concern, resolved per family and applied on every path (gh#108, v2.10.3). Gemma-4 emitted
<|channel>…<channel|>intoresult.contentand the live stream on plain decode, streaming, MTP and batch alike. Root cause was structural, not behavioural: every family had an adapter stripping its own markers except gemma4, whichadapter_registrydeliberately omitted (tool calls go through llama.cpp’sPEG_GEMMA4), soadapter: gemma4resolved toGenericAdapter— which strips<think>, a marker gemma4 never emits. The sole<|channel>handler (strip_thinking_channels) sat insideparse_response, reachable only whencommon_chat_parse_reliable()is true, i.e.parse_params_valid_ && format == PEG_GEMMA4— a gate whose actual purpose is “is this captured format multi-parameter safe?”. Reasoning stripping had been bolted onto it, so it ran only for gemma4 AND only after a tooled render. MTP/streaming/grammar were red herrings — a plain-decode non-streaming control leaks identically, which also means the v2.9.1 MTP-streaming guard (#43) gated a feature over a defect in a different layer and never protected anyone; #53’sStreamThinkFilter“fix” targeted<think>, the wrong family’s marker, and no test caught it because no test droveorchestrator->generate_streamingwith MTP on. Resolution: (a)ChatAdapter::thinking_markers()— each family declares its delimiters once, consumed by bothstrip_think_blocks(now marker-driven, plain substring since<|channel>contains a regex metacharacter) andStreamThinkFilter(markers injected by the orchestrator; core takes plain strings, no inference dependency), so buffered and live paths cannot diverge again; (b)Gemma4Adaptersupplies the fallback that never existed, withPEG_GEMMA4still primary when an arena exists; (c)response_parse.hcollapses the byte-identical branch duplicated inorchestrator.cppandinterface_factory.cppinto one template-first/adapter-second rule — content cleanup composes (adapter strip always runs, idempotent) while tool-call extraction does not, so the template result is validated against the staged tool schema and falls back to the adapter when required params are missing, which is the only way to detectcommon_chat’s silent first-parameter-only extraction (gh#87 Phase D — it returns a well-formed ToolCall, so no try/catch fires); (d)ConstitutionalValidatorresolves markers per tier via a facade-supplied callback, since one validator serves all tiers but thinking format is per-family. Process note: the release that introduced #52/#53 shipped on a vacuously-passing test — it asserted the removed guard no longer fired rather than that streaming worked — so the RED for this entry deliberately drives the real production path and carries plain-decode/non-streaming controls that attribute a leak to the correct layer. (v2.10.3, gh#108)Grammar has three sources and one seam; UTF-8 has many exits and few entrances — fix at the choke point, not the instance (gh#134/gh#136, v2.10.4). Two consumer defects, one shared cause: repeated per-call-site fixes for a class of bug that needed a single structural one. (a) gh#134 —
common_chat_templates_applyderives a tool-call GBNF from the staged schemas;render_with_toolsharvestedprompt/format/generation_prompt/parserand DISCARDEDgrammar, so every tools-staged tier decoded unconstrained andtool_choice: REQUIREDwas inert. That is the third dropped-grammar instance after #48-era gh#95 (identity grammar dropped in the facade) and #52 gh#108 (params.grammarnot reaching MTP). Fixed by capturing the render’s grammar (invalidated indo_unloadbeside the parse snapshot per #54’s stale-arena lesson) and applying it into_common_sampling— the ONE seam plain decode and MTP share, so MTP is covered by construction rather than needing the follow-up gh#108 required. Critically it must be applied asCOMMON_GRAMMAR_TYPE_TOOL_CALLS, never_USER:common_grammar_needs_prefill()is true only for the former, andgeneration_promptmust be prefilled into the grammar sampler because the model’s output begins mid-template — applied as_USERthe grammar rejects the first token and surfaces asGENERATE_FAILEDwith empty content, which is precisely what was measured before the prefill was threaded.TierConfig::require_tool_callexposes it, opt-in per tier. Under REQUIRED the gemma4 rule iszero_or_more(any) + tool_call— unbounded preamble, mandatory call — so the grammar guarantees a call eventually, not withinmax_tokens; a budget-starved REQUIRED turn endsfinish_reason=lengthwith zero calls and is now named explicitly, since it is a config error indistinguishable from a model stall otherwise. (b) gh#136 —type_error.316recurred a fourth time after gh#112/113 were closed as “permanent closure of the family”. Every fix patched one.dump(); there are ~18 in the facade alone. Sanitized at INGRESS instead — the three points where model bytes first become astd::string— whichresponse_generator.cpp:360had already done for the streaming accumulator since v2.1.1 without the pattern ever being generalised. Safe becauseraw_contentis a copy ofcontentand sanitize only replaces bytes already invalid as UTF-8, which cannot form part of a valid JSON token. General rule adopted: when a defect class recurs, count the exits and the entrances and guard whichever is bounded. Process note: three of the four tests written for gh#134 passed vacuously (the model emitted the tool call regardless), and the discrimination metric compared prose counts rather thanfinish_reason, hiding a real effect — only a same-model, same-prompt, same-budget A/B with the flag as the sole variable discriminated. Every invariant added here therefore carries a control that must fail. (v2.10.4, gh#134, gh#136)A traceability catalog that fails open is not a gate — and headers describe intent, not behaviour (v2.11.0).
docs/requirements.yamlwas deleted as collateral in adocs/purge at v2.1.0 and stayed gone for fifteen months of green commits, because all three of its consumers degrade silently when it is absent:check_req_existsself-disables on an empty catalog (req_ids = set(...) or None→None→ returns[]),check_req_coverageverifies only that the config names a path and is satisfied by exemption tags, and impact reporting degrades to “No requirements affected.” Even at its healthiest the catalog was 10 of 140 entries referenced from code — it was never load-bearing. Rebuilt bottom-up from the shipped implementation (eight parallel subsystem sweeps → 112 requirements → 105 after reconciling the cross-cutting rules each sweep restated at its own boundary), and made durable byinv check-requirements, which fails closed. Three properties that tool must check and doxygen-guard structurally cannot: (a)@reqon a bodiless header declaration is invisible to doxygen-guard for both coverage and cross-reference — the parser skips declarations with no body, which is how a deadREQ-INFER-003survived ini_inference_backend.hafter Phase 2 merged it intoREQ-ABI-001, seen by no gate; (b) exemption creep is invisible —_extract_tagged_functionnever collects a function whose only tag is@internal/@utility/@callback, so the repo’s 0.9%@reqratio was undetectable by the coverage command; (c) a ratio floor, not an absolute count, since deleting code lowers both numbers legitimately and only the proportion expresses the property worth defending. The second lesson is sharper. The sweeps were instructed that the implementation IS the specification, but they read headers and doxygen — which describe intent — and four times the intent had never been built:entropic_set_error_callbackreturnedENTROPIC_OKwhile discarding its arguments (the callback type is invoked from nowhere in the tree);FileAccessTracker::was_read_unchangedhad no production caller, and the test named..._detects_external_changeconceded in its own comment that the write succeeds; the bash/git command timeout is stored, logged and exposed but never enforced; and two catalog entries written from those headers asserted both. This is the same class as #54 (gh#133: a dlopen plugin contract documented from v1.8.5 with no loader). Rule: a requirement derived from a header is a hypothesis until a test exercises the production path. Anyverified_bynaming a test must be checked for whether that test drives the real call site or asserts on a helper directly — the filesystem one passed for years while the behaviour was absent. Third, on method: gh#137 was chased through five hypotheses reasoned from source (strip greediness, toolless render bypass,enable_thinkingthreading, template support, named channels) and every one was wrong; the strip provably matches the model’s own jinjastrip_thinkingmacro case by case. What settled it was measurement — three GPU runs across E2B and E4B QAT, all delivering 100% of their content — and what nearly derailed it was a self-inflictedgpu_layers=15copied from a note about a model three times the size, which aborted indo_activateand was briefly mistaken for the model being unusable (#139). Reading code proposes; only running it disposes. (v2.11.0, gh#137, gh#138, gh#139, gh#140)Two headers promised what nobody built, and the third told a consumer to build on it (v2.12.0, gh#143/gh#144/gh#145). gh#144 arrived with an INVERTED premise — a careful reader concluded concurrent asks would queue — because
@threadsafety Serialized per-handle.sits on all six run entry points and has been false since #52-era gh#109 removedapi_mutexfrom them so a long turn could not blockentropic_interrupt(). Meanwhile the bridge has served each client on its own thread since v2.1.2. Two concurrent asks therefore raced the shared conversation vector AND decoded concurrently on onellama_context. Alongside it,ENTROPIC_ERROR_ALREADY_RUNNINGwas declared in the enum, carried in the error-string table and documented as a returnable outcome on two entry points since v1.8.9 — and returned from nowhere in the tree; andentropic_inference_generate_seqhas been on the plugin ABI since v1.9.13 withdo_generate_seqsilently delegating to the keyless variant, overridden by nobody and called by nobody. That is three more instances of #57’s class in one issue, so the rule generalises: a contract stated only in a header is a hypothesis, and the cost of a false one is not a stale comment — it is a consumer who designs against it. Serialization was therefore implemented as making the documented outcome occur rather than as new API surface. The claim is a compare-exchange on the existingrunning_flag_, never a mutex, andHandleTurnGuardis a deliberate SIBLING ofHandleApiLockrather than a subclass, because reusing that type would silently reintroduceapi_mutexon the run path and re-break gh#109 — the single likeliest mistake in the refactor, so both headers say so at the declaration. Rejecting at the ABI while QUEUEING at the bridge is the split that satisfies both callers: a direct C consumer wants to be told, a shared host wants to wait, and a FIFO ticket queue (not a bare mutex) is what makes the wait fair, bounded and observable — a mutex offers no fairness, no depth and no deadline, and MCP clients carry their own timeouts, so blocking one indefinitely is worse than telling it the truth. Non-unified KV was chosen for fail-fast, not for memory. Verified in the vendored llama.cpp that total KV isn_ctxworth of cells either way (llama-kv-cache.cpp:98,247;llama-context.cpp:229-243) — unified is not cheaper, it tradesn_seq_maxprivate guaranteed streams for one shared pool in which a long session starves the others behind “could not find a KV slot”, a runtime failure with no attribution to a session.max_sessionstherefore DERIVESn_seq_max,kv_unifiedandn_ctxtogether rather than exposing three knobs an operator can set inconsistently, andcontext_lengthstays PER SESSION. The KV correctness trap is worth naming precisely, because the in-repo comment about it was wrong:try_warm_reuseclaimed an interleaved conversation “either fails the occupancy gate or diverges in the prefix scan, and we fall back”, and NEITHER branch fires — two sessions on one handle share a system prompt, socommon_prefix_len > 0, socut > 0, so theseq_rmbranch destroys the other session’s tail and, by returning true, skips the prompt cache as well. Latent only while one shared conversation meant one monotonic history; keying ACTIVATES it, which is why per-sequence residency had to land before the store. Two process notes. First, the exception barrier for gh#143 was initially placed one level too low: inToolRegistry::dispatchit letinject_anchor_if_neededstill run on a failed call, so a REJECTED path traversal was anchored into context as though it had been read — caught by the existing security test, and the reason the barrier now sits inMCPServerBase::executeabove anchor injection. Second, normalisation must not swallow caller error: the first cut coerced ANY non-object argument payload to{}, andEntropicServer’s followup tool — which already answers a non-object with a typed “invalid args” naming the real problem — failed and was right to. Only empty and literalnullmean “no arguments”; an array, a scalar or unparseable input reaches the tool so the sender is told. Fourth, MTP was discarding a cache for no reason anyone had stated.mtp_init_runcalledllama_memory_clear(ctx_tgt, true)and fully re-prefilled on EVERY generation, so underspeculative.mtpwarm-keep and the prompt cache never executed at all — a consumer observed ZERO warm-keep events across a three-turn review with MTP on, against substantial prefix reuse with the same workload MTP off. The figures first recorded here — a prefill:generate ratio and an MTP-off percentage — were WITHDRAWN, and the reason is worth keeping. That measurement ran over the external bridge while every external tool call was silently failing via gh#150, so both arms measured a degraded fallback path; and the error has no predictable sign, because dead tool results were tiny where live ones would have INFLATED prefill, while the extra flailing turns and one 557 KB directory listing pushed the other way. So the ratio is not merely imprecise, its direction is unknown. What survives is the mechanism question — whether retention engaged AT ALL — whichmtp_init_run’s unconditionalllama_memory_clearsettles independently of what the context held, and which the consumer later confirmed on v2.12.1 (retention engaged on every turn with MTP active, against zero events before). Rule: a consumer’s measurement is evidence about their whole stack, not about the one variable you care about — check that the instrumented path was actually alive before reading a number off it. Nothing about speculative decoding requires that: it was an implementation choice in one path, and it made two effects that should COMPOSE mutually exclusive. Retention uses the same rule as plain decode — a prefix match validated against the KV’s own occupancy viallama_memory_seq_pos_max, never a software counter. Fifth, and the methodological point of the whole release: this class of defect is invisible to CPU tests, and the instrumentation is what finds it, not the output. Three separate times the assertion that mattered was a token COUNT, not an answer: (a) the session-pool bug —restore_cached_prefixrestored the cached prefix into sequence 0 while decoding the remainder into the caller’s slot, so every session but the one holding slot 0 attended to a fragment with no system prompt, and both it andrun_prefillwiped every other session on any cold prefill — 1739 CPU tests passed throughout, because the single-session path cannot reach either bug when slot 0 IS the hardcoded sequence, and the giveaway was one session prefilling 17 tokens where another prefilled 38, not the wrong answers; (b) the first MTP RED was red for the WRONG reason, reporting 0 tokens per turn becauselast_prefill_tokens()was never instrumented on that path at all —GenerationResult::prefill_tokenshad to exist before anything could be measured; (c) the isolation test’s cross-contamination assertions passed VACUOUSLY while the feature was broken, because a session that recalls nothing trivially contains no other session’s secret. Rule: assert the instrumentation, never only the output — a correctness test passes via fallback even when the optimisation is dead. Worth recording that four of the defects found in this release were in the TESTS (a wrong flatness assertion, a vacuous>= 0, a Catch2 leaf-section re-run that started four bridges on one socket, and an impatient client that reported a working FIFO queue as a failure) against two in the engine — and that the harness itself hid evidence twice:inv test --model --filterfiltered only the CPU phase and then ran the entire model suite, and the model runner sent stdout and stderr toDEVNULLso a failing GPU test discarded every assertion message that said why. The GPU time is already spent; throwing away the diagnosis is the expensive part. (v2.12.0, gh#143, gh#144, gh#145)A performance claim measured in a configuration we later called a bug outlived the fix (v2.12.2, gh#106/gh#108). Decision #42 records that MTP “on Pascal is lossless+functional but bandwidth-bound (low accept-rate, no net throughput win) — a modern-HW / ceiling-additive lever, not a floor win.” That was measured at v2.9.0, when
n_draftdefaulted to 16. Decision #44 then changed the default 16→4 at v2.9.2 with the note “16 over-drafts the small head → net slowdown”. So #42’s Pascal figure was taken in precisely the configuration #44 identifies as a net slowdown, and it has never been re-measured on Pascal since the fix — the claim simply stayed in the log, where it reads as a property of the hardware rather than an artifact of a default that no longer exists. A consumer has since measured ~2x tok/s over the generate call (76.7 vs 38.3 tok/s, temperature 0, warm trials — prefill included, so not a decode rate; see #42) on this project’s own GTX 1080 Ti atn_draft=4, against a 19% floor established by a control of two IDENTICAL plain configs — and the figure agrees with what the measured accept rate predicts independently (0.62–0.68 atn_draft=4⇒ ~2.6 target tokens per forward pass ⇒ ~2x after overhead), which is the part that makes it credible rather than the raw number. Measured with NO active request grammar — the consumer’s tier named its grammar by bare stem, their harness wrote each arm’s config where no matching.gbnfsat, and the registry failed open as documented (gh#154). The comparison survives, because both arms lacked it equally and were judged against a same-config control; the CONFIGURATION LABEL does not, and the standing claim is “~2–3x on Pascal atn_draft=4, unconstrained decode” rather than “~2–3x on Pascal”. Grammar-constrained decode is that consumer’s production configuration and a grammar plausibly moves the accept rate the speedup rests on, so the interaction is open, not settled — both accept-rate figures on gh#147 are now withdrawn and none was ever measured under an active grammar on this hardware. This correction is rule one catching a claim recorded under rule one, one day later, which is the most direct argument for the rule that could be asked for. This is not yet OUR measurement: the suite asserts MTP engagement (n_drafted/n_accepted) and has never asserted throughput, so #42’s claim was never under test and its staleness could not surface as a failure. The consumer’s route to it is instructive on its own: four earlier figures from the same harness (−5%/+16%, 36–39%, ~8%) were each withdrawn, and every one of them was the harness measuring itself — a cold trial averaged into warm ones, 1 Hz polling quantising a 2 s measurement, a control run overwriting the real run’s logs. The control is what changed the answer, not better analysis. Two rules follow. First, a performance claim must record the configuration it was measured in, and must be re-measured or retired when that configuration changes — otherwise a fixed bug leaves its symptom behind as documented fact. Second, an A/B without a same-config control measures the harness as much as the subject: 19% between two identical configs is the scale against which any candidate effect must be judged, and 8% was inside it. Third rule, and the one that explains all five withdrawn figures at once: a per-unit-of-work wall clock is not a throughput metric when the size of the unit is itself a variable. A later run made this visible in a single line — three arms took 8186, 9721 and 7576 ms per review, near-identical, while the fastest emitted 2378 tokens against 958. Per-review time was measuring how much each arm decided to SAY, not how fast it said it. Every withdrawn figure divided by something that moved for reasons unrelated to the variable under test: ms/iteration when the arms took 19 and 14 iterations, ms/review when output volume differed 2.5x, a prefill:generate ratio when the tool layer was dead. Tokens per second is the metric that survives, because both of its terms are measured rather than assumed. #42’s Pascal sentence is superseded pending our own instrumented measurement; gh#151 shipped thetok/sline on the speculative path that makes it readable at all. (v2.12.2, gh#106, gh#108, gh#151)llama.cpp b9886 → b11009: the bump was five mechanical API breaks, and the interesting finding is what the enum swap hides (v2.13.0, gh#148/gh#166).
extern/llama.cppmoved20a04b220(b9886, 2026-07-06) →fb27a525d(b11009, 2026-09-16). Motivation: the FlashAttention fix that #45 already relies on stays in, upstream #28549 puts CUDA graphs on the MTP draft path (a GPU-gate question, not reachable from a CPU build), and the pin had drifted far enough that the API renames were going to have to be paid eventually. Five compile breaks, all resolved without a behaviour change: (a)llama_model_params::use_mmap/::use_mlockare gone, replaced by a singlellama_load_modeenum; (b)llama_sampler_init_penaltiesgained a leadingn_vocab(fedllama_vocab_n_tokens(vocab_), matching upstream’s own call incommon/sampling.cpp); (c)common_speculative_draft_params::n_past→pos0— verified a pure rename by diffing every use incommon/speculative.cpp, which are line-for-line identical; (d)mtmd_helper_bitmap_init_from_filegained a trailingmtmd_helper_init_optcarrying video-decode params (mtmd_helper_init_opt_default()is the still-image behaviour); (e)tools/mtmddroppedLLAMA_INSTALL_VERSIONforLLAMA_VERSION_BASE/LLAMA_VERSION_MAJOR, and sinceextern/CMakeLists.txtadds that subdirectory by hand it has to mirror the new names — an undefinedVERSIONproperty is not a CMake error, so this one fails silently rather than loudly and is worth re-checking on every future bump. Theload_modemapping is the only one with a judgement call in it. Three values could plausibly stand in foruse_mmap = true:AUTO,MMAP,MMAP_MLOCK.AUTOis upstream’s default and is NOT the faithful choice — it additionally probes every backend device forcaps.mmap_supportand silently downgrades to a full read when one says no (src/llama-model.cpp:1444), a probe that did not exist at b9886. So the mapping is explicit:MMAP_MLOCKwhenModelConfig::use_mlock,MMAPotherwise, through one helper (mmap_load_mode) shared by all four load sites. The field the enum swap quietly added islazy_mode, and it defaults to ON.LLAMA_LAZY_MODE_AUTOreads rows of arch-marked tensors over 4 GiB on demand from the mmap instead of materialising them — and the only two tensors markedTENSOR_READ_LAZYin the tree aregemma4.cpp’sper_layer_tok_embdandqwen4exp.cpp’s PLE block. Gemma 4 is this project’s MTP family, so the new default lands squarely on the primary path: a lazily-read tensor takeslazy_read::buft()and stays host-side, which changes VRAM footprint and first-token latency rather than correctness. Nothing was set here — changing it would be a behaviour change beyond what compiling required — but it is a GPU-gate item, not a settled one: if E4B load time or VRAM moves,lazy_mode = LLAMA_LAZY_MODE_OFFis the one-line restoration of b9886 behaviour. The sibling fieldload_mtp(default false) gates MTP tensors that live INSIDE a target GGUF (deepseek, qwen3next, qwen35moe, glm4-moe, …);gemma4-assistant.cppnever reads it, so entropic’s separate-head MTP is unaffected — but any future in-GGUF MTP target would need it set. Tripwires re-validated by reading, not running. #19 (n_gpu_layersis still a MODEL param, so WARM→ACTIVE must still reload), #28 (llama_set_adapters_loraplural, still nollama_rm_adapter_lora), #30 (llama_sampler_init_grammarstill returns nullptr on parse failure), #34/#35 (llama_memory_*unchanged;llama_state_seq_get_datastill has no range parameter, so the two-pass prefill stays the only honest way to cache a prefix), #39/#40 (common_speculative_are_compatibleis stillstatic, still has NO recurrent/hybrid check, and the four rules entropic mirrors — vocab type, BOS/EOS parity,SPEC_VOCAB_MAX_SIZE_DIFFERENCE128, prefix text equality fromSPEC_VOCAB_CHECK_START_TOKEN_ID5 — are byte-identical), #44b (swa_fullstill present onllama_context_params), #45 (the GQA-2 MMA specialisation is still live infattn.cu), #51 (common_speculative_impl_draft_simplestill exists, so the classical path the predicate guards is still reachable), #56 (common_grammar_needs_prefillstill true only forOUTPUT_FORMATandTOOL_CALLS), #58 (kv_unifiedstill makesn_ctx_seq = n_ctxwhile non-unified divides and re-derives, so total cells aren_ctxeither way — the fail-fast argument, not the memory one, is still the reason to pick it). #46 is the one that mattered and it holds:common_speculative_impl_draft_mtp::draft()still proposescur_p->data[0].idand still never readsselected, so the draft proposal remains a deterministic point mass and MTP stays lossless at any temperature. Two drifts worth recording. First,common_speculative_acceptrelaxed a hardGGML_ASSERT(impl)into an early return guarded byGGML_ASSERT(n_accepted == 0). #43’s zero-draft-round skip is therefore no longer load-bearing against an abort — it is kept anyway, because it is still correct and removing it buys nothing. Second, the separate-draft path grew recurrent/hybrid awareness (need_boundary_stash()stashes the boundaryg_embdrow because “their single-position checkpoints drop it on restore”), which is the first upstream movement toward the cross-ubatch state continuity that #41 declared structurally unreachable. That does NOT reopen #41 on reading alone — #41 was settled by measurement (the Gate A logit dump) and can only be reopened the same way. On-disk state: the format constants upstream bumped are ones entropic never reads.LLAMA_SESSION_VERSION(9→10) andLLAMA_STATE_SEQ_VERSION(2→3) are checked only byllama_state_load_file/llama_state_seq_load_file; entropic uses the in-memoryllama_state_seq_{get,set}_dataexclusively, and those carry a magic (io_magic, unchanged at0xaf143cd8) but no version field at all.entropic_state_savethen writes that raw blob to disk with no header of its own — no magic, no version, no model identity. A stale blob is therefore caught only by llama.cpp’s structural checks (layer count, K/V type, row size, and a bounds-checked read that throws and is converted to a0return), which surface asENTROPIC_ERROR_INTERNAL— a typed error, so nothing is accepted silently in the corrupt case. The prompt cache is host-memory only and never crosses a process, so no stale blob can reach it. The residual hole is narrow but real and PRE-DATES this bump: a blob whose layout still parses is accepted with no version check, and the seq-scoped KV layout happens to be unchanged for plain-KV models between v2 and v3 (only the cell-ext gate moved fromn_pos_per_embd() > 1tohas_cell_ext()), so this bump does not exercise it. Ifentropic_state_saveis ever promoted past “opaque blob, same pin, same model”, it needs its own header with a pin id — the llama.cpp version constants will not do that job for it. (v2.13.0, gh#148, gh#166)The engine knew and the consumer could not ask — and a documented fail-open is only documented to us (v2.13.0, gh#154). Two findings, one root. First, no
GenerationResultfield had ever reached a consumer.prefill_tokens(gh#144) was serialized nowhere,throughput_tok_sand the speculativen_drafted/n_acceptedwent to a log line and died there,entropic_metrics_jsoncarried onlyLoopMetrics, andiface_generatehands the engine a bare string by design (#49). So every observability field this project has added since v2.9.0 was added for a reader that did not exist, and the one consumer who needed them estimated output volume from drafted/accepted arithmetic and published an upper bound.entropic_metrics_jsonnow carriesgenerations[]— one record per generation, appended at the tail every orchestrated path already shares (record_generation, called from bothgenerateoverloads,generate_streamingand each arm ofgenerate_batch), so a new decode path cannot ship unrecorded the way a new grammar source used to ship unwired. The record is deliberately not a transcript: metric fields only, bounded ring of 64. Second, grammar provenance.GrammarRegistry::get()returns""on a miss, the engine warns, and the decode proceeds unconstrained — documented, and undetectable from outside, because constrained and unconstrained output have the same SHAPE whenever the prompt also describes the shape. The only distinguishing signal was the ABSENCE of aRegistered grammarline, which is not something a consumer can assert on; three days of speculative-decode measurement were published against that state and withdrawn (#59).GrammarSourcegains a fourth member,tier, and the sentinel test caught the addition exactly as designed.tierandrequestdiffer ONLY in reporting — both arrive asGenerationParams::grammarand are applied identically — which is a trap, because the application site comparedsource == GrammarSource::requestand would have silently stopped applying tier grammars, reproducing gh#95 in the fix for its successor. The site now asksis_request_grammar().describe_grammar()reads the SAME two inputsapply_grammar_sourcereads, through the sameresolve_grammar_source, so the record cannot disagree with what the sampler did; a provenance field computed from a parallel rule would be a second thing to keep in sync, and #56 is the catalogue of that going wrong.sourceandresolvedare separate fields on purpose: a key that was NAMED and produced no text is precisely the undiagnosable state, so the naming source is still reported withresolved: false. The fail-open is replaced only where the answer is static. A tier’sgrammar:stem is config, knowable the moment the config is read, soconfig::validate_tier_grammarsrejects an unresolvable one withENTROPIC_ERROR_INVALID_CONFIGnaming the tier, the stem and every directory searched — raised afterthread_frontmatter_samplers(the common spelling is an identity frontmatter key, absent fromTierConfiguntil that step) and beforeinit_orchestrator, so no model loads first, the same placement rule gh#156 established one commit earlier. (Superseded within v2.13.0 — see the amendment at the end of this entry: “knowable” was true and “wrong” was not, and the refusal moved to first use.) A RUNTIMEparams.grammar_keykeeps failing open: it may legitimately name a grammar registered after configure, and that miss is now readable on the record instead. The search-path rule is mirrored, not invented:<config_dir>/grammarsalone when it holds any.gbnf, plus<data_dir>/grammarsotherwise, because the facade’s fallback runs only when the config_dir load registered nothing — listing both unconditionally would accept a stem the registry will not hold. The gate’s first act was to convict this repository. Three shipped identities —scribe,compactor,benchmark_judge— declaredgrammar: grammars/<name>.gbnf, anddata/grammars/has only ever heldconstitutional_critique.gbnf; git history shows the other three files never existed. Those keys were inert from the day they were written, and gh#95 (v2.7.4) “fixed” the threading of exactly this field so it would reachresolve_grammar_keyand silently miss. So the default config had been running three tiers unconstrained while declaring otherwise, and every gate was green. The keys are removed rather than the grammars invented, and a test now walks the shippeddata/prompts/so the next dead key fails in CI instead of in a consumer’s measurements. Both bundled examples were also casualties, and in the informative way:explorerandpychesseach callentropic_grammar_register_fileAFTERentropic_configure_dir, for keys their own tiers NAME — a post-configure registration can only ever run too late for a tier that is validated at configure. They now declareconfig_dir: data, sodata/grammars/*.gbnfis loaded during configure and the runtime registration (which would now collide as a duplicate key) is deleted. That is the residual risk made concrete rather than hypothetical: a tier stem naming a grammar the consumer intends to register after configure is now rejected. The alternative — checking after the registry is built — puts the diagnosis behind a multi-gigabyte load, which is the thing gh#156 established one commit earlier that we do not do. (v2.13.0, gh#154)
Amendment, same version, one commit later: the configure-time refusal is withdrawn, because it made a documented API impossible to use. The residual risk named two paragraphs up was not residual — it was the workflow. entropic_grammar_register and entropic_grammar_register_file both begin with check_orchestrator, so neither can be called until entropic_configure* has returned; registering a tier’s grammar from the host application is therefore necessarily a post-configure act, and refusing at configure left a consumer whose grammar lives in memory (or at a path the engine cannot discover, or is generated at startup) with no legal order of calls at all. The entry above noticed the two bundled examples doing exactly this and read it as two examples needing a fix; they were the sample. The GPU gate then named the real one: tests/model/test_gh95_identity_grammar.cpp — the regression test for the predecessor bug — is that same sequence, and it stopped passing. A gate that breaks the test for the bug it builds on is not reporting a mis-written test. The error was a category error, not a placement error. “Knowable at configure” was true: the stem does not resolve, and the engine can say so. What is NOT knowable at configure is whether that is WRONG — at that instant the only call that could fix it has not become legal yet. So configure now WARNS, naming every unresolved tier, its stem, every directory searched, and the call that resolves it; the refusal lands at first use, in ModelOrchestrator::refuse_unresolved_tier_grammar, where a run SELECTING the tier is the proof that nobody is going to register it. That run returns ENTROPIC_ERROR_GRAMMAR_NOT_FOUND and decodes nothing. The fail-open is still closed — an unconstrained decode still cannot happen silently — and the sequence the C API documents is legal again. Placement inside the dispatch is load-bearing twice over: the gate runs BEFORE get_model, so a doomed run costs no model swap and cannot prefill, and — because it needs no backend — it is provable in a CPU unit test with no GGUF, which is what tests/unit/inference/tier_grammar_gate_test.cpp is. It also forced resolve_grammar_key out of resolve_and_stage (which runs after a model is resolved) and into the gate, so there is still exactly ONE place the precedence rule lives: the gate calls it and then asks tier_grammar_unresolved() about what it recorded, rather than re-deriving the answer. The asymmetry with params.grammar_key survives and is now the clearer for having a reason: a per-call key may name a grammar the caller registers later and the CALLER chose it, so it fails open and reports resolved: false; a tier stem is selected by the ENGINE, so the caller cannot see the miss at all — that is what makes it an error rather than their problem. The bundled examples keep config_dir: data from the entry above: both orders are valid now, and churning them back would only lose a worked example of the discovery path. The general rule: before making a config-time check fatal, ask whether the call that fixes it is legal yet. A validation that is correct about the world and wrong about the clock reads exactly like a correct validation — every gate stayed green, the test suite the check shipped with passed, and only a test that predated the check caught it. (v2.13.0, gh#154)
An ignore rule’s anchor base is an index, not just a regex prefix — and the walk that builds the rule set never obeyed the rule set (v2.13.0, gh#161). A consumer vendoring boost/opencv/rtabmap/pcl/eigen/ceres reported
filesystem.globtaking 87,249 ms for one call.IgnoreMatcher::is_ignoredran twostd::regex_matchagainst every rule for every path — 5,061 rules x 187,855 entries — because last-match-wins appeared to forbid an early exit. Three corrections, in order of how much they explain. (a) Bucketing. EveryRulealready carriedbase, the directory of the.gitignoreit came from, andcompile_patternalready baked^<base>/into both regexes. So a rule fromdeps/boost/libs/geometry/docprovably cannot matchsrc/main.cpp, and the bookkeeping to know that was already on disk —by_base_merely indexes positions in the ordered rule set, so the global source order survives. A path consults the root bucket plus one bucket per ancestor directory: 13 rules instead of 650 in the regression test, 26 regex evaluations instead of 1,300. (b) Descending order, not a precomputed negation map. The plan was to precompute “does any negation follow me” per index and stop when none can. Walking the applicable rules BACKWARDS is strictly better and needs no precompute: last-match-wins means the last matching rule decides, so the first match found walking backwards IS the decision. The k-way merge over the ancestry buckets is a handful of integer comparisons per rule — free against a regex. (c) The discovery walk was the dishonest part.load_nested_gitignorescarried a comment claiming it skipped excluded directories; it walked the entire tree including.git, loading ~200 vendored.gitignorefiles at startup and again on everyset_working_dir. It now prunes the skip list and any directory the rules loaded so far exclude — which matches git, since git cannot re-include anything below an excluded directory. The skip list moved ontoIgnoreMatcherbecause two private copies of it are exactly how discovery came to walk.gitwhile glob and grep pruned it. The ordering consequence, stated rather than fixed:.explorerignoreis layered last so it can override gitignore, so its exclusions are not yet known during discovery and do not prune it. And a bound, because none of the above is a guarantee: the pre-2.13.0 caps counted MATCHES (500 glob, 100 grep), so a pattern matching nothing still visited every entry.filesystem.max_walk_entries(default 250,000) caps the walk itself and, when it fires, appends{"truncated": true, "note": "walk truncated at N entries — narrow the pattern"}as the last element of the result array and logs a warning. A silent truncation would be worse than the hang it replaces: the model would read a partial answer as a complete one. The regression tests assert regex-evaluation counts, never elapsed time — a timing assertion measures the machine, not the code.A documented flag that controlled nothing, and an eager path that skipped its own gate (v2.13.0, gh#157).
ModelConfig::keep_warmwas documented “Pre-warm model at startup” from v1.8.0 to v2.12.2 and read by exactly one site — swap-out, where it picks WARM over COLD. The default tier loaded duringentropic_configureregardless of it, so a consumer had no key that said “load on first use”: two sumac hosts opened by one editor session each loaded the same 4.8 GB GGUF and held ~9.6 GB of an 11 GB card without ever being sent a run. The fix is a new key,models.defer_load(defaultfalse), not a new meaning forkeep_warm— whose default is alsofalse, so repurposing it would have made every existing consumer lazy without their asking, a behaviour change disguised as a doc fix. The more interesting half is what fixing it exposed:activate_default_tiercalledbackend->load_and_activate()directly, so the one load every consumer performs bypassed the residency gate (#57), fired noLoadedevent and recorded no footprint — the residency bookkeeping could see every load except the one that always happened. Both paths now go throughget_model, so eager and deferred differ only in WHEN. Four things assumed a loaded default backend and were corrected rather than documented as limitations: (a) adapter preload moved from init to the activation of the owning model — the init-time version required the base model to be loaded, which is true of exactly one tier, so every tier on a different GGUF logged “model not loaded”, skipped, was never retried, and the later swap failed with “not found or COLD” (a live bug, independent of this issue); (b)entropic_model_has_visionanswers from config (declared capability or mmproj path), because the backend’shas_vision_is set while building the mmproj context during activation and an unloaded tier therefore answered a confident, wrong0; (c)entropic_state_save/_load,entropic_get_logprobs,entropic_compute_perplexityandentropic_adapter_loadlazy-load through the gate instead of throwing “model not active” — each now claims the handle’s turn first (HandleTurnGuard), because a load must not land mid-generation; (d)entropic_speculative_compatstill reports “no main tier loaded” when nothing is resident — left as is, since it is a query whose honest answer depends on residency. Deferred is opt-in precisely so a consumer whose first token latency matters keeps the old behaviour by doing nothing.Weights and conversations have different lifetimes, and the engine only knew how to end both at once (v2.13.0, gh#164). A loaded model stayed in VRAM for the life of the handle:
ModelOrchestratorevicts only when a DIFFERENT tier needs the space, so a laptop host that wanted its 13 GB back had toentropic_destroy— which also drops every session’s conversation, re-runs configure and re-registers MCP servers.entropic_release_model(handle, tier_name /* NULL = all */)unloads and keeps everything else. Three decisions inside it are worth recording. (a) Adapter registrations are PRESERVED. The existing swap-out path callsAdapterManager::unload_all_for_model, which erases the entries — correct for a tier being replaced, wrong for one the consumer intends to bring back, since the next activation would then failswapwith “not found or COLD” (the same failure mode gh#157 found for never-preloaded tiers). Release frees only thellama_adapter_lora*handles (they belong to the model being freed) and leaves the name → path/scale registration COLD;load()re-initialises such an entry in place, while a name that still holds a handle is still refused as a duplicate. (b) It takes the handle’s turn claim, and refuses withALREADY_RUNNINGrather than serialising.swap_mutex_guards tier swaps and residency mutations, NOT generation (orchestrator.h has said so since v1.8.2), so “wait for the mutex” would not have waited for the decode: unloading mid-generation frees thellama_contextthe decode is running on. The claim is the same compare-exchange the six run entry points take (#58/gh#144). (c) Release-all re-ensures the secondary roles at the next cold activation.classify_taskwarns “router not loaded” and falls back to the default tier; nothing reloaded a role on its own, so releasing everything would have silently and permanently degraded routing for the rest of the handle’s life.activate_and_tracknow callsactivate_router/activate_draft, both no-ops when the role is loaded. No idle timer ships: only the host knows what idle means for its users, and a wrong guess unloads a model a user is about to type at.The doubled memory was page cache; the doubled WORK was real, and only one of them was in the report (v2.13.0, gh#148). gh#148 reported “closer to 1.5x the file size” for a partially offloaded model and attributed it to the WARM and ACTIVE residencies overlapping across the reload boundary. That overlap does not exist —
load_gpu_modelhas freed the WARM model BEFORE the GPU reload since v2.7.0 (decision #19’s follow-up), so the two are never simultaneously resident and what the reporter measured was the page cache holding the file it had just read. The waste sitting next to it is not a memory figure at all:load_and_activaterando_load— the WHOLE file,n_gpu_layers = 0— and then immediately discarded that model and read the whole file again with the configured split. One cold activation, two whole-file reads, nothing consuming the first one. Measured with a deterministic counter ofllama_model_load_from_filecalls (the instrumentation shape of #62/gh#161’s regex counter, chosen because RSS and wall-clock both depend on page-cache state — which is exactly why the original report could not be turned into a test): 2 before, 1 after, and the CPU smoke’s activation halved from ~8.7 s to ~4.5 s.do_load_activeis a new virtual whose BASE implementation is the olddo_load+do_activate, so every other backend and every mock is unchanged;LlamaCppBackendoverrides it to read once. WARM → ACTIVE still reloads and always will (decision #19: llama.cpp binds offloading to the model load), and that reload is whatkeep_warmpays for. Two policy decisions travelled with it, both from the v2.12.0 oversized-model work that lived ONLY in the test harness while the engine took config verbatim: (a) typed refusals foruse_mlockbeyondRLIMIT_MEMLOCK(ENTROPIC_ERROR_MLOCK_LIMIT_EXCEEDED— pinned pages cannot be reclaimed, which is what turned partial offload from slow into OOM-killed) and for an offload on a card whose free VRAM cannot hold the compute buffers alone; and (b)gpu_layers: auto, an explicit opt-in that derives the split the harness used to compute privately. Both refusals are floor-gated to models above 10 GB —use_mlockdefaults to TRUE, so an un-floored mlock rule would have refused the everyday case of a CPU-resident 4 GB model on a box with the usual 8 MB limit, a configuration that works. Judging a SPECIFIC partial split is deliberately not attempted: it needs a layer count the admission gate does not read, and guessing it refuses configurations that work — the same asymmetry that makesestimate_footprint_bytesreport a partially offloaded tier as unpriceable rather than inventing a number. Andautoderives the layer split ONLY: the harness also flippeduse_mlockoff behind the operator, which is the silent correction this engine refuses to make.Serialization was an accident of the run guard, so removing it had to make the serialization deliberate — and the audit is the feature, not the lock (v2.13.0, gh#158).
ENTROPIC_ERROR_ALREADY_RUNNINGwas a per-HANDLE compare-exchange (#58/gh#144), so a host serving several conversations from one resident model serialized every turn — and the consumer’s measurement is the argument: 123 tok/s at one sequence against 353 at eight on the same weights via llama-server, because decode is bandwidth-bound and one weight read serves a whole batch. But nothing else serializedllama_decode. Onellama_contextis shared by every session and tier on a GGUF;LlamaCppBackend::active_slot_,residency_, the staged tool arena and the sampler chain are all ONE field per backend;entropic_run_batchopened by clearing the WHOLE KV cache and held a local cancel flag nothing in the tree could set. So the per-handle guard was not merely a policy about turns — it was the only thing making every one of those fields safe, and keying it per session removes that protection from all of them at once. Three consequences, recorded in the order they matter. (a) The lock.ModelOrchestrator::generation_mutex_is the ONE lock on the generation path, held across a wholegenerate*call rather than aroundllama_decode— which is what makes concurrent runs interleave at GENERATION boundaries (a side request waits for the current generation, not the whole multi-iteration turn) and what coversactive_slot_and the arena, which a decode-only lock would leave racing. Order:generation_mutex_→swap_mutex_/records_mutex_→ the backend’stransition_mutex_/mtp_mutex_. It is impossible to invert by construction rather than by discipline: the lock is taken at exactly five sites, all entry points of one class, and no holder of an inner lock calls any of them —get_modeltakesswap_mutex_and RELEASES it before returning, so nobody holds it across a generation. It is RECURSIVE becausegenerate()routes androute()→classify_task()decodes on the router, which is itself a generation entry point; a plain mutex would self-deadlock the first time a run routed. (b) The default is off.concurrent_sessionsshipsfalse. Per-key runs are safe only once every piece of per-handle mutable state a turn touches is per-run or locked, and shipping the concurrency on would make every existing consumer concurrent without their asking — the mistake #63/gh#157 explicitly refused to repeat withkeep_warm. A racy default is strictly worse than today’s honest serialization, which is also why the flag is the ONLY thing that changes behaviour: with it off the guard is handle-exclusive and v2.12.0 semantics hold exactly. (c) The bug the audit found was the binding, not the lock. The session key was a per-handle field read atrun(); making it thread-local so two runs can each answer “which session am I” produced a subtler defect — a binding that outlived its run stayed on that thread and silently captured the NEXT unkeyed run, on any handle. The existing gh#144 tier-switch test caught it, because Catch2 re-runs a scenario per leaf section and the second run inherited the first’s binding. The fix is that the claim IS the binding:try_begin_turninstalls it andend_turnremoves it, so there is no state whose lifetime is not a run’s. External-tool cancellation becomes per REQUEST for the same reason. gh#150’sinterrupt_external_tools()trips every transport at once, which is right for “stop everything” and wrong for “stop session A” — it would hand session B an empty tool result indistinguishable from a real one, which is the defect gh#150 was filed for, arriving through a different door. Threading a token through would changeToolExecutionInterface,ServerManager,ExternalClientandTransport— four signatures across three.soboundaries — for a value already unambiguous from context: a run is a blocking call on the caller’s thread and every tool call it makes happens on that thread. So the token is published per THREAD (RunCancelScope, modelled onHandleLogScope) and the transport polls it beside the latch.entropic_interruptkeeps the latch;entropic_interrupt_sessionnever touches it. And the batch.run_batched_decode’s whole-cache clear and its hard-coded sequence 0 for arm 0 are both invisible to a correctness test — a session whose KV was destroyed still answers correctly, having silently paid a cold prefill — so the fix ships with a counter (kv_full_clear_count(), the instrumentation shape of #62/gh#161 and #65/gh#148) and a pure planner the production path consults, because a helper the code does not call proves nothing. COMPLETING THE AUDIT, AND WHY THE DEFAULT IS NOW ON (v2.13.0, second pass). (b) above said the flag ships off until every piece of per-handle mutable state a turn touches is per-run or locked. That is a finite list, so it was finished rather than deferred, and the default moved with it —concurrent_sessionsnow defaultstrueand remains as a KILL SWITCH, the one-line escape hatch for a consumer who hits a concurrency defect in the field. Resolved in this pass:token_counter_— its memo was anunordered_mapkeyed by the ADDRESS of aMessage, written from aconstmethod with no lock. Two defects in one field: an address is not an identity (the message vector reallocates, the allocator reuses slots, so a hit could answer for a message that no longer exists) and the unsynchronized insert is heap corruption rather than a wrong number. Deleted, not locked —count_textis onesize()and one division, strictly cheaper than hashing a pointer, so the memo was never worth defending.per_tier_metrics_/last_metrics_—metrics_mutex_, and the fold was copy-pasted at two sites (run()andrun_loop()’s tail) so it was extracted first; locking one would have left the other racing.entropic_metrics_jsoncopied the map while a finishing run inserted into it, and an insert that rehashes relocates every bucket under the copy’s iterators. Itsgenerations[]ring (gh#154) was ALREADY correct —records_mutex_, returning a copy — which is the useful contrast: the field added THIS release was safe and the accumulator that has been there since v2.0.6 was not.context_anchors_—anchors_mutex_; handle-wide, but written from INSIDE the loop by thecontext_anchordirective.system_prompt_—prompt_mutex_; written on the API thread underapi_mutexand read on run threads, which have held nothing since gh#109 (v2.9.5) tookapi_mutexoff every run entry point, soapi_mutexnever covered that pair.sandbox_mgr_+ the repo-dir cache —sandbox_mutex_, as ONE unit because the manager is constructed from the cached path. The check-then-emplace was a use-after-free, not a wasted snapshot: two delegating runs both see an emptyoptional, bothemplace, and the second destroys the manager the first already returned.SandboxManager::ensure_base_snapshothas the same shape one level down and gets its ownbase_mutex_— two runs both copying the project tree into onebase_dir_is a file-level race, not duplicated effort, and the lock is held ACROSS the copy because the second caller wants the finished snapshot rather than its own.ConstitutionalValidator’s per-turn fields (current_tier_,current_tool_context_,current_tool_evidence_,current_system_prompt_) — the sharpest find, and one the brief did not name: per-HANDLE members describing a per-TURN thing, set athandle_hook()entry. A mutex fixes thestd::stringrace and leaves the real defect, which is session A’s critique prompt built from session B’s tool evidence and identity prompt. Made thread-local; the one path that legitimately crosses threads,resume_retry()from the consumer’s thread afterpaused_pending_consumer, carries the system prompt forward inPendingValidationState. The decode itself — and this is the gap the first pass left in its own work. ba48877 gave each run a cancel token and taught the agent loop and the MCP transports to poll it, butResponseGeneratorholdsGenerationEvents{&interrupt_flag_, &pause_flag_}, raw pointers to the HANDLE-wide flags fixed at construction, so the per-token poll and the batch cancel poller answered only toentropic_interrupt().entropic_interrupt_session(A)therefore could not stop the generation it named — the longest-running thing a session does. Both sites now OR in this run’s token (generation_cancelled), and the batch poller, which runs on its OWN thread where the thread-local is not installed, captures the token pointer on the run thread before spawning. The pause prompt’s “no injection” path likewise raises THIS run’s token (cancel_current_run()) instead of the handle-wide flag, which used to abort every concurrent session on one session’s declined prompt.pause_flag_stays handle-wide, deliberately. The asymmetry with the interrupt is the argument:interrupt_session(key)can route because the engine owns the map from key to run, whereaspause()is raised from a thread that owns no run and names no key — routing it would need anentropic_pause_sessionthat no consumer has asked for, and every consumer of pause today is a single-session TUI holding one conversation. What WAS wrong is that a fresh turn cleared it unconditionally, so starting run B silently un-paused run A: the same shape as the interrupt defect this issue was filed for. The clear is now conditional on being the only run in flight, which is byte-identical behaviour underconcurrent_sessions: false. TOOL EXECUTION, which was not in the brief and is the finding worth reading twice.StdioTransport::send_requesthas heldio_mutex_across write-then-read since v1.8.7, so two concurrent runs never interleave BYTES on the pipe — the obvious hazard was already handled. The real one is that nothing ever checked that the response line answered the request line. A request can be ABANDONED — a timeout, orrequest_cancelled()tripping mid-read, which gh#158 turns from an exceptional event into a routine one — and the server still answers; that answer sits in the pipe and is read as the result of the NEXT request. Serialized, that was a stale answer to yourself. Keyed, it is a cross-session leak of exactly the gh#150 shape: session A’s interrupt hands session B the content of A’s tool call, and B cannot tell. Two fixes, because one of them is recovery and the other is detection: the transport marks the pipe desynced on an abandoned read and drains orphaned lines before the next write, andExternalMCPClientnow stamps and VERIFIES the JSON-RPC id, returning a typed error rather than another request’s payload.next_id_became atomic in the same pass — a plainint++from two run threads (and from the HealthMonitor’s reconnect thread, which has issuedinitialize/tools/listthrough it since v1.8.7) is a data race, and two requests sharing an id is precisely what defeats the pairing check. What was checked and deliberately NOT changed:ServerManager’s four registry maps have no lock, but two concurrent runs only READ them, and concurrent reads of astd::mapare safe. The writer is a runtimeentropic_connect_mcp_server/disconnectlanding while a turn is in flight — an API-versus-run race that has existed since gh#109 (v2.9.5) removedapi_mutexfrom the run path, is not made worse by keying the guard, and whose honest fix isshared_ptrownership soexecute()can hold a reference across a call it must not hold a lock across. Recorded here rather than half-fixed.ToolExecutorneeded nothing: its only shared mutable state ishistory_(its ownshared_mutex) andhistory_seq_(atomic); everything else isLoopContext, which is per-run already. ThreadSanitizer is the proof, and getting it to run was itself a finding. Thetsanpreset existed and could not build: on Linux >= 6.5 the kernel hands out 32 bits of mmap entropy and GCC’s TSan aborts withunexpected memory mappingbeforemain(), socatch_discover_tests— which RUNS each test binary at build time — failed the build outright.sysctl -w vm.mmap_rnd_bits=28fixes it and needs root;setarch -Rdisables ASLR for the process and needs nothing, so the preset now setsCMAKE_CROSSCOMPILING_EMULATOR=/usr/bin/setarch;-R, which both Catch2 and ctest honour, scoped to that preset alone. The run found two races the CPU suite cannot see, and neither was in the state this audit set out to lock.StdioTransport::close()closed the three fds and THEN joined the stderr pump, soclose_fdwrotestderr_fd_ = -1while the pump was still reading it — a data race on an int and a use-after-close waiting to happen, since a freed fd number is immediately reusable by another thread’sopen(); the join now precedes the closes. AndMockInference, the test HARNESS, raced ongenerate_call_count++andresponse_queue.erase()once one engine served two runs — worth recording because, left alone, a harness race reads as a finding about the engine. After both, 15/15 gh#158 tests pass with zero warnings, and the newly locked engine state is clean. THE BUILT-IN SERVERS’ OWN STATE (v2.13.0, third pass). The first two passes locked the engine and the external transports and never opened the in-process servers — andconcurrent_sessions: truemeans every UNBOUND session on a handle shares its ONE default server set, so two sessions can be inside the sameFilesystemServerat the same moment. Three findings, and the one worth reading twice is a wrong answer, not a crash. (1)FileAccessTrackerhad no lock.read_fileinserts into anunordered_mapthatwrite_file/edit_filelook up; TSan: 7 races inrecord_read. A leaf mutex inside the tracker. (2) The sandbox swap was exclusive against every other swap and against nobody’s tool calls. gh#160’s facaderecursive_mutexwas taken byScopedSandboxentry and restore only, so while session A’s isolated delegation had the default set re-rooted, session B’sread_file("notes.md")andbash cat notes.mdresolved INSIDE A’s sandbox — deterministically, the test readsMARKER-sandboxback — and B’s writes would have landed there and shipped in A’s patch. The swap itself was also an unsynchronizedstd::filesystem::pathwrite plus anIgnoreMatcher::loadracing B’sresolve_path/is_ignored/ bash’s default cwd (4 TSan races in the deterministic scenario, 13 under swap churn, where all 30 of B’s read batches saw the sandbox in at least one of their two calls). So the answer to “does B wait, read A’s sandbox, or race?” was both of the last two. The fix isToolRootLockon theServerManager: SHARED around every in-process and plugin dispatch, EXCLUSIVE from sandbox entry to restore (enter_working_dir/leave_working_dir, andset_working_dir_allfor its own duration), re-entrant for its owner, and the owner passes through its own shared side — the sandboxed child’s calls are the ones that SHOULD see the sandbox. B now WAITS, and then resolves against its own root; the wait is logged by tool name before and after, so a stall behind another session’s delegation is not mistaken for a slow tool. External servers take nothing — the swap never moves them. The facade’ssandbox_swap_mutexandEntropicWorkspace::swap_mutexare deleted: one lock, living with the state it guards, and one perServerManageris still one per workspace. The honest cost: underdelegation.isolation: sandbox(defaultnone) other sessions’ in-process tool calls on the SAME server set stall for the length of a sandboxed delegation. The parallel path is a workspace per session (gh#166). A per-call thread-local root would give the built-ins back their parallelism but not the dlopen plugins, which hold their own cwd behind a C ABI that cannot see a thread-local — two mechanisms for one invariant, so not done. Lock order:ToolRootLockis OUTERMOST — exclusive, it is held across a child’s whole run, soToolRootLock → generation_mutex_ → swap_mutex_ / records_mutex_ → transition_mutex_ / mtp_mutex_; shared, it is taken only at tool dispatch on a run thread that holds none of those norapi_mutex, and nothing inside a dispatch reaches a generate entry point, so no inner-lock holder ever waits on it. No shared→exclusive upgrade can happen on one thread: a delegation starts after its tool batch returns (dispatch_pending_or_halt), never insideServerManager::execute. (3)TodoTool::items_— outside the three servers the brief named, found by the same sweep. The entropic server keeps its todo list on the tool object, one per server set; two sessions appending racedstd::vector::push_backand the TSan run ABORTED with an impossible allocation size inside it — heap corruption. The action and the render now run under one hold of a leaf mutex. Two semantic questions are left open, deliberately, because they are design and not locking: the read-before-write tracker and the todo list are per SERVER, so session B may overwrite a file only session A read, and B’s todo result lists A’s items — the per-handle-describing-a-per-session-thing shape the validator fields had, now locked but not re-scoped. RE-SCOPED PER SESSION (v2.13.0, fourth pass — the user’s decision on those two questions). Both are now keyed by the running session. The key is the one the call ROUTED on:ToolExecutor::execute_toolpublishesLoopContext::session_keyto its own thread (RunSessionScope) for the duration of the dispatch, and the tracker and the todo tool readcurrent_run_session()— so the state is filed under exactly the value that chose the server set, rather than a second notion of “which session” that could drift from it.HandleTurnGuardalready publishes the same key for the whole run; republishing it at dispatch is what makes a directToolExecutordriver (the white-box tests) and a delegated child agree with production by construction. A delegated child shares its parent’s key (build_child_context/build_resumed_child_contextcopy it), so a child’s read legitimately unlocks the parent’s write — kept deliberately, and pinned by a test that drives a realDelegationManager. Bounded growth: a session’s entries are released when its conversation ends —entropic_session_drop,entropic_session_context_clear,entropic_session_context_set(a restore replaces the history the reads described) andentropic_context_clear(the active session) — throughrelease_session_tool_state, which visits the default set AND every workspace’s, because which set a session touched depends on when it was bound and releasing an absent key is free. The model-facing argument for releasing on clear is the same as the correctness one: read-before-write means this conversation has seen the file, and a cleared conversation has not. Mechanism: aSessionScoped<T>map (one leaf mutex, apeekthat never allocates — asking “did this session read X?” must not grow the map for sessions that never read) and aSessionStateOwnermixin thatServerManager::release_sessioncross-casts to. Not a virtual onMCPServerBase: its vtable is plugin ABI (i_mcp_server.h), so a server opts in beside the base instead.release_sessiontakes noToolRootLock— the state is behind its own leaf lock, and waiting on the root lock would stall an API call for a whole sandboxed delegation. Checked while here, not changed:AgentEngine::context_anchors_is handle-wide and re-injected at every run start, which would leak one session’sfile:/todo_stateanchors into another’s turn — but tool-emitted anchors never reach it (build_directivereturns nullptr forcontext_anchor, so the directive is dropped), so there is nothing to leak today. If that path is ever wired, the map must become per session first.DelegationManager::set_todo_callbacks(save/fresh/restore around a child) has no caller insrc/, so a child’s todos land on the parent session’s list — the pre-existing behaviour, now per session.Server
State
Written by
Verdict
filesystem
root_dir_ctor;
set_working_dir(sandbox swap)was race + wrong root →
ToolRootLockfilesystem
ignore_(rules_,by_base_)ctor; reload in
set_working_dirwas race →
ToolRootLockfilesystem
IgnoreMatcher::regex_evals_(#161)every match
atomic; cumulative across sessions (instrumentation only)
filesystem
glob / grep
WalkBudget(#161)per call
per-call (stack)
filesystem
tracker_read_filewas race → leaf lock (46d3474); was per SERVER → per SESSION, released with the conversation (fourth pass)
filesystem
config_— mode,outside_root_allow/_deny(#72);max_read_bytes_ctor
immutable after construction
filesystem
approver_/approver_data_(#72)configure
approver_mutex_, copied and called outside it; the facade slot behind it ispath_approval_mutexbash
working_dir_ctor;
set_working_dirwas race + wrong root →
ToolRootLockbash
timeout_, the toolctor (
mcp.bash.timeout_seconds, #73)immutable; ENFORCED since #73 (was never read)
git
repo_dir_ctor;
set_working_dirwas race + wrong root →
ToolRootLockall
tool objects,
registry_,name_ctor
immutable after construction
plugin
the plugin’s own cwd
set_working_dirPluginServer::call_mutex_(bytes) +ToolRootLock(which root)diagnostics
root_dir_ctor
immutable — never re-rooted (no
set_working_dir), and NOT a sandbox leak (verified, fourth pass): both tools,diagnosticsandcheck_errors, are stubs that discard their arguments and return a fixed “not yet connected (v1.8.7)” string, so nothing a sandboxed child calls reads or writes any root;root_dir_is read only by the ctor’s log line and byroot_dir(), which nothing insrc/calls. Must join theToolRootLock/set_working_dirdiscipline the day an LSP backend makes it touch files. (Separately: both stubs are advertised to the model by default,enable_diagnostics: true.)entropic
TodoTool::items_→lists_todowas race (heap corruption) → leaf lock (095a2f2); was per SERVER → per SESSION, released with the conversation (fourth pass)
entropic
state_provider_, tier listsconfigure / ctor
immutable after construction
manager
PermissionManagerlistsctor
immutable in production —
add_permissionhas no callerA read nobody could write back is a read that was allowed to be lossy (v2.13.0, gh#165). gh#144 gave consumers
entropic_session_context_getandentropic_session_listand no counterpart, so a session could be read out but not restored: a host that stopped the engine to free VRAM lost every conversation, and the only way to put messages back —entropic_run_session— appends and then RUNS, re-executing the whole agentic loop per message, tool calls included.entropic_session_context_setis the missing half, and pairs with #64/gh#164 to give weights and conversations independent lifetimes, which is what a long-running local assistant actually needs. The interesting finding is what the missing write was hiding.facade_json::serialize_messagesemitted ONLYroleandcontent— it droppedmetadataandcontent_parts— and that had been invisible for eighteen months because nothing ever fed the output back.metadata["tool_name"]is read bycontext_manager(twice),compaction, and the engine’s tool-result folding;metadata["is_context_anchor"]marks the messagesreinject_context_anchorspreserves. A restore through the lossy serializer would therefore have produced a conversation the engine could no longer reason about — tool results indistinguishable from prose, anchors that no longer re-inject — and every assertion about message COUNT and CONTENT would still have passed. This is #57’s rule in a new form: a serializer is a contract with a reader, and a format with no reader has never been tested. The byte-identical get→set→get assertion is the shape that catches it, because it is the only assertion that fails on a field nobody thought to check. The emission is ADDITIVE, deliberately: the new keys appear only when there is something to carry, andcontentstays a STRING on every message, so a consumer reading role/content sees byte-identical output for every message it has ever seen. Parts ride in their owncontent_partskey rather than turningcontentinto the inbound multimodal ARRAY shape — the alternative would have been lossless and would have broken every consumer that readscontentas a string. Two scoping decisions. (a) The refusal is per SESSION, not per handle: replacing the conversation a turn is appending to is the race, and a busy HANDLE is not.conversations_gains its own mutex, which also closes a latent race that predates this issue — the session APIs takeapi_mutexbut NOT the run guard, soentropic_session_context_clearand_dropcould already mutate the map mid-turn. (b) What a restore invalidates, and why that is sufficient. The session’s resident KV tokens and its sequence slot are dropped. Warm-keep would have been correct without this —warm_keep_cutmatches TOKENS andseq_rms the divergent tail, so reuse is prefix-correct whoever produced the prefix — and the invalidation is kept anyway, because that gate is token equality rather than conversation identity: a future change that coarsened it (reuse by message count, by a conversation hash) would silently decode a restored session against the history it replaced. The prompt cache needs nothing, being keyed by prefix hash — a changed prefix misses, an identical prefix hits on identical tokens. The cost is one cold prefill on the restored session’s next turn, which is exactly what an LRU-evicted session already costs. The issue’s own table was wrong and is corrected here rather than quietly: it listsentropic_session_listas returning the message array for all sessions; it returns[{key, messages: <count>}].A callback with no caller is not a feature with a bug — it is a documented guarantee that was never in force (v2.13.0, gh#160).
DelegationManager::set_dir_swapshipped in v2.1.5 and, insrc/, was never called by anything. All threeScopedSandboxsites therefore took theswap_dir_fn_ == nullptrbranch, so every delegated child ran against the REAL working directory while the engine dutifully snapshotted a project tree, diffed it against itself and delivered a 0-byte patch — andentropic.htold consumers “the engine never writes to the user’s project directory; the consumer applies patches with user consent” the whole time, whiledata/tools/entropic/delegate.jsontold the MODEL the opposite (“Filesystem state IS shared via the parent’s worktree (no isolation)”). Two documents, one codebase, opposite claims, and the tool JSON was the accurate one. The fix is the switch, not the default.delegation.isolation: none|sandboxdefaults tonone, which is what every release since v2.1.5 actually did; turning it on by default would park every delegated edit inpending/<id>.patchfor the many consumers that register noon_completecallback, which is a silent loss of work, not a safety improvement. Withnonethe sandbox is not constructed at all — the wasted snapshot gh#160 reported disappears along with the 0-byte patch that was its only product, the one behaviour that is NOT byte-identical to v2.12.2 and the one nobody can have depended on. Three findings sat underneath the missing call. (a) The snapshot source was the ENGINE’s repo dir while the tools usedmcp.working_dir; those are different paths for any consumer whose launcher cwd is not the target repo, which is the reporter’s exact configuration, so even a wired swap would have diffed the wrong tree. The root now comes from ONE seam,AgentEngine::resolve_session_root(session_key), which the facade answers because only the facade can see theServerManager— the same shape as decision #23’sTierResolutionInterface, and the single function gh#166 re-points at a named workspace. (b) Sibling delegations at one depth both mintedd<depth>, so the secondcreate_sandboxreused the first’s directory andpending/d1.patchoverwrote the first’s patch: a lead fanning out to two specialists silently kept one result. Ids are minted from a counter on the engine-scopedSandboxManager, because theDelegationManageris per-delegation and cannot count its own siblings. (c)ScopedSandboxrestored to the repo root unconditionally, so a NESTED delegation handed the outer child the user’s working tree the moment the inner one finished — the guarantee inverted exactly where it mattered most. The restore target is now the parent’s active root, carried onLoopContext::active_root. The concurrency consequence is the honest cost.set_working_diris one field on each in-process server, andconcurrent_sessionsnow defaults true (#66), so two sandboxed delegations on one handle would interleave their swaps and write into each other’s sandbox. The facade takes a per-handle recursive swap lock fromScopedSandboxconstruction to destruction: sandboxed delegations serialize, unsandboxed ones are untouched, and gh#166’s per-workspace server instances are what give the parallelism back. (Amended by #66’s third pass: that lock now lives on theServerManagerasToolRootLockand tool dispatch takes it too, shared — a swap lock only swaps took left another session’s tool calls resolving inside the sandbox.) And what cannot be contained is refused rather than downgraded. An external stdio/SSE MCP server is a separate process with its own cwd; nothing the engine does moves it. If a sandboxed child can reach one whosetools/listdoes not assertreadOnlyHint: true— absence is not a promise — the delegation is rejected with a typed message naming the tool, because a containment claim that is quietly false is worse than one the consumer is told it cannot have.The API made the expensive mistake easy and the cheap one impossible (v2.13.0, gh#162). A lead that had already cited
app/include/b12/control/slam/SlamConfig.hppdelegated a follow-up about the same subsystem with no path in it, because there was nowhere to put one:taskwas the only channel. The read-only child could not search, guessed atsrc/slam, and answered from inference about a file that does not exist — 553 s against 144 s for the same model and tools with no delegation, and the second question unanswered. A prompt rule is not a fix for a schema gap, as the reporter found: the rule helped and the schema still accepted the contextless call. Sodelegateandpipelinetakecontext: [{path, lines?, note?}], rendered as a[CONTEXT]block AHEAD of the task in the child’s opening message — a small model that reads the task first has already started searching by the time it reaches the references. References, never excerpts. Inlining file content would copy the parent’s context into the child’s, which is the cost delegation exists to avoid; what the child cannot do cheaply is FIND the path again, and that is the only thing being handed over. The same block is written into the delegation’s storage row, so “what did this child know” is answerable after the fact rather than inferred from a transcript. Structural inability gets a structural refusal. A tier configuredrequires_context: true— a reader withread_fileand no search tool — refuses a contextless delegation at the TOOL boundary, as an error result with no directives. That placement is the point: the lead sees it inside the same turn and can re-issue with a path, where an engine-side rejection would arrive as a user message after the directive round trip, and a burned child loop would arrive as a confident wrong answer. A pipeline is refused the same way if ANY stage requires context, because one context list seeds them all. Andresume_delegationnow takes a tier. Reaching it used to requirefollowupfirst purely to learn a storage id — two round trips on a slow local model before any work starts — sotargetresumes that tier’s most recent COMPLETED delegation, with the id resolved by the engine at admission because the tool cannot see storage. Writing the test found the wiring bug that made the feature a no-op:execute_pending_delegationentered the resume path only when the id was non-empty, and resume-by-target arrives with it empty BY CONSTRUCTION, so the request silently ran as a cold delegation. Explicitly rejected: auto-scraping the parent’s file:line citations into every child. It looks like the same feature and is not — the lead’s citations are a mix of what matters and what it happened to touch, and a child that is handed the second kind reads it as instruction. The lead choosing what to pass is the signal; harvesting would destroy it.One resident model, many repositories — and the routing key was already on the thread (v2.13.0, gh#166).
mcp.working_dirwas fixed at configure time, so serving a second repository meant a second handle and a second copy of the weights: impossible for a 13.27 GiB model on a 16 GB card, and unnecessary, because the model has no reason to care which repository a session is about. A workspace is{root, its OWN built-in + plugin server instances, its own external servers, its own sandbox and swap lock}, and the reason it is an OBJECT rather than a path is that a server holds one working directory:FilesystemServer,BashServerandGitServertake their root at construction, so two repositories cannot share one set, andset_working_diris a field write that gh#160 already had to serialize. Weights, tiers and identity stay handle-wide, which is the entire point. Binding is once. A session that already holds messages is refused a rebind: its conversation cites paths relative to the root it was built in, and silently re-rooting it would make every one of those citations wrong without a single error. An UNBOUND session resolves to the handle’s default servers, so a consumer that binds nothing sees no change at all. The interesting constraint was the tool PROMPT. Tool dispatch could route onLoopContext::session_key, which it already carries, but the callback that answers “which tools does this turn see?” isget_tool_prompt(tier)oni_inference_callbacks.h— an interface header that does not change without a proposal. gh#158 had already solved this exact shape for its cancel token and written down why (decision #66): a run is a BLOCKING call on the caller’s thread, and everything it does happens on that thread. So the session key is published per thread byHandleTurnGuardand read by the facade’s tool-prompt callback —RunSessionScope, the same mechanism asRunCancelScopeandHandleLogScope, not a new one. gh#160 paid for itself here. Itsresolve_session_root(session_key)seam was re-pointed and nothing else in the delegation path moved: sandbox roots, restore targets and the readOnlyHint refusal all followed, and the per-handle swap lock became per WORKSPACE, which is what lets two sessions in different repositories delegate in parallel instead of serializing on each other. What is deliberately not done. Per-workspaceapp_contextis a follow-up. A workspace’s external servers now spawn withcwd= its root (posix_spawn_file_actions_addchdir_np, with the pre-2.13.0 inherit-the-host’s-cwd behaviour and a log line where that call is unavailable) and connect at workspace creation, so theirreadOnlyHintannotations already exist by the time gh#160’s delegation gate reads them — no lazy spawn at the gate. Metadata lookups inToolExecutor(schema, permission level, duplicate-skip) still consult the default manager: they are workspace-invariant for the built-ins and fail SAFE for anything else (unknown tool ⇒ WRITE required), whileexecute— the call that touches the filesystem — routes.A prompt that cannot fit the tier context is REFUSED, before any decode (v2.13.0). The release gate for this version staged 27 tools (18,594 bytes) into a tier configured
context_length: 2048, rendered 5,026 tokens, and llama.cpp answered every turn withDecode chunk failed (slot=0, start=287, off=1536, chunk=512)andCache restore failed, falling back to full prefill— while forty assertions in that test passed. The engine knew both numbers and proceeded anyway. The check lives inLlamaCppBackend::run_prefill_cached, which is the one point every text decode path reaches immediately after tokenizing its render and the last point beforellama_decode: it is the earliest place holding BOTH the rendered prompt size andcontext_length, and by the time it runs the engine’scheck_compactionandprune_old_tool_resultshave already done everything they can, so what it measures is the IRREDUCIBLE prompt. The staged tool block is the part compaction provably cannot shrink — it is rebuilt from tier config on every render. The rule is the unarguable one: refuse whenprompt_tokens >= context_length, i.e. zero positions left to emit into. It deliberately does NOT reserve room formax_tokens; a prompt that fits but leaves less headroom than the caller asked for is a “length” finish, and refusing it would break every caller that passes a generousmax_tokensagainst a small window. The error names the knob, not just the total.ENTROPIC_ERROR_EVAL_CONTEXT_FULL(“Sequence exceeds model context window”, v1.9.10) already meant exactly this, so no new code was added to the public header; the message carries the token count, thecontext_length, the overshoot, the largest contributor and the per-part breakdown, because tool block / system prompt / history have three different fixes. Explicitly rejected: trimming tools, truncating the prompt, or raising the context to fit. All three are silent clamps, and a silent clamp is what made this cost a release gate instead of a config edit. The refusal is terminal for the loop, carried asfinish_reason: "context_overflow"rather than"error":"error"is not terminal, so it fell through to the empty-turn ladder, which appends “you must end every turn with exactly one tool call, retry” — making a prompt that already did not fit LARGER — three times, and then reportedzero_tool_calls_with_explicit_completion, sending the operator after a model that was never given a chance to answer.A boundary nobody chose is not a boundary — outside-root file access now asks, and the answer can be written down (v2.13.0).
mcp.filesystem.allow_outside_rootwas a bool whose C++ default wasfalse, butdata/default_config.yamlshipped ittrue— and the bundled default is what every consumer without its own config runs, and what seeds an auto-created~/.entropic/config.yaml. So the effective default gave the model unconfined READ and WRITE of the whole filesystem throughread_file,write_file,edit_fileandlist_directory;ef6516dhad already had to force workspaces back to confinement because that default let one workspace read another’s files. The user’s design, implemented as ratified: (1) the key is tri-state,true|false|optional, withtrue/falseparsing to exactly their old meaning andoptionalthe default in BOTH the C++ type (OutsideRootAccess::optional) and the bundled YAML; (2) underoptionalan escaping path goes to the host’s approver with the canonical path, the root, the fully-qualified tool and READ/WRITE, and with no approver registered the call is refused with a typedoutside_root_approval_requiredmessage that names the path and the three ways to configure access — fail loud, never open; (3) two lists,outside_root_allow(pre-approved, no prompt) andoutside_root_deny(always refused, even undertrue), deny beats allow beats the tri-state, matched by canonical SUBTREE through the samelexically_relativetest the root uses,~-expanded, with a relative entry or an unknown mode failing the config load; (4) a named workspace’s servers stay HARD-confined —confined_mcp_config()forcesfalseAND clears the allow list, and the approver is wired onto the handle’s default set only, so a sibling workspace can never become “just approve it”; (5)permissions.auto_approvedoes NOT approve a root escape — it exists to skip per-tool permission prompts, not to widen the filesystem boundary, and an auto_approve host that wants outside access says so withoutside_root_alloworallow_outside_root: true. Item (5) was the implementing session’s call, not the user’s, and is recorded as such so it can be overruled. There was no approver to reuse. The brief assumed the tool executor’son_tool_callwas one; it is an internalEngineCallbacksslot that returnsvoid, cannot deny (check_approvalsetsapproved = trueafter calling it), and has no facade setter, so no consumer could ever register it. A decision surface therefore had to be added:entropic_set_path_approval_callbackwithent_path_approval_request_tand the existingent_decision_t, stored on the handle (REQ-API-010: pre-configure registration survives) and read per call by a facade thunk installed on the default set’sFilesystemServer. It is deliberately scoped to the filesystem boundary rather than retrofitted into a general per-tool approval API, which is a different and larger design. Refusals are still thrown, not returned as structured JSON like the other filesystem errors, becauseMCPServerBase::execute’s barrier is what skips the ContextAnchor on a refused read (gh#143); each new refusal leads with a stable type token and keeps the pre-2.13 “Path escapes project root:” phrase, and legacy falseis byte-identical. The lists govern outside-root paths only — the literal design — so a deny entry inside the root is WARNED about at server construction and on every re-root rather than silently doing nothing. Not migrated: a~/.entropic/config.yamlauto-created from an older bundled default still saystrue, explicitly, and keeps meaning it; the server logs that posture at WARN.A tool that runs arbitrary shell commands had a timeout on paper and a safety claim in a comment, and neither was in force (v2.13.0).
BashServer::timeout_was stored, logged and never read —popen()offers no handle to stop a command — sosleep 30held the tool call, the run thread and every lock above it for 30 s, and nothing could be configured becauseinit_builtinsnever passed a value either.bash.hmeanwhile said the server “blocks dangerous commands” and “enforces timeout”. Both claims are now honest. The timeout is ENFORCED: each command is/bin/sh -cspawned (posix_spawn,POSIX_SPAWN_SETPGROUP) as the leader of its OWN process group; on the deadline the whole group isSIGKILLed and the shell reaped, and the model gets a typed{"error":"timeout", message, timeout_seconds, elapsed_ms, output}naming the limit and the elapsed time and keeping the partial output — a bare “timed out” invites a retry of the same command. The exit is detected withwaitid(WNOWAIT)so the shell stays a zombie, and therefore keeps its pid — which IS the group id — until after the group kill: a reaped leader’s pid could be reused, and the kill would land on an unrelated group. The same kill runs on a NORMAL exit, because the requirement is that a tool call leaves no processes behind:cmd &used to outlive the call, and a background child that inherited stdout held the read loop open for its whole life (measured:sleep 25 & echotook 25 s to return; now 0.01 s, child dead). A process that deliberately leaves the group (setsid) escapes by design, and its output is abandoned after a 2 s drain grace with a warning. The denylist claim is deleted, not implemented. Nothing ever filtered commands, and a pattern denylist on free-form shell is trivially bypassed; command gating is the permission layer (permissions.allow/deny, keyed byget_permission_pattern) and tool approval, and the header now says so. Two side effects, both deliberate: stderr is captured for EVERY command, not only where the command’s own trailing2>&1reached (a non-final command’s stderr used to go to the host’s terminal), and stdin is/dev/null(a tool call is not interactive and must not read the host’s terminal). The implementing session’s call, recorded so it can be overruled:mcp.bash.timeout_seconds(default 30, the value the constructor always had;>= 1or the config load fails — no silent clamp, and 0 does not mean “unbounded”) is NEW. The brief assumed a configured timeout existed; none did, and enforcing a hard-coded 30 s with no knob would turn every build or test suite run through bash into a kill.mcp.server_timeout_secondswas NOT reused: it has been parsed since v1.8.1 and read by nothing, its name does not say which server, and giving a vague key a specific meaning would be a second undocumented behaviour — it is left inert and labelled so inconfig.h. Not done: the bash call does not yet poll the per-run cancel token (current_run_cancelled(), #66), soentropic_interrupt_sessionstill waits for a running command up to its timeout — the timeout is now the bound that interrupt previously did not have.A performance assertion is gated on the condition the performance depends on, not on which test is running (v2.13.0, gh#153). The gh#153 matrix measured MTP at +42.8 % on a fully GPU-resident E4B and −0.92 % on an A4B at 18 of 30 layers, on the same card, the same engine and the same
n_draft(#42). One pinned threshold would have to be wrong for one of them, and the tempting fixes are both bad: assert the win only in the case that shows it (the rule then encodes which model is under test, not what MTP does), or lower the bar until both pass (the E4B stops being a regression test). The rule is instead SELECTED, per run, from what the engine RESOLVED: fully resident → MTP must CLEAR the same-config floor; partially resident → MTP must only not be materially WORSE than plain, and no win is claimed. Residency is read fromgpu_layersAFTER admission — whereautohas already become a number (#65) and-1still carries llama.cpp’s “every layer” — againstllama_model_n_layer; the YAML string is never consulted, because-1andautostate an intent and only one of them survives contact with the card. A layer count that cannot be read fails the run rather than selecting the weaker rule (#43’s fail-loud principle: guessing the gate is how a gate stops being one). Amended (v2.13.0, gh#153 #42(iii)): residency is about WEIGHTS, and a layer count alone cannot report it.cpu_moe_layers(#75) places a layer’s routed-expert FFN tensors on the host while that layer’s attention, KV, router, shared/dense FFN and norms stay on the card, so a tier atgpu_layers: 30, cpu_moe_layers: 30reports 30 of 30 layers resident while the large majority of a 26B-A4B’s bytes are in system RAM — and the rule as first written would have asserted the STRICT, fully-resident bar on it, which is precisely the misreading this decision exists to prevent.fully_residenttherefore requirescpu_moe_layers == 0as well, and the rule is deliberately coarse: ANY expert offload disqualifies, because “the first N layers” is not “N layers’ worth of experts” and a resident FRACTION that counted bytes would need GGUF tensor metadata the engine reads nowhere — a coarse “not fully resident” is honest, an invented fraction would not be.cpu_moe_layersis recorded beside everyresident_fraction(human table, config block, every arm row,effect),offloadcarries a+experts_hostsuffix sofull+experts_hostcannot be skimmed asfull, the printed RESIDENCY block states in words that the experts are host-side, and the summary schema isentropic.gh153.mtp-bench/3. BOTH rules’ outcomes are computed and printed on every run with the asserted one marked, and the resident fraction is recorded beside every figure in the human table AND inbuild/test-reports/bench/gh153_mtp_{e4b,a4b}.json, because the number means nothing without it — the same A4B on a 12 GB card is still partial, at a better fraction, and must report a BETTER number under the SAME rule rather than a different rule. The tolerance in the partial direction ismax(floor, 5 pp), the same quantity as the clearing rule’s margin read backwards: on the run that fixed #42 the floor was 1.00 % and the effect −0.92 %, which a bare-floor bound would have passed by 0.08 pp — not a margin, a coincidence. The general rule behind it, extending #59: a performance claim must record the configuration it was measured in (#59), and a performance ASSERTION must additionally be conditioned on it — otherwise the gate silently becomes a claim that the condition always holds, which is exactly how #42’s Pascal sentence outlived the default it was taken under and read as a property of the hardware for four minor versions. (v2.13.0, gh#153, gh#167)Whole-layer offload is role-blind, so the prototype that isn’t is a config key and a default of OFF (v2.13.0, gh#153 #42(iii)).
gpu_layersplaces a layer wholly on the device or wholly on the host. On a model that does not fit, that spends VRAM on rarely-touched routed-expert weights while exiling attention — and its KV — to system RAM. The measurement is #42(b): Gemma 4 26B-A4B QAT (14.25 GB) on an 11 GiB GTX 1080 Ti resolvesgpu_layers: autoto 18 of 30 layers, runs at 18.7 tok/s, and MTP — worth +42.8 % on the fully resident E4B — is worth nothing there (−0.92 % and +0.82 % across two runs against a same-config floor of 0.5–1.0 %). Published practice is unanimous about the direction (KTransformers, Fiddler ICLR’25, mixtral-offloading): keep attention, KV and the shared/dense path resident and push only routed-expert FFN weights to the host.models.<tier>.cpu_moe_layers: Nexposes exactly llama.cpp’s-ncmoe/--n-cpu-moe, and is named for it on purpose — the mechanism (llama_model_params::tensor_buft_overrides), the semantic (“the FIRST N layers”) and the tensor-name patterns are upstream’s, so an operator who has read llama.cpp’s documentation transfers it without translation and a future-cmoe/-ncffnsibling has an obvious name. The pattern tail is copied verbatim from the vendoredLLM_FFN_EXPS_REGEXrather than inferred, and a CPU unit test includes<common.h>and asserts the two are byte-identical, because a stale pattern matches nothing and offloads nothing while every other gate stays green. It was checked against the gemma4 MoE arch specifically, not assumed from DeepSeek naming: at this pinsrc/models/gemma4.cppcreatesffn_gate_exps/ffn_up_exps(or the fusedffn_gate_up_exps) andffn_down_exps,llama-model.cppattaches a per-expert.scaleto each, and the test runs the assembled patterns through the samestd::regex_searchllama-model-loader.cppuses against those literal names — and against attention,attn_*_norm, the routerffn_gate_inp, the dense/shared FFN, every*_shexp, the norms and the embeddings, none of which may match.
The lifetime is the trap, and upstream’s answer is not available to a library. llama_model_tensor_buft_override holds a const char*; llama.cpp copies neither the array nor the strings, storing the pointer and dereferencing it per tensor per pattern throughout placement. llm_add_n_cpu_ffn_overrides keeps its strings in a function-local static std::list<std::string> that is never freed — fine for a CLI that loads one model and exits, wrong for an engine that loads, unloads and reloads across many handles. ExpertOffloadOverrides owns its strings instead, fills them ONCE so no reallocation can invalidate a c_str(), appends the {nullptr, nullptr} terminator llama.cpp’s walk requires, and deletes copy and move so “this object contains pointers into itself” is enforced rather than reasoned about. It is constructed in the scope that performs the load, at both call sites.
Refusals are split by what can be known when. Configure time, purely, with the tier named: a negative count (there is deliberately no “all layers” sentinel — -1 means “every layer” for gpu_layers only because llama.cpp defines it so, and nothing defines it here); gpu_layers: 0 (the whole model is already host-side, so the knob would be a no-op an operator explicitly asked for); and gpu_layers: auto, because the gh#148 admission math prices a layer as a WHOLE layer and has no model of expert placement, so the split it derived would not describe the load being performed. Load time, because they need GGUF metadata entropic reads nowhere else: a model that declares no experts (<arch>.expert_count absent or 0 — otherwise the operator measures the technique instead of their mistake), and a count beyond the block count (not clamped; a count that cannot be honoured is an error, not a preference). The load-time pair costs one wasted read to refuse, which is the right trade against a configuration that quietly placed nothing.
Deliberately NOT done, and this is the boundary of the prototype. The residency/admission footprint math is untouched: estimate_footprint_bytes and gpu_layers: auto still price whole layers, so a prototype user states gpu_layers explicitly and that combination is refused rather than approximated. Nothing here is measured — the knob exists so the experts-only split CAN be measured against #42(b)’s 18-of-31 baseline, and whether it ships as a supported feature in v2.13.0 or v2.14.0 is that measurement’s to decide. The engagement signal is a load-time INFO line plus llama.cpp’s own load_tensors: buffer sizes shifting from the device buffer to CPU_Mapped at an unchanged gpu_layers; at DEBUG llama.cpp names every tensor it overrode. Absent the key, no override array is built at all and tensor_buft_overrides stays the nullptr llama_model_default_params() already carries — byte-identical to v2.12.2, which is why no green gate from this release had to be re-run. (v2.13.0, gh#153)
The measurement case, and how a prototype knob is held to having done something. [mtp-a4b-experts] runs the same four arms, the same floor and the same rules as [mtp-a4b] on the same A4B and the same card, changing one thing: gpu_layers: 30 with cpu_moe_layers: 30 (the model has THIRTY layers; the first attempt asked for 31 and the engine refused it rather than clamping, which is the refusal working). The count is explicit for a reason worth writing down — -1 and 99 classify as Offload::full in vram_footprint.h, so the gh#148 admission gate prices the whole 14.25 GB file against an 11 GiB card and refuses the tier before the knob can help, and auto is refused by design; 30 classifies as partial_unknown, which leaves the gate open because the engine declines to price what it cannot price. A knob that silently did nothing must FAIL, never report a number, and llama.cpp exposes no post-load per-tensor buffer query, so the case takes the strongest in-process signal and states what makes it sufficient. MECHANISM: gpu_layers is asserted to have resolved to exactly llama_model_n_layer, so every repeating layer was REQUESTED resident and nothing left in the engine can put trunk weights on the host except the expert override — which rules out both ways the arm could quietly become an ordinary partial-offload run. EFFECT: the VRAM the load actually took (device-wide, after minus before) must clear a bound derived from the trunk’s size on disk and this card’s free VRAM alone, bound = free − (weights − free) — the ceiling, cleared by the overflow again, the same margin idiom as the floor rule’s required = floor + max(floor, 5 pp). It is more than an idiom here: cpu_moe_layers is not a fitting algorithm, it has no idea how big the card is and moves EVERY routed-expert tensor of the first N layers rather than the least that would fit, so an engaged override lands far below the ceiling and a load that merely squeaked under it did not do what the knob does. Both halves rest on the card being unable to hold the trunk; on a card that CAN, the case SKIPs with that reason before the load rather than passing vacuously. What it does NOT establish is HOW MUCH moved — nothing here prices the split in bytes, and the admission math still models no expert placement. (v2.13.0, gh#153 #42(iii)) MEASURED 2026-09-22 (1080 Ti, gpu_layers=30, ctx 8192, max_tokens 256, 4 trials), sweeping cpu_moe_layers by hand: N=30 — 2767 MiB VRAM, plain 17.68, mtp 18.18 tok/s, effect −0.29 % (floor 3.11 %); N=20 — 6775 MiB VRAM, plain 22.62, mtp 23.76 tok/s, effect +4.16 % (floor 0.83 %); N=12 — 9446 MiB, refused by the engagement bound (see below). Experts-on-host by itself buys NOTHING on this card: N=30 lands at 18.2 tok/s against whole-layer offload’s 18.7 (#42(b)), because the per-token expert bytes still come from host RAM either way. What it buys is VRAM — 2767 MiB against 7865 MiB — and that only pays once the freed memory holds experts again: at N=20 throughput rises to 22.6 and MTP’s effect turns positive (+4.16 %), which is #74’s resident-fraction rule appearing INSIDE one model rather than between two. The engagement bound cannot judge a mid-sweep point: it assumes most weights are host-side, so N=20 clears it by 300 MiB and N=12 exceeds it — not because the knob failed but because 18 layers of experts ARE resident. The committed case therefore stays at N=30, the robust comparison against #42(b); sweeping N needs a residency-aware bound and is gh#167/gh#180’s job.
An ABI that advertises a modification channel must apply it, and the guard on it is identity, not content (v2.13.0, gh#168).
entropic.h’s memory-ownership paragraph nameshook modified_jsonas a cross-boundary allocation the engine consumes, andtypes/hooks.hstates the pre-hook contract as “return 0 +*modified_json != NULL: proceed with modified context”.ToolExecutor::fire_pre_tool_hookdidfree(mod); return rc != 0;— so for every tool, on every call, since the hook point existed, the advertised channel was a documented no-op. This is the SAME defect as issue #2 onPOST_TOOL_CALL(v2.1.1) and, before it, gh#3: the engine freeing a hook’s output without applying it. POST was fixed twice and PRE was never looked at, which is why the class is written down here rather than in a third commit message. The consumer symptom was silent by construction — a host appending a parent’s verbatim observation to a delegated task saw the specialist work from the lead’s paraphrase, with no error anywhere; their feature reached 0 of 15 lifetime and two downstream workarounds measured 0 of 3 each, because neither could reach a channel that was never wired. Only the ARGUMENTS may change. The payload is the same object shape the hook received and only itsargsobject is read;tool_name, if restated, must equal the call’s own. A hook that could rename the tool would route a permitted call to a tool the tier’sallowed_toolsnever granted — the per-tier dispatch gate (gh#83) reads the name BEFORE the hook, so an identity rewrite lands after the only check that would have caught it. Arguments do not have that property: they are re-validated against the tool’s schema, re-keyed for duplicate detection and re-matched against permission patterns after the hook, which is why they are the safe half. Refusal is loud, total and NOT a cancellation. A payload that is not valid JSON, not an object, carries noargsobject or names another tool is refused whole — logged at ERROR with the reason and the verbatim payload, with the model’s original arguments dispatched. The tempting alternative, treating a bad payload as a hook error and cancelling the call, was rejected: cancellation has exactly one channel (a non-zero return), and overloading it would make a buggy host hook indistinguishable from a deliberate policy denial in both the model’s context and therejected_preconditionresult kind — the host’s bug would be diagnosed as the agent’s behaviour. A silent fallback was equally rejected (#43): the ERROR line IS the surfacing, and it names the knob the operator has to fix. Both argument representations are rewritten,arguments_json(whatserialize_argshands the server, the schema validator and the POST context) and theargumentsmap (whattool_call_keyhashes), because writing only one would let a rewritten call collide with the original in the duplicate cache and be rejected as a repeat of a call that never ran.process_single_calltherefore takes the model’sToolCallby const reference and works on its own copy, so preconditions, dispatch, the dup cache and the POST hook all observe one consistent call. The payload is sanitized BEFORE it is parsed, not after: a hook is a plugin.so, an external boundary in both directions (gh#3, gh#111, gh#132), and nlohmann rejects an ill-formed UTF-8 byte inside a string — sanitizing after the parse would refuse a payload that is merely dirty and turn the gh#113/#114/#132 trap into a second silent no-op.The iteration cap is an ANNOTATION on the run’s last real output, never a replacement for it (v2.13.0, gh#169).
AgentEngine::looppushed a synthetic assistant message whose CONTENT was[iteration cap reached after N iterations — returning current state].DelegationManager::extract_summarytakes the last assistant message asDelegationResult::summary, so on every capped delegation that placeholder became the child’s result — in the parent-tier relay, in the ON_DELEGATE_COMPLETE payload, and in the storage record. The child’s real summary EXISTS at cap time: the consumer’s curriculum specialist completed its work at iteration 10 of 10 with real text and the parent was handed the placeholder instead. The measured symptom is a lead confidently reporting the opposite of what happened: in 3 of 5 turns the lead told a parent a record lookup had FAILED whileget_student_recordhad returnedstatus=okwith a full 501-character record andset_interesthad written the row; separately a lead apologised that a lesson plan “didn’t come through” with the finished lesson sitting in the store. The engine was not losing the work — it was overwriting the one field the parent reads. The cap now carries the last substantive assistant content and appends the note, so the parent gets the answer AND the fact that it is partial. “Substantive” is byte-level (any content that is not entirely whitespace), measured before the cap message is pushed, so there is no engine-authored marker to filter out and no classifier to get wrong. Nothing about the failure signal moves.terminal_reason = "budget_exhausted"is still written and is still the sole indicator that the child did not complete naturally:DelegationResult::successstays false,finalize_delegation_resultstill tags[partial — budget_exhausted],relay_statusis stillbudget_exhausted_relayed, andbuild_delegate_complete_jsonstill emitssuccess: falsewithresult_kind: "delegation_failed". A consumer parsing those fields sees no change — which is the point: carrying the work is orthogonal to reporting the budget, and conflating them is what the placeholder did. A child that produced nothing stays distinguishable, twice over: the two branches are worded differently in prose (“no substantive output was produced before the cap”) ANDmetadata["cap_carried_content"]records “true”/”false”, following therelay_statusconvention (#E8) so a consumer can branch without matching engine prose. Deliberately NOT done:cap_carried_contentis not hoisted ontoDelegationResult. The parent already distinguishes the two cases from the summary it receives, and a public struct field with no reader is surface that has to be kept true forever; it can be added when a consumer asks for it.The thinking-budget hard cut annotates too, through the SAME helper as the cap (v2.13.0, gh#181).
AgentEngine::hard_cut_budgetpushed an assistant message whose CONTENT was[thinking budget exhausted — the turn was hard-cut after the completion nudge went unheeded; no tool call was emitted], then setterminal_reason = "budget_exhausted_thinking". Same sink as #77 —DelegationManager::extract_summaryreads the last assistant message — so a child hard-cut by the thinking budget handed its parent that string where its result belonged. Identical defect, other budget path. The two paths now share one implementation,AgentEngine::finish_with_carried_output+annotate_hard_stop: carry the last substantive assistant content, annotate rather than replace, write the caller’sterminal_reasonand the typedcap_carried_content, force COMPLETE. They differ only in reason text, in the stop noun (“cap” / “cut”) and in theterminal_reasonvalue; two hand-rolled copies of the same annotation is how those two paths drift apart, which is the whole reason for one helper. The cap’s rendered text is byte-identical to what #77 shipped. The nothing-was-produced branch matters MORE here, not less. A hard cut fires precisely when a model narrates instead of calling a tool, so “it produced something substantive first” is less often true on this path than at the iteration cap — which argues for carrying whatever exists and saying plainly when nothing does, not for keeping the placeholder.cap_carried_contentis ONE key for both stops, deliberately. The question a consumer asks is “did the handed-back text contain the agent’s own work?”, and it should have one place to look;terminal_reasonalready distinguishes which stop fired, and the two values stay distinct —"budget_exhausted"for the cap,"budget_exhausted_thinking"for the cut — because a consumer may key on them. Nothing else moves:DelegationResult::successstays false, the relay still tags[partial — budget_exhausted]withrelay_status = "budget_exhausted_relayed", and ON_DELEGATE_COMPLETE still reportssuccess: false/result_kind: "delegation_failed".An argument the model is shown must bind something, and when it meets an operator’s limit the STRICTER wins (v2.13.0, gh#182).
data/tools/entropic/delegate.jsonadvertisedmax_turnsto the model withminimum: 1, maximum: 30and the description “Maximum number of turns the delegate can use”. The value travelledDelegateDirective→PendingDelegation→DelegationManager::run_child→ thedelegationsstorage row, and stopped:run_childdispatches throughrun_child_fn_, which takes no limit, so the child’s actual bound came fromLoopConfig::max_iterationsor the child tier’s identity frontmatter and never from what the model asked for.grep max_turns src includefound it only instorage/backend.cppand indelegation.cppsignatures — the shape of #76’s defect class, an advertised channel wired to nothing, and worse than an absent argument because the model believes it has scoped the work. The child now carries the request onLoopContext::delegated_max_turnsandAgentEngine::resolve_max_iterationstakesmin(operator_limit, delegated_max_turns). A value below the tier’s or the engine’s bound TIGHTENS it; a value above it changes nothing. A model must not be able to RAISE a limit the operator set —max_turnsis the model’s estimate of how much work the task needs, not a budget grant, and the schema maximum of 30 would otherwise let any lead overrun a tier deliberately pinned at 3. The min is taken in the RESOLVER, not by folding the request intoeffective_max_iterations. Two writers touch that field —apply_identity_overridesat loop entry andrun_childbefore it — so a fold would make the outcome depend on their order, while a min at read time cannot; it also keeps “operator’s setting” and “model’s request” separately inspectable, which is what the log line and the precedence rule are stated in terms of.delegated_max_turns < 1means the argument was omitted, and the resolver is then byte-identical to its pre-gh#182 self, so every un-capped delegation, every pipeline stage and every top-level run behaves exactly as before. Amax_turns-bounded child is the ITERATION CAP, not a new terminal. It reaches the sameresolve_max_iterationscomparison inshould_stopandloop, so it gets #77’s hand-back for free: the child’s last substantive output is carried and annotated[iteration cap reached after N iterations …],terminal_reasonstays"budget_exhausted",DelegationResult::successstays false and ON_DELEGATE_COMPLETE still reportssuccess: false/result_kind: "delegation_failed". Deliberately so — a bounded child did not complete naturally, and inventing amax_turns_reachedterminal would hand consumers a fourth value to parse for a distinction they can already make from themax_turnsthey themselves sent. The cost, recorded because it lands on tests: a model-chosenmax_turnscan now shorten a child the FIXTURE meant to cap elsewhere, so a scenario whose subject is one of the budget terminals must tell its lead not to pass the argument rather than assume it is inert (make_lead,tests/model/test_gh169_gh181_budget_carry.cpp).A per-identity override that only a delegated child honours is not a tier setting — it is a delegation setting nobody called one (v2.13.0, gh#183).
AgentEngine::apply_identity_overridesreadsmax_iterationsandmax_tool_calls_per_turnfrom a tier’s identity frontmatter and writes them onto theLoopContext; it had exactly ONE caller,run_loop, which is the door a delegation CHILD arrives through.AgentEngine::run()builds its ownLoopContextand callsloop(ctx)directly, so the same tier, with the same frontmatter, was capped when it ran as somebody’s delegate and uncapped when it ran as the LEAD. Not a subset of behaviour and not a documented exception — REQ-IDEN-001 said “applied into the LoopContext at loop entry”, andrun()is a loop entry. Both paths now run ONE preamble,AgentEngine::begin_loop_preamble: apply identity overrides, reinject context anchors, start the metrics clock if it is not already running, move to PLANNING. A second call site was rejected for the same reason gh#181 made the budget cut share gh#169’s helper — two copies of a setup sequence drift, and this defect is what the drift looks like after four minor versions. The interrupt reset and the pause clear stay OUT of the preamble, deliberately. They are precisely what the two entries must keep doing differently:run()is always a fresh top-level turn and resets unconditionally, whilerun_loopresets only wheninherit_interruptis false, so a child cannot swallow a parent interrupt raised at dispatch (gh#81). Hoisting them would have handed a top-level run a child’s inheritance semantics — the exact failure mode the fix had to avoid, and the reason the preamble is drawn where it is rather than around everything the two functions have in common.run()’s ownstart_timeassignment also stays where it is, ahead ofinit_session_conversation, so the storage insert keeps counting toward the run’s duration as it always has; the preamble’s clock start is guarded on== 0.0and is a no-op there. Known and NOT fixed here: a ROUTED lead.run(messages, tier_override)locks the tier up front only when the caller names one (run_turn_as, gh#99); with an empty override the tier is chosen inside the first generation byResponseGenerator::lock_tier_if_needed, which is after the preamble has run, so a routed lead’s identity overrides still do not apply. Re-applying once the tier is locked would also have to decide what happens when adir_tier_changeswitches tiers mid-run and the new tier sets no override (the old tier’s value is sticky, becauseapply_identity_overridesonly writes when the parameter is non-empty). That is a design question about override lifetime, not a missing call, and it is left for its own proposal rather than settled inside a one-line-caller fix.gpu_layers: autosolves the ONE footprint estimator against the model’s real shape; it never runs a second, cruder estimate beside it (v2.13.1, gh#192 — recorded retroactively in v2.14.0). v2.13.0’sautopriced every model as 30 layers atfile_bytes / 30each, against free VRAM minus a flat 2 GiB that double-countedvram_reserve_mb, and knew nothing about the KV cache, the draft head, mmproj or experts — whilevram_footprint.halready priced all of those for the admission gate. Two estimators disagreeing about one tier is the defect class:autowould derive a placement the gate then refused. v2.13.1 reads the GGUF metadata (gguf_init_from_file,no_alloc— header and tensor index, no data), sums expert bytes from the tensors matching llama.cpp’s ownLLM_FFN_EXPS_REGEX, counts the draft head, and searches placements withestimate_vram_footprintitself: fully resident, then every layer resident with experts progressively host-side (a MoE keeps attention on the card), then fewer layers. Rule: a derived configuration must be priced by the same function that will judge it. The release found four places it had broken this rule in its own fix — a second estimator, a second reserve, a second opinion about one tier — two of which would have shipped silently.automay lowern_ubatchto buy full residency, states the margin it leaves free, and that ladder is honestly scoped to the full-residency case (v2.13.2, gh#193/#196 — recorded retroactively in v2.14.0). A cold-prefill sweep (26B-A4B IQ2, four iterations, fixed-layer rows only) measuredn_ubatch128→512 buying prefill 2.02× at a decode cost of 1.21×, while dropping 30→24 layers cost prefill 1.79× AND decode 2.93×. Soautotries full residency at 512, then 256, then 128, stopping at the FIRST rung that fits and only ever lowering. Three corrections were published against this within days, and they define its real scope: (1) the ladder runs only when full residency is reachable at some rung — otherwise the lever is discarded and experts/layers are priced at the original 512 compute buffer (gh#196; zero engagements across the 89-test gate that shipped it); (2) the sweep pinnedcpu_moe_layersat 0, so “ubatch before EXPERTS” was never measured and today’s experts-first behaviour in the partial case may be the better policy; (3) the margin quoted in the notes came from a test fixture, the real gate reading was 297 MiB.autotherefore logs the margin unconditionally, warns under 256 MiB, and a drift-guard test asserts which branch fires at a free-VRAM figure read from a real log. Rule: an optimisation’s test takes its environment from a log, not from a constant chosen so the branch fires.An external server the operator did not enable is a process nobody asked for: discovery is Claude-Code style and fails closed (v2.14.0, gh#199/#200). A
.mcp.jsonthe engine discovers is a list of processes a repository asks the host to start. Before v2.14.0 a named workspace started all of them unconditionally — a consumer’s handle, configured by file precisely to avoid project config, launched a 58-tool application server and four nested launchers — while the main handle never connected anything at all: nothing calledServerManager::initialize()there, somcp.external_servers(in the struct and schema since v1.8.7, parsed by no loader) was dead, andloader.cpp’s own.mcp.jsonmerge fed only that dead list. Now: declaredmcp.external_serversare parsed and connected on the default set (declared = enabled); discovered servers connect only when enabled —disabled_mcpjson_serversrefuses,enabled_mcpjson_servers/enable_all_project_mcp_serverspre-approve, otherwise the newENTROPIC_HOOK_PRE_MCP_SERVER_CONNECTpre-hook decides, and with no hook registered the server is not connected — the one pre-hook where silence refuses, because the alternative is a repository launching processes by default. Every server set, default and workspace, receives the same policy; the loader’s duplicate discovery was deleted with its tests (user-ratified). The self-guard (gh#200) is rebuilt: the old one compared a non-standard"path"key against a socket derived from the server set’s root and could never match a stdio entry — our own trackedentropic mcp-bridgeescaped it only by a name collision.launches_own_bridgeresolves where anentropic mcp-bridgeentry would connect exactly as the CLI does, and compares with the path the bridge actually binds, computed by the same facade helper the bridge uses. Rule: a capability that starts processes on the host is opt-in, and its opt-in is visible in config or in a hook the host registered — never inferred from the absence of an objection.Network serving stays on loopback and borrows its remote story from SSH; a bearer token stands in for SO_PEERCRED (v2.14.0, gh#204). One host serving many MCP clients needs a network transport (MCP’s own answer is Streamable HTTP), and TCP has no peer-credential check, so something must replace the unix socket’s uid test. Rejected: TLS plus a bind-address option inside the engine — certificate handling, a remote attack surface and a config surface for a capability
ssh -Lalready provides, audited, with key-based auth. Now:mcp.external.http_portserves the SAMEExternalBridge(same tools, sessions, turn lanes) at127.0.0.1:N/mcp; a 256-bit token regenerated per start lives in~/.entropic/serve/N.token(0600, in a 0700 owned non-symlink directory — refuse to start otherwise), compared in constant time, never logged;Originand foreignHostare refused (browser pages and DNS rebinding); size caps, timeouts and an auth-failure throttle. A port that cannot be served fails configure withENTROPIC_ERROR_IO— a host that is not reachable must not look like one that is.entropic serveis the headless host: it sets the twoENTROPIC_MCP__EXTERNAL__*env overrides (so no second config format), blocks SIGINT/SIGTERM before any engine thread exists andsigwaits, then destroys the handle, which removes the token. Async completion notifications stay unix-socket-only; an HTTP client pollsask_status(no server-initiated stream, GET is 405). Rule: the engine trusts exactly one boundary — this uid on this host — and any wider reach is delegated to a tool built for it.A tool’s response shape is declared once, in its
outputSchema, and everything else is derived from it or tested against it (v2.14.0, gh#203/#173/#201/#202/#190/#174). A tool description is the one artifact that is load-bearing, read by a model that cannot verify it, and covered by no gate. All three filesystem tools that stated a shape stated a false one (read_filepromised line-number keys; gh#120 had made them an unkeyed array, so a model supplied numbers and cited fabricated lines, gh#201). An audit found the same class across the set: followup promised{results:[{delegation_id, summary}]}and returned storage’s raw rows, even thoughi_mcp_server.hdeclared the provider’s shape;edit_fileinserted BEFORE the line its schema said AFTER, andinsert_line: 0was a silent no-op reporting success; grep claimed to skip binaries and checked nothing; todo’s out-of-range update reported success; the diagnostics/web servers answered with prose that read like results. Now: every bundled descriptor carries anoutputSchema(MCP’s field), kept onToolDefinition; the description’s Response format is generated from it (render_response_format) — never hand-written; andtool_contract_gate_test+filesystem_contract_testdrive every tool, hold each output to its schema with closed objects, and require the error codes produced to equal the codes declared, so a schema may not promise a code nothing emits. Silent caps became declared results (truncated,reason,next_offset;limit/offseton grep/glob/list_directory; read_file pages and numbers every line). Code was fixed to the contract, not the reverse. Placeholder servers default off and answernot_implemented. One error classifier (looks_like_tool_error) now serves the failure counter, the history and the result kind, and an external server’sisErrorreaches it (gh#190). Cost: the default tool block grew ~25% (~1.7k tokens). Rule: a statement a model will treat as ground truth must be generated from, or tested against, the code that makes it true.A workspace may carry its own app_context; the rest of the prompt stays the handle’s, and repository-supplied text is opt-in (v2.14.0, gh#179). gh#166 gave workspaces their own root, servers and sandbox but not their own project context, so a daemon serving several repositories from one resident model gave every session the same app_context. Now:
entropic_workspace_set_app_context(h, name, text)(NULL = back to the handle’s, “” = none), and a config keyworkspace_app_context: <path relative to the root>that, when set, loads that file from each new workspace’s root. Both feed one composer (apply_workspace_app_context) that assembles exactly what configure assembles — constitution, app_context, tier identity — with only the app_context source swapped, and hands the result to the engine keyed by workspace. The engine keeps workspace→prompts and session→workspace, and resolves them at the three places a system prompt enters a conversation: untiered first-turn seeding, tier seeding (run_turn_as), and a delegated child’sChildContextInfo— so a session’s project context follows its delegations. Resolution is by the calling thread’s session key, so concurrent sessions in different workspaces each get their own. A started conversation keeps the system message it was seeded with (re-seeding mid-conversation would rewrite history the model already reasoned from). Rejected: always-on discovery of a file in every workspace root — repository-supplied text in the system prompt by default is the same “the repository decides what the host does” exposure gh#199 closed for.mcp.json(user-ratified: setter plus opt-in file). The file must resolve inside its root; a symlink out of the repository fails workspace creation rather than being followed. Prompt-cache note: per-workspace prompts are distinct prefixes, which is correct — warm-keep and prefix matching already key on the actual tokens, so two workspaces simply do not share a prefix. Rule: a per-tenant override replaces one input to the shared assembly; it never forks the assembly.Declared external servers run in every server set, rooted at it — revising #83 (v2.14.1). #83 kept
mcp.external_serverson the handle’s default set (“the handle’s, not every repository’s”). But a session bound to a workspace lists and dispatches tools from its workspace’s set only (gh#166), so a declared server was not merely untargeted there — it was absent. The consumer that exposed it (sumac: one serve host for every repository, a code-index server declared once) could not ship: a bound session had correct files and no index, an unbound one had the index and one repository’s files. Now: each workspace launches the declared servers itself, started in its root, and${ENTROPIC_WORKSPACE_ROOT}in an entry’s args or env values expands to that root, so a server that takes its repository from an argument or an environment variable can be told which. Cost, stated: one process per declared server per workspace, launched at workspace creation. Rejected: a fallback from the workspace set to the default set — it gives visibility but leaves the model to name the repository on every call, which is exactly the rule a small model drops. Found while testing this:StdioTransporthad storedworking_dir_since gh#166 and every caller set it, butspawn_childnever applied it — every external server had been starting in the host’s cwd, while a comment inmake_transportsaid otherwise. It nowchdirs at spawn and logs where it started each child. Rule: a tool a session cannot see is not a scoping decision, it is a missing tool — decide scope by what the session can reach.Per-run state is published to the run’s thread, never parked in a handle-wide slot (v2.14.2, gh#208).
run_streamingbuilt its stream context on its stack and stored the pointer inAgentEngine::callbacks_— one slot per handle. Harmless while a handle ran one turn at a time; with concurrent sessions (default since v2.13.0, routine underentropic serve) a second streaming turn overwrote it, so one client’s tokens went to another’s stream and, when the second turn returned, the first streamed into a dead frame (consumer SIGSEGV, 2 runs in 3). Now:RunStreamScopepublishes the run’s sink to its own thread — the patternRunCancelScopeandRunSessionScopealready established, and correct for the same reason: generation runs inline on the run’s thread — and the emitter prefers it over the handle slot. The TSan sweep that pinned it found three more of the same shape in the bridge, all fixed here: a client fd closed by its thread whilestop()shut it down (a reused number shuts down a stranger’s socket); a notification check-then-send split across a lock release (a reused number delivers another client’s completion); and detached async workers capturingthis(use-after-free on destroy) — now owned, interrupted and joined. They escaped v2.14.0 because the TSan filter matchedbridgecase-sensitively and skipped everyExternalBridge …test. Rule: if two runs can be in flight, anything one of them owns lives in a run scope or under the lock that also guards its release — and a sanitizer filter is checked by listing what it selects.What an MCP client can take over MCP, it can give back over MCP (v2.14.3). Any
askloads a model; through v2.14.2 nothing in the bridge’s surface unloaded one — the only routes were SIGUSR1 / SIGTERM to the host process, which need a shell on the box.<prefix>.releasecallsentropic_release_model(h, NULL): every resident model unloaded; the handle, sessions and conversations kept; the next ask reloads. It refuses rather than waits while a turn runs (ENTROPIC_ERROR_ALREADY_RUNNING→ anisErrorresult telling the caller to retry), matching the C API, and its result names what it released or says nothing was resident, read from the residency snapshot. Noshutdowntool: on a shared host it would end every other client’s sessions. Accepted cost: any client of a shared host can unload the model under the others; the next ask reloads, so it costs latency, not correctness (user-ratified). Rule: a resource a protocol lets a client acquire must be releasable through the same protocol.Text from a model is data: it never reaches a shell, and a broken or empty safety declaration fails closed (v2.14.4, gh#211). A consumer’s audit (reported privately) found three holes. (1) The git server — on by default — built
git -C <root> <args>forpopen(), unquoted: a model-supplied file name, ref or commit message (even inside double quotes, where$(...)still runs), or a repository path with;, executed as the user; prompt-injected text in any file the model read could reach it.run_gitnow fork/execs an argv (no shell), paths follow--, and refs starting with-are refused (--orphan,-Dran as options before). (2) Any directory could become a workspace root —/made the model a reader of the whole account.mcp.workspace_rootsbounds it (canonical paths, so neither a symlink nor..escapes). (3) A tier’s tool allowlist failed open twice: a missing or unparseable identity was skipped silently, leaving no allowlist; and a DECLARED empty list (allowed_tools: [], three bundled identities) read as “no filter” at both staging and dispatch. A named identity now must load or configure fails, and[]means no tools — only an absent key is unrestricted. Fixing (3) exposed a fourth: every YAML parse used ryml’s default error handler, which ABORTS — a config or frontmatter typo killed the host.parse_yamlinstalls a throwing handler and returns the error. Also found:branch.jsondeclaredname, the code readcreate. Rule: where text crosses into an interpreter, pass it as data (argv, not a command line); and a safety setting that is missing, empty or unreadable means “deny”, never “allow”.A turn the engine fails is a failure to its caller, and it leaves no trace in the session (v2.14.5, gh#209/gh#212). Two consumer reports, one root: when the loop ended a turn in
AgentState::ERROR(explicit-completion retries exhausted, a prompt that does not fit), the reason lived only in that run’s metadata and every run entry point returnedENTROPIC_OK. The bridge then picked “the answer” by scanning backwards for any non-empty assistant message — which crossed the turn boundary and returned the PREVIOUS turn’s answer (gh#209), or returned a{"action":"complete"}block the model had written as text after the nudge, while the real answer sat two messages earlier (gh#212). Now: (1) the engine records the failure per session, and every agent-loop run entry point returns the new, appendedENTROPIC_ERROR_TURN_FAILED— the bridge maps it toisError: true; (2)entropic_last_error()carries the reason plus, when the turn wrote something substantive, that text labelled as unconfirmed — the error text is the only channel the streaming entry points have; (3) the failed turn is rolled out of the session (prompt, nudges, replies, tool results) — the v2.14.5 gate showed a failed turn’s leftovers (the nudge,entropic.inspectwritten as text) making the next healthy turn answerentropic.complete, 3 of 3; a queued-message drain stops at the failure so a later turn cannot bury it; (4) answer selection is bounded to the turn’s own prompt, and skips a tool call written as text — a{"action":"complete"}object, or content that is exactly one registered<server>.<tool>name — without ever treating it as the call (no guessing at what the model meant); (5) the nudge now says the call must be an actual tool call, not text. Rejected: an opt-in status accessor (direct C consumers stay silently wrong), promoting a text imitation to a completion (a heuristic that tolerates the behaviour that broke it), and skipping the nudge after prose (dilutesexplicit_completion). Known limit:last_erroris per handle, so two sessions failing at the same instant can read each other’s text; the write is locked, the attribution is not. Reporting failures exposed one the default had been causing: a tier with noexplicit_completionsetting owed a completion call unless it auto-chained — including grammar-constrained tiers (the NPCrun_aspattern), which cannot emit a tool call at all, so every call was nudged three times (4× the generations) and then failed, behindENTROPIC_OK. Now a tier that binds a grammar (tier config or identitygrammar:) defaults to no explicit completion (prompts::derive_explicit_completion). One identity file stating bothgrammar:andexplicit_completion: truefails configure; across sources (a config grammar on an identity that saystrue, as every bundled agentic identity does) configure WARNS instead, because gh#154 requires that configuration to configure — and each turn then fails loudly. The gate also showed a failed MTP decode swallowed into a completed empty turn (gh#214, open). Rule: a failed turn is never presented as an answer, and never left in the history a later turn learns from.One turn must never be able to take down the host (v2.14.6, gh#214, gh#216, gh#217). Three consumer-found ways it could. (1) Typed generation failures never left the inference wrappers.
iface_generate,iface_generate_streamandiface_generate_with_cancel(interface_factory.cpp) returned 0 whatever the orchestrator said, so a prompt that does not fit (EVAL_CONTEXT_FULL), a failed MTP decode and a residency refusal all reached the loop asfinish=stop, 0 charsand fell into the empty-turn nudge ladder. The v2.13.0 context-overflow refusal (decision log, 26884f6) was implemented in the backend and the engine but never connected between them: the engine had only ever seen the code from a unit-test mock, and a coverage test assertedrc == 0on a no-model error, encoding the defect. The wrappers now returnresult.error_code. (2) The tool-call history is handle-wide and re-serialized every run, so one record holding invalid UTF-8 (a 200-byte cut through U+2014) made every later turn on the host throwtype_error.316, in any session, until restart. The cut now backs up to a character boundary, and the dump uses nlohmann’sreplacehandler, so a bad byte can never throw. (3) Release claimed only the default session’s turn. Under per-session concurrency (entropic serve’s default) a decode in another session kept running while release unloaded its model: SIGSEGV or CUDA abort, host dead. Release now takes an EXCLUSIVE claim (try_begin_turn(key, exclusive),HandleTurnGuard::claim_exclusive), refused while any run is in flight on any key and refusing every other claim while held. Cancelling a turn whose client disconnected is gh#218. Riding along (consumer request): an opt-in<prefix>.shutdowntool that takes the same exclusive claim, replies, then raises SIGTERM so serve’s existingsigwaitstop path does the teardown — opt-in (serve --allow-shutdown) because the bridge is library code and an embedder must never get a tool that signals its own process. A gate failure the user refused to carry forward found a fourth: the model never saw its own tool calls. The assistant message stored only the CLEANED text, and the result arrived as a bare user message, so the history read “question, empty reply, result” — results with no calls — and the model learned to write result-shaped prose (“Error: not_found”) instead of calling.test-outside-root-approvalpassed ~13% of attempts (v2.14.0 baseline ~37%, same inputs). Calls and results now travel as structured fields (tool_meta::kCalls/kCallTexton the assistant message,kCallId/kNameon every per-call result — success, denial, error, duplicate) beside role/content, and the backend renders the chat template’s native tool-call and tool-response turns (to_common_chat_msg);contentstays clean for consumers, storage and answer selection, and the template-less path shows the raw call text. 10/10 after, with a log line proving the native turns rendered and no jinja fallback. And the Qwen3.6 tests’ host-RAM skip quoted a threshold (file + 2 GiB) the gate had already rejected while deciding on 1.5x file + 1 GiB; per the user, the harness auto-sizes the load to this machine (gpu_layers: auto, mlock off), so the shortfall no longer skips — only an explicit operator waiver does — and all three run with zero memory pressure measured. Rule: the model must be shown the conversation it actually had; test the production wiring, not just the mock. Shared, handle-wide state written by one turn must be impossible to poison for the next.After a nudge, a tier that owes a tool call is forced to make one; if it already answered in prose, it may only conclude (v2.14.6, e7-delegation). E4B under
explicit_completionsometimes answered in prose, was nudged, then emitted thinking-only turns until the turn failed (test-e7-delegation; 18 of 102 no-tool-call turns at a consumer). The nudge only asked. Now the retry after a no-tool-call nudge is generated with gh#134’s tool-call grammar forced, for that generation only (force_tool_callin the params; the first attempt stays free-form, so a complying model is never constrained). Forcing alone let the retry re-delegate work the prose had already answered. Per the user’s decision, when the nudged turn had prose, the forced retry is offeredentropic.completealone (ResponseGenerator::build_params_jsononly_tool), so the grammar has nothing else to pick. A thinking-only (empty) turn’s retry keeps every tool, since no answer exists to conclude with. A tier never offeredentropic.completekeeps its tools, logs an ERROR, and its retry is NOT forced (corrected after the v2.14.6 gate: the first cut still forced “any tool”, so a gh#169/gh#181-shaped child — explicit completion, no completion tool, on purpose — emittedread_filecalls instead of narrating, and the thinking-budget cut, its only exit, never fired); configure refusing that tier is gh#213. Rule: a nudge that a model can ignore is a request, not a contract; the contract is enforced in decoding, as narrowly as the turn’s state allows.Engine metrics are INFO log fields; there is no metrics registry (gh#26, ratified 2026-11-23). gh#26 asked where namespaced counters and histograms should route. In practice option A has been in place since v2.2.4: every load, evict, swap, prefill and generation logs its numbers as untruncated INFO fields, and consumers that want time series scrape the log. The user ratified A: no in-engine registry, sink or exporter. Rule: a new measurement is a field on an INFO line the code already emits (or a new INFO line), never a counter only a registry would show.
Engine directives skip the host’s approval gate; every other tool still passes it (v2.14.6 gate, user decision 2026-11-24). Once decision 93’s forced retry really forced a call, a headless host — no approval callback, auto-approve off, as the bridge test runs — denied
entropic.completeevery time, so the turn could never conclude and the client got an empty reply (test-gh144-bridge-queue, 3 of 3). Anentropic.*tool is the engine directing itself (complete, delegate, prune, introspect), not an action on the user’s system.MCPServerBase::requires_approval(local)(new virtual, defaulttrue, appended after every other virtual so existing vtable slots keep their positions) is answered by the owning in-process server only;EntropicServerreturnsfalse;ServerManager::requires_approvalreturnstruefor any plugin, external or unknown prefix, so an external server that names itselfentropiccannot exempt anything (routing prefers in-process servers too). Tier allow-lists and operator deny rules still apply; only the interactive approval step is skipped. Rule: approval guards actions on the user’s system; the engine’s control flow never waits on it.A tool call the parser cannot read is kept and reported, never dropped; “calls work with thinking on” is an engine-level guarantee (v2.14.6 gate, user decisions 2026-11-24). With thinking on, Gemma 4 sometimes writes its call with plain
"where the format uses<|"|>(call:read_file{path: "/etc/hostname"}). At the pinned llama.cpp,common_chat_parsereturned no call and kept only the thought block, whichstrip_thinking_channelsthen moved into reasoning: the call disappeared with no log line. Upstream master still requires<|"|>around string values (only keys may be plain-quoted), so there is no parse fix to mirror.parse_responsenow restores any<|tool_call>span absent from the parsed content (gemma4_dropped_tool_text.h), logs ERROR with the full raw emission, and lets the loop treat it as prose: the nudge fires, and the forced-grammar retry (decision 93) produces a valid call. A raw free-form decode therefore guarantees only that the call is never lost;test-v2146-thinking-tool-callasserts the real guarantee, that a thinking turn ends in an executed call. Rejected: accepting plain-quoted values locally, a parser divergence from upstream we would have to maintain. Riding along:gpu_layers: autofor backend-direct model tests resolves through the orchestrator’s own derivation (derive_tier_auto_placement,tier_placement.h); a test-side estimator would break decision 81. Rule: a parse never discards model output silently; what it cannot read, it keeps and reports.