Front end: llama.cpp's server files with the Strata engine behind them (design C), with fake-engine tests

frontend/strata_context.cpp replaces tools/server/server-context.cpp. The other seven server files
(server-http, -queue, -task, -common, -chat, -schema, -stream) compile unmodified from the submodule into
the static library strata_llama_server; frontend/ui_stub/ supplies the empty web-UI asset table that
server-http.cpp references. The context runs one slot: the engine is a child process spoken to over its
line protocol (docs/BACKENDS.md), a vocab-only llama_model provides tokenizing, the chat template and the
reasoning and tool-call parsers, and the server's own task and result types carry the OpenAI JSON, SSE
framing and client-disconnect cancel. Routes kept: /health, /v1/models, /v1/chat/completions, /tokenize,
/detokenize. The strata engine's 8-token reserve is kept out of max_new. A supervisor thread ends the
process with exit code 1 when the engine dies, for a unit with Restart=on-failure.

frontend/engine.hpp is the child adapter: fork+exec, READY/INFO, GEN/GENI, T/PP/RESUME/DONE/ERR/FATAL,
STOP with drain to DONE, non-blocking reap. quit() and the supervisor's reap_exit() share the pid through
an atomic that quit() takes over by exchange, and only a positive local copy ever reaches kill(). The
first draft kept a plain pid_t and the supervisor set it to -1 on reaping, so a SIGTERM during shutdown
raced into kill(-1, SIGKILL), which killed every process of the user; it did so twice on 2026-10-17.

Build: STRATA_FRONTEND (default on) gates the llama.cpp libraries and the front end, not CUDA, so they
build on a machine without a GPU. Makefile: unbiased-strata joins `make build`; `make frontend` builds it
alone without CUDA into build-frontend/; `make test` builds engine_test there and runs it and
frontend/tests/e2e.sh against a fake engine (frontend/tests/fake-engine.py). The nvcc probes run only
when there is an nvcc and only the build and configure goals demand one. UPSTREAM.md records all of it.

Verified on macOS arm64 without CUDA: `make frontend` and `make test` pass. engine_test, 7 cases: READY,
a request, STOP mid-request with drain and a clean next request, a 100k-token burst the caller abandons,
ERR leaves the adapter usable, the engine dying mid-request is diagnosed, a DONE with the wrong prompt
size is visible. e2e.sh, 12 checks: /health, /v1/models, a non-streaming chat with content, finish and
usage, a stream whose deltas join to the content and end with finish_reason and [DONE], a client that
disconnects mid-stream (the server logs the cancel and the next request completes), an oversize prompt
refused with 400, a tokenize/detokenize round trip. Zero new patch lines to llama.cpp, so the step-4
gate of PLAN.md section 5 passes and design C stands. Not yet run against a real engine.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Robert KarlandClaude Fable 5.1 committed 2026-10-17 21:31:05 -07:00
1 parent 822babeeb6
commit 4c25aa6f6a
12 files changed
+2219 -9

No files matched your search

+30 -1
View File
@@ -2147,7 +2147,8 @@ endif()
# cpp-httplib) and its image encoder (mtmd) from the same pinned checkout that ggml comes from. ggml is configured
# above, so llama.cpp's build reuses those targets. Nothing here downloads: LLAMA_USE_PREBUILT_UI is off and
# LLAMA_CURL is a no-op at this pin.
if(STRATA_ENABLE_CUDA AND STRATA_NATIVE_EXPERTS)
option(STRATA_FRONTEND "Build the C++ front end (unbiased-strata); needs no CUDA, so it also builds on a laptop" ON)
if(STRATA_FRONTEND AND STRATA_NATIVE_EXPERTS)
set(LLAMA_BUILD_COMMON ON CACHE BOOL "" FORCE)
set(LLAMA_BUILD_MTMD ON CACHE BOOL "" FORCE)
foreach(_o LLAMA_BUILD_TESTS LLAMA_BUILD_TOOLS LLAMA_BUILD_EXAMPLES LLAMA_BUILD_SERVER LLAMA_BUILD_APP LLAMA_BUILD_UI
@@ -2155,6 +2156,34 @@ if(STRATA_ENABLE_CUDA AND STRATA_NATIVE_EXPERTS)
set(${_o} OFF CACHE BOOL "" FORCE)
endforeach()
add_subdirectory(${STRATA_GGML_DIR} ${CMAKE_BINARY_DIR}/llama.cpp EXCLUDE_FROM_ALL)
# The engine-agnostic files of llama.cpp's tools/server, compiled as they are from the submodule: the HTTP layer,
# the task queue, the task and result types with their OpenAI JSON, request parsing and SSE formatting, the request
# schema, the resumable-stream pipe. server-context.cpp, the part bound to llama_context, is replaced by
# frontend/strata_context.cpp. server-http.cpp wants the web UI's asset table (ui.h, generated by tools/ui at build
# time); frontend/ui_stub provides an empty one.
find_package(Threads REQUIRED)
set(_strata_srv ${STRATA_GGML_DIR}/tools/server)
add_library(strata_llama_server STATIC
${_strata_srv}/server-http.cpp ${_strata_srv}/server-queue.cpp ${_strata_srv}/server-task.cpp
${_strata_srv}/server-common.cpp ${_strata_srv}/server-chat.cpp ${_strata_srv}/server-schema.cpp
${_strata_srv}/server-stream.cpp
frontend/ui_stub/ui.cpp)
target_include_directories(strata_llama_server PUBLIC ${_strata_srv} ${STRATA_GGML_DIR}/tools/mtmd
${STRATA_GGML_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/frontend/ui_stub)
target_link_libraries(strata_llama_server PUBLIC llama-common llama mtmd cpp-httplib Threads::Threads)
target_compile_features(strata_llama_server PUBLIC cxx_std_17)
add_executable(unbiased-strata frontend/main.cpp frontend/strata_context.cpp)
target_include_directories(unbiased-strata PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/frontend)
target_link_libraries(unbiased-strata PRIVATE strata_llama_server)
target_compile_features(unbiased-strata PRIVATE cxx_std_20)
# The engine adapter against the fake engine (frontend/tests/fake-engine.py): no GPU, no model, no llama.cpp.
# `make test` builds and runs it, then frontend/tests/e2e.sh against the binary above.
add_executable(engine_test EXCLUDE_FROM_ALL frontend/tests/engine_test.cpp)
target_include_directories(engine_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/frontend)
target_compile_features(engine_test PRIVATE cxx_std_20)
endif()
if(STRATA_BUILD_TESTS)
+26 -5
View File
@@ -3,7 +3,8 @@
#
# git clone <repo> && cd <repo>
# git submodule update --init
# make build # build/bin/strata, build/bin/strata-poly, build/bin/libstrata_kq.so
# make build # build/bin/{strata,strata-poly,libstrata_kq.so,unbiased-strata}
# make test # the front end against a fake engine; no GPU needed
#
BUILD_DIR ?= build
# CUDA archs: GTX 10 (61), RTX 20 / GTX 16 (75), RTX 30 (86), RTX 40 (89). Any arch below 75 turns on upstream's
@@ -13,8 +14,12 @@ CUDA_ARCHS ?= 61;75;86;89
# nvcc: on PATH, else the toolkit's usual place (RunPod images and distro packages differ). NVCC=/path overrides.
NVCC ?= $(or $(shell command -v nvcc 2>/dev/null),$(wildcard /usr/local/cuda/bin/nvcc))
ifeq ($(NVCC),)
$(error nvcc not found on PATH or in /usr/local/cuda/bin; install a CUDA 12.x toolkit or set NVCC=/path/to/nvcc)
ifneq ($(filter build configure,$(MAKECMDGOALS)),)
$(error nvcc not found on PATH or in /usr/local/cuda/bin; install a CUDA 12.x toolkit or set NVCC=/path/to/nvcc)
endif
endif
# Everything below that runs nvcc is skipped when there is none (a laptop running `make frontend` or `make test`).
ifneq ($(NVCC),)
NVCC_ARCHS := $(shell $(NVCC) --list-gpu-arch 2>/dev/null | sed 's/compute_//' | tr '\n' ' ')
ifneq ($(NVCC_ARCHS),)
CUDA_ARCHS_DROPPED := $(strip $(foreach a,$(subst ;, ,$(CUDA_ARCHS)),$(if $(filter $(firstword $(subst -, ,$(a))),$(NVCC_ARCHS)),,$(a))))
@@ -36,13 +41,14 @@ HOSTCXX ?= $(shell for c in g++-15 g++-14 g++-13 g++-12 g++-11 g++; do p=$$(comm
t=$$(mktemp /tmp/strata-hc-XXXXXX.cu) && printf 'int main(){return 0;}\n' > $$t && \
if $(NVCC) -ccbin $$p -c $$t -o /dev/null >/dev/null 2>&1; then rm -f $$t; echo $$p; break; fi; rm -f $$t; done)
HOSTCC := $(subst g++,gcc,$(HOSTCXX))
endif
COMPILER_FLAGS := $(if $(HOSTCXX),-DCMAKE_C_COMPILER=$(HOSTCC) -DCMAKE_CXX_COMPILER=$(HOSTCXX) -DCMAKE_CUDA_HOST_COMPILER=$(HOSTCXX),)
# capped: inside a container nproc reports the host's CPUs, not the container's quota
JOBS ?= $(shell n=$$(nproc 2>/dev/null || echo 4); [ $$n -gt 16 ] && n=16; echo $$n)
# what `make build` produces; upstream's `all` also builds about 70 parity and bench programs
TARGETS := strata strata-poly strata_kq llama-common mtmd
TARGETS := strata strata-poly strata_kq unbiased-strata
.PHONY: build configure clean
.PHONY: build configure clean test
configure:
@test -f third_party/llama.cpp/ggml/CMakeLists.txt || \
@@ -55,7 +61,22 @@ configure:
build: configure
cmake --build $(BUILD_DIR) -j $(JOBS) --target $(TARGETS)
@echo "built:"; ls -1 $(BUILD_DIR)/bin/strata $(BUILD_DIR)/bin/strata-poly $(BUILD_DIR)/bin/libstrata_kq.so
@echo "built:"; ls -1 $(BUILD_DIR)/bin/strata $(BUILD_DIR)/bin/strata-poly $(BUILD_DIR)/bin/libstrata_kq.so $(BUILD_DIR)/bin/unbiased-strata
# The front end alone, without CUDA: for a laptop or a CI box. Needs only a C++20 compiler and CMake.
.PHONY: frontend
frontend:
cmake -S . -B $(BUILD_DIR)-frontend -DCMAKE_BUILD_TYPE=Release -DSTRATA_ENABLE_CUDA=OFF -DSTRATA_BUILD_TESTS=OFF \
-DCMAKE_RUNTIME_OUTPUT_DIRECTORY=$(abspath $(BUILD_DIR))-frontend/bin $(CMAKE_EXTRA)
cmake --build $(BUILD_DIR)-frontend -j $(JOBS) --target unbiased-strata
# The front end's tests, against a fake engine (frontend/tests/fake-engine.py): the adapter's cases (cancel, drain,
# backpressure, child exit, ERR) and the HTTP surface a coding agent touches (frontend/tests/e2e.sh). Needs python3
# and curl; no GPU and no model. Runs in the CUDA-free build directory, so it works on the build box and on a laptop.
test: frontend
cmake --build $(BUILD_DIR)-frontend -j $(JOBS) --target engine_test
$(BUILD_DIR)-frontend/engine_test frontend/tests/fake-engine.py
frontend/tests/e2e.sh $(BUILD_DIR)-frontend/bin/unbiased-strata
clean:
rm -rf $(BUILD_DIR)
+16 -3
View File
@@ -34,9 +34,22 @@ GPU, Pascal or newer, CUDA 12.x), each recorded below with the file, the reason
CMake both; here it is CMake only, so a tree configured directly gets it too.
- **llama.cpp's libraries for the front end.** A second `add_subdirectory` of the submodule with
`LLAMA_BUILD_COMMON` and `LLAMA_BUILD_MTMD` on and tests, tools, examples, server, app, UI, prebuilt UI,
OpenSSL and llguidance off. It reuses the ggml targets configured above.
- **`Makefile`.** `make build` configures once and builds `strata`, `strata-poly`, `strata_kq`, `llama-common`
and `mtmd` into `build/bin/`, not upstream's `all`, which also builds about 70 parity and bench programs.
OpenSSL and llguidance off. It reuses the ggml targets configured above. Gated by `STRATA_FRONTEND` (default on),
not by CUDA, so the front end also builds on a machine without a GPU.
- **The front end, `unbiased-strata`.** Seven of llama.cpp's `tools/server` files are compiled unmodified from the
submodule into a static library (`server-http`, `server-queue`, `server-task`, `server-common`, `server-chat`,
`server-schema`, `server-stream`): the HTTP layer, the task queue, the OpenAI request and result types, SSE
framing, the request schema. The eighth, `server-context.cpp`, is bound to `llama_context` and is replaced by
`frontend/strata_context.cpp`, which runs the engine as a child process over its line protocol (`docs/BACKENDS.md`)
and uses a vocab-only `llama_model` for tokenizing, the chat template and the output parsers. `server-http.cpp`
references the web UI's asset table (`ui.h`, generated by `tools/ui` at build time, which downloads); `frontend/
ui_stub/` provides an empty one. No patch to llama.cpp was needed for this; the undocumented internal API of
`tools/server` is used as it is at the pinned commit.
- **`Makefile`.** `make build` configures once and builds `strata`, `strata-poly`, `strata_kq` and `unbiased-strata`
into `build/bin/`, not upstream's `all`, which also builds about 70 parity and bench programs. `make frontend`
builds the front end alone without CUDA into `build-frontend/`; `make test` builds and runs the front end's tests
there against a fake engine (`frontend/tests/`): the adapter's cases and the HTTP surface a coding agent touches.
The nvcc check applies only to the `build` and `configure` goals.
`CUDA_ARCHS` defaults to `61;75;86;89`; an arch below 75 adds upstream's `STRATA_EXPERIMENTAL_SM60`
(upstream's default is `120`, which needs CUDA 13). `PORTABLE=1` gives the AVX2 baseline instead of
`-march=native`. One GCC for the C, C++ and nvcc host sides: the Makefile probes `g++-15`, `g++-14`, ... with
+392
View File
@@ -0,0 +1,392 @@
// UnbiasedStrata: the engine as a child process.
//
// The engines (`strata`, `strata-poly`) speak lines over stdin/stdout: `GEN <max_new> key=value... <id,id,...>` in,
// `T <id>` per token, `PP`, `RESUME`, `DONE ...`, `ERR ...` out, `STOP` to cancel, `QUIT` to end (docs/BACKENDS.md,
// "How a backend works"). This class owns one such child. It never blocks longer than the caller allows: the server
// loop polls it between tasks so a cancel from a disconnected client is seen within the poll interval.
#pragma once
#include <atomic>
#include <cerrno>
#include <csignal>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
#include <string>
#include <vector>
#include <fcntl.h>
#include <poll.h>
#include <sys/wait.h>
#include <unistd.h>
namespace strata_frontend {
// Reap a dead child: kill(pid, 0) would report a zombie as alive. The pid slot is shared with quit() on another
// thread (the supervisor polls this while a SIGTERM handler shuts down), so it is read once and cleared by
// compare-exchange. Nothing here or in quit() may pass a pid that is not > 0 to kill(): kill(-1, SIGKILL) kills every
// process the user owns (it took out two whole login sessions on 2026-10-17).
inline bool child_running(std::atomic<pid_t> & pid_slot, std::string & why) {
pid_t pid = pid_slot.load();
if (pid <= 0) {
return false;
}
int status = 0;
const pid_t result = ::waitpid(pid, &status, WNOHANG);
if (result == 0 || (result < 0 && errno == EINTR)) {
return true;
}
if (result < 0) {
why = std::string("waitpid: ") + std::strerror(errno);
} else if (WIFSIGNALED(status)) {
why = "engine killed by signal " + std::to_string(WTERMSIG(status));
} else if (WIFEXITED(status)) {
why = "engine exited with code " + std::to_string(WEXITSTATUS(status));
} else {
why = "engine exited unexpectedly";
}
pid_slot.compare_exchange_strong(pid, -1);
return false;
}
// One line from the engine, already classified.
struct EngineLine {
enum Kind { NONE, TOKEN, PP, RESUME, REUSED, DONE, ERR, INFO, OTHER, EOF_ } kind = NONE;
std::string raw;
int32_t token = -1;
// PP <done> <total> [<ms> <tok/s>]
long long pp_done = 0, pp_total = 0;
// RESUME <n> / REUSED <n>
long long n = 0;
// DONE <generated> <prompt> <prompt_ms> <decode_ms> <finish> [<drafts_accepted> <drafts_offered> <reused> ...]
long long produced = 0, prompt_n = 0, draft_accepted = 0, draft_offered = 0, reused = 0;
double prompt_ms = 0, decode_ms = 0;
std::string finish; // stop | length | cancel | nonfinite
std::string message; // ERR text
};
class Engine {
public:
Engine() = default;
Engine(const Engine &) = delete;
Engine & operator=(const Engine &) = delete;
~Engine() { quit(); }
// fork+exec `executable` with `args` (args[0] is argv[0]). Must be called before any thread exists.
bool start(const std::string & executable, const std::vector<std::string> & args, std::string & err) {
int to_child[2], from_child[2];
if (::pipe(to_child) != 0 || ::pipe(from_child) != 0) {
err = std::string("pipe: ") + std::strerror(errno);
return false;
}
const pid_t pid = ::fork();
if (pid < 0) {
err = std::string("fork: ") + std::strerror(errno);
return false;
}
if (pid == 0) {
::dup2(to_child[0], STDIN_FILENO);
::dup2(from_child[1], STDOUT_FILENO);
::close(to_child[0]); ::close(to_child[1]); ::close(from_child[0]); ::close(from_child[1]);
std::vector<char *> argv;
for (const std::string & a : args) {
argv.push_back(const_cast<char *>(a.c_str()));
}
argv.push_back(nullptr);
::execv(executable.c_str(), argv.data());
std::fprintf(stderr, "unbiased-strata: could not start the engine %s: %s\n", executable.c_str(), std::strerror(errno));
::_exit(127);
}
pid_ = pid;
::close(to_child[0]);
::close(from_child[1]);
in_fd_ = to_child[1];
out_fd_ = from_child[0];
alive_ = true;
return true;
}
// Reads start-up lines until READY. Loading a model takes minutes; `timeout_s` bounds the wait (<= 0: forever).
// `READY <max_context> [stop]`: the context the engine actually allocated (its VRAM plan may lower the request);
// `stop` means it honours STOP mid-request. INFO lines land in `info`.
bool wait_ready(std::string & err, int timeout_s = 0) {
const int64_t deadline = timeout_s > 0 ? now_ms() + (int64_t) timeout_s * 1000 : 0;
std::string line;
while (true) {
int wait_ms = 1000;
if (deadline) {
const int64_t left = deadline - now_ms();
if (left <= 0) {
err = "the engine did not become ready within " + std::to_string(timeout_s) + " s";
return false;
}
wait_ms = (int) std::min<int64_t>(left, 1000);
}
const int rc = read_line(line, wait_ms);
if (rc < 0) {
err = "the engine exited before it was ready (its messages are above)";
return false;
}
if (rc == 0) {
continue;
}
if (line.rfind("READY", 0) == 0) {
char stop[16] = {0};
long long ctx = 0;
std::sscanf(line.c_str(), "READY %lld %15s", &ctx, stop);
max_context_ = ctx;
can_stop_ = std::strcmp(stop, "stop") == 0;
ready_ = true;
return true;
}
if (line.rfind("INFO ", 0) == 0) {
parse_info(line.substr(5));
continue;
}
if (line.rfind("ERR", 0) == 0) {
err = line.size() > 4 ? line.substr(4) : "the engine reported an error";
return false;
}
if (line.rfind("FATAL", 0) == 0) {
err = line;
return false;
}
// anything else before READY is chatter on stdout; the engine's log is on stderr
}
}
// Writes one request line. `header` is `GEN <max_new> key=value...` or `GENI <max_new> key=value... <file>`.
bool send_request(const std::string & header, const std::vector<int32_t> & ids) {
std::string req = header;
req.reserve(header.size() + ids.size() * 7 + 2);
req += ' ';
for (size_t i = 0; i < ids.size(); ++i) {
if (i) {
req += ',';
}
req += std::to_string(ids[i]);
}
req += '\n';
busy_ = true;
return send(req);
}
// Asks the engine to end the current request. Its output continues until a DONE with finish=cancel.
bool stop() {
return send("STOP\n");
}
// One classified line, waiting at most `timeout_ms` (0: only what is buffered). Returns false on timeout.
// kind == EOF_ when the engine closed its stdout (it exited).
bool next_line(EngineLine & out, int timeout_ms) {
std::string line;
const int rc = read_line(line, timeout_ms);
if (rc == 0) {
return false;
}
out = EngineLine{};
out.raw = line;
if (rc < 0) {
out.kind = EngineLine::EOF_;
return true;
}
classify(line, out);
if (out.kind == EngineLine::DONE || out.kind == EngineLine::ERR) {
busy_ = false;
}
return true;
}
// One command between requests with a one-line reply whose first word is `reply_prefix` (`STATS`, `VRAM`).
bool command(const std::string & line, const char * reply_prefix, std::string & reply, std::string & err, int timeout_ms = 5000) {
if (!alive_) { err = "the engine is not running"; return false; }
if (!send(line + "\n")) { err = "the engine is not running"; return false; }
std::string got;
const int64_t deadline = now_ms() + timeout_ms;
while (true) {
const int64_t left = deadline - now_ms();
if (left <= 0) { err = "no reply from the engine"; return false; }
const int rc = read_line(got, (int) left);
if (rc < 0) { err = "the engine exited"; return false; }
if (rc == 0) { continue; }
if (got.rfind(reply_prefix, 0) == 0) { reply = got; return true; }
if (got.rfind("ERR", 0) == 0) { err = got.size() > 4 ? got.substr(4) : "the engine reported an error"; return false; }
}
}
// Stop the engine: QUIT, up to 10 s for it to leave, then SIGKILL. Safe against reap_exit() on another thread.
void quit() {
// Take the pid out of the shared slot first: from here only this call owns the child, and kill() below
// targets this positive local copy, never the slot (which reads -1 once the supervisor has reaped it).
const pid_t pid = pid_.exchange(-1);
if (pid > 0) {
send("QUIT\n");
int status = 0;
pid_t reaped = 0;
for (int i = 0; i < 100 && (reaped = ::waitpid(pid, &status, WNOHANG)) == 0; ++i) {
::usleep(100 * 1000);
}
if (reaped == 0) { // still running; -1 means another thread already reaped it
::kill(pid, SIGKILL);
::waitpid(pid, &status, 0);
}
}
if (in_fd_ >= 0) { ::close(in_fd_); in_fd_ = -1; }
if (out_fd_ >= 0) { ::close(out_fd_); out_fd_ = -1; }
alive_ = false;
}
// Non-blocking: has the child exited? `why` names the signal or code.
bool reap_exit(std::string & why) {
if (child_running(pid_, why)) {
return false;
}
alive_ = false;
return true;
}
bool alive() const { return alive_; }
bool busy() const { return busy_; }
bool ready() const { return ready_; }
bool can_stop() const { return can_stop_; }
long long max_context() const { return max_context_; }
const std::map<std::string, std::string> & info() const { return info_; }
pid_t pid() const { return pid_; }
static int64_t now_ms() {
struct timespec ts;
::clock_gettime(CLOCK_MONOTONIC, &ts);
return (int64_t) ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
}
private:
bool send(const std::string & s) {
if (in_fd_ < 0) {
return false;
}
size_t off = 0;
while (off < s.size()) {
const ssize_t n = ::write(in_fd_, s.data() + off, s.size() - off);
if (n < 0 && errno == EINTR) {
continue;
}
if (n <= 0) {
alive_ = false;
return false;
}
off += (size_t) n;
}
return true;
}
// 1: a line; 0: timeout; -1: EOF/error
int read_line(std::string & line, int timeout_ms) {
const int64_t deadline = now_ms() + timeout_ms;
while (true) {
const size_t nl = buf_.find('\n');
if (nl != std::string::npos) {
line.assign(buf_, 0, nl);
buf_.erase(0, nl + 1);
while (!line.empty() && line.back() == '\r') {
line.pop_back();
}
return 1;
}
if (out_fd_ < 0) {
return -1;
}
int wait = timeout_ms <= 0 ? 0 : (int) std::max<int64_t>(0, deadline - now_ms());
struct pollfd pfd = { out_fd_, POLLIN, 0 };
const int pr = ::poll(&pfd, 1, wait);
if (pr < 0) {
if (errno == EINTR) {
continue;
}
alive_ = false;
return -1;
}
if (pr == 0) {
return 0;
}
char chunk[65536];
const ssize_t n = ::read(out_fd_, chunk, sizeof chunk);
if (n < 0 && errno == EINTR) {
continue;
}
if (n <= 0) {
// EOF: the engine closed stdout. Hand out what is buffered without a newline, then -1.
if (!buf_.empty()) {
line.swap(buf_);
buf_.clear();
return 1;
}
alive_ = false;
return -1;
}
buf_.append(chunk, (size_t) n);
}
}
void parse_info(const std::string & kv) {
size_t i = 0;
while (i < kv.size()) {
while (i < kv.size() && kv[i] == ' ') ++i;
const size_t j = kv.find(' ', i);
const std::string tok = kv.substr(i, j == std::string::npos ? std::string::npos : j - i);
const size_t eq = tok.find('=');
if (eq != std::string::npos) {
info_[tok.substr(0, eq)] = tok.substr(eq + 1);
}
if (j == std::string::npos) break;
i = j + 1;
}
}
static void classify(const std::string & line, EngineLine & out) {
if (line.size() > 2 && line[0] == 'T' && line[1] == ' ') {
out.kind = EngineLine::TOKEN;
out.token = (int32_t) std::atoi(line.c_str() + 2);
} else if (line.rfind("DONE ", 0) == 0) {
char finish[32] = {0};
// DONE <generated> <prompt> <prompt_ms> <decode_ms> <finish> <drafts_accepted> <drafts_offered> <reused> ...
const int got = std::sscanf(line.c_str(), "DONE %lld %lld %lf %lf %31s %lld %lld %lld", &out.produced, &out.prompt_n,
&out.prompt_ms, &out.decode_ms, finish, &out.draft_accepted, &out.draft_offered, &out.reused);
out.kind = EngineLine::DONE;
out.finish = got >= 5 ? finish : "stop";
} else if (line.rfind("PP ", 0) == 0) {
out.kind = EngineLine::PP;
std::sscanf(line.c_str(), "PP %lld %lld", &out.pp_done, &out.pp_total);
} else if (line.rfind("RESUME ", 0) == 0) {
out.kind = EngineLine::RESUME;
out.n = std::atoll(line.c_str() + 7);
} else if (line.rfind("REUSED ", 0) == 0) {
out.kind = EngineLine::REUSED;
out.n = std::atoll(line.c_str() + 7);
} else if (line.rfind("ERR", 0) == 0) {
out.kind = EngineLine::ERR;
out.message = line.size() > 4 ? line.substr(4) : "the engine reported an error";
} else if (line.rfind("FATAL", 0) == 0) {
out.kind = EngineLine::ERR;
out.message = line;
} else if (line.rfind("INFO ", 0) == 0 || line.rfind("WARN ", 0) == 0) {
out.kind = EngineLine::INFO;
} else {
out.kind = EngineLine::OTHER;
}
}
std::atomic<pid_t> pid_{-1};
int in_fd_ = -1;
int out_fd_ = -1;
std::string buf_;
std::atomic<bool> alive_{false};
bool busy_ = false;
bool ready_ = false;
bool can_stop_ = false;
long long max_context_ = 0;
std::map<std::string, std::string> info_;
};
} // namespace strata_frontend
+225
View File
@@ -0,0 +1,225 @@
// UnbiasedStrata: the front end's program. Mirrors llama.cpp's tools/server/server.cpp without router mode, MCP,
// server-side tools, the web UI and model downloads.
//
// unbiased-strata --engine build/bin/strata-poly -m model.gguf [llama-server options] -- <engine options>
//
// Options before `--` are llama-server's (common_params_parse): -m/--model gives the GGUF the vocabulary and chat
// template are read from, --host/--port/--api-key/--threads-http the listener, --temp/--top-k/... the sampling
// defaults, --reasoning-format/--chat-template-kwargs/--jinja the chat handling. Options after `--` go to the engine
// as they are; `--serve` is added. The engine's READY line gives the context size.
#include "strata_context.hpp"
#include "arg.h"
#include "common.h"
#include "llama.h"
#include "log.h"
#include "server-common.h"
#include "server-stream.h"
#include <atomic>
#include <clocale>
#include <csignal>
#include <cstdio>
#include <cstring>
#include <string>
#include <thread>
#include <vector>
#include <unistd.h>
namespace {
std::function<void(int)> shutdown_handler;
std::atomic_flag is_terminating = ATOMIC_FLAG_INIT;
void signal_handler(int signal) {
if (is_terminating.test_and_set()) {
std::fprintf(stderr, "Received second interrupt, terminating immediately.\n");
std::exit(1);
}
if (shutdown_handler) {
shutdown_handler(signal);
}
}
void usage() {
std::fprintf(stderr,
"usage: unbiased-strata --engine <strata|strata-poly|path> -m <model.gguf> [llama-server options] -- <engine options>\n"
"\n"
" --engine PATH the engine binary; a bare name is looked up beside this program\n"
" -m, --model FILE the GGUF the vocabulary and chat template are read from (no tensors are loaded)\n"
" --host, --port, --api-key, --threads-http, --temp, --top-k, --top-p, --min-p, --reasoning-format,\n"
" --chat-template-kwargs, --alias ... llama-server options (see llama-server --help)\n"
" -- everything after it is passed to the engine; --serve is added\n"
"\n"
"example (Qwen3.6-35B-A3B from its GGUF):\n"
" unbiased-strata --engine strata-poly -m Qwen3.6-35B-A3B-UD-Q3_K_M.gguf --port 8080 \\\n"
" -- --model Qwen3.6-35B-A3B-UD-Q3_K_M.gguf --max-context 32768\n");
}
std::string self_dir() {
char buf[4096];
const ssize_t n = ::readlink("/proc/self/exe", buf, sizeof buf - 1);
if (n <= 0) {
return ".";
}
buf[n] = 0;
std::string p(buf);
const size_t slash = p.find_last_of('/');
return slash == std::string::npos ? "." : p.substr(0, slash);
}
bool file_exists(const std::string & p) {
return ::access(p.c_str(), X_OK) == 0;
}
} // namespace
int main(int argc, char ** argv) {
std::setlocale(LC_NUMERIC, "C");
#ifndef _WIN32
signal(SIGPIPE, SIG_IGN);
#endif
// split: ours (--engine), llama-server's, and after `--` the engine's
std::string engine_exe;
std::vector<std::string> engine_args;
std::vector<char *> llama_argv;
llama_argv.push_back(argv[0]);
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
if (a == "--") {
for (++i; i < argc; ++i) {
engine_args.push_back(argv[i]);
}
break;
}
if (a == "--engine") {
if (i + 1 >= argc) { usage(); return 2; }
engine_exe = argv[++i];
continue;
}
if (a.rfind("--engine=", 0) == 0) {
engine_exe = a.substr(9);
continue;
}
llama_argv.push_back(argv[i]);
}
if (engine_exe.empty()) {
usage();
return 2;
}
if (engine_exe.find('/') == std::string::npos) {
const std::string beside = self_dir() + "/" + engine_exe;
if (file_exists(beside)) {
engine_exe = beside;
}
}
if (!file_exists(engine_exe)) {
std::fprintf(stderr, "unbiased-strata: engine not found or not executable: %s\n", engine_exe.c_str());
return 2;
}
common_params params;
common_init();
server_stream_session_manager_start();
if (!common_params_parse((int) llama_argv.size(), llama_argv.data(), params, LLAMA_EXAMPLE_SERVER)) {
return 1;
}
if (params.model.path.empty()) {
std::fprintf(stderr, "unbiased-strata: -m <model.gguf> is required (the vocabulary and chat template come from it)\n");
return 2;
}
if (!params.mmproj.path.empty()) {
std::fprintf(stderr, "unbiased-strata: --mmproj (images) is not in this build yet; see PLAN.md step 8\n");
return 2;
}
auto model_name = params.model.get_name();
if (params.model_alias.empty() && !model_name.empty()) {
params.model_alias.insert(model_name);
}
llama_backend_init();
llama_numa_init(params.numa);
strata_context ctx_server;
server_http_context ctx_http;
if (!ctx_http.init(params)) {
SRV_ERR("%s", "failed to initialize HTTP server\n");
return 1;
}
// routes first (handlers are not called until is_ready), then the engine (forked before any thread exists),
// then the HTTP thread, which answers /health with 503 while the engine loads
ctx_server.init_routes(ctx_http);
std::string err;
if (!ctx_server.start_engine(params, engine_exe, engine_args, err)) {
SRV_ERR("could not start the engine: %s\n", err.c_str());
return 1;
}
auto clean_up = [&]() {
SRV_INF("%s", "cleaning up before exit...\n");
server_stream_session_manager_stop();
ctx_http.stop();
ctx_server.terminate();
llama_backend_free();
};
if (!ctx_http.start()) {
clean_up();
SRV_ERR("%s", "exiting due to HTTP server error\n");
return 1;
}
if (!ctx_server.load(params, err)) {
SRV_ERR("%s\n", err.c_str());
clean_up();
if (ctx_http.thread.joinable()) {
ctx_http.thread.join();
}
return 1;
}
ctx_http.is_ready.store(true);
SRV_INF("listening on %s, context %lld tokens\n", ctx_http.listening_address.c_str(), ctx_server.n_ctx());
shutdown_handler = [&](int) {
ctx_server.terminate();
};
struct sigaction sigint_action;
sigint_action.sa_handler = signal_handler;
sigemptyset(&sigint_action.sa_mask);
sigint_action.sa_flags = 0;
sigaction(SIGINT, &sigint_action, NULL);
sigaction(SIGTERM, &sigint_action, NULL);
// the engine's exit ends this process too, with a non-zero code, so a unit with Restart=on-failure brings both
// back. A replacement engine is not forked from this multithreaded process (UnbiasedStrata 1 main.cpp:873).
std::atomic<bool> engine_died{false};
std::atomic<bool> stop_supervisor{false};
std::thread supervisor([&]() {
std::string why;
while (!stop_supervisor) {
if (ctx_server.engine_exited(why)) {
SRV_ERR("%s; shutting down so the service manager can restart\n", why.c_str());
engine_died = true;
ctx_server.terminate();
return;
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
});
ctx_server.start_loop(); // blocks until terminate()
stop_supervisor = true;
supervisor.join();
clean_up();
if (ctx_http.thread.joinable()) {
ctx_http.thread.join();
}
return engine_died ? 1 : 0;
}
File diff suppressed because it is too large. Load diff
+46
View File
@@ -0,0 +1,46 @@
// UnbiasedStrata: the server context with a Strata engine behind it.
//
// This is the fork's replacement for llama.cpp's tools/server/server-context.cpp. Everything around it is llama.cpp's
// own, compiled unmodified from the submodule: the HTTP layer (server-http), the task queue and response reader
// (server-queue), the task and result types with their OpenAI/Anthropic/Responses JSON (server-task), request parsing,
// tokenization helpers and SSE formatting (server-common), the request schema (server-schema). What this file adds is
// the part that llama.cpp does with llama_context, llama_batch and common_sampler and that the engine does inside
// its own process: run one request at a time through `strata`/`strata-poly`, turn its `T <id>` lines into partial
// results, and its `DONE` line into the final one.
#pragma once
#include "server-http.h"
#include <memory>
#include <string>
#include <vector>
struct common_params;
struct strata_context_impl;
struct strata_context {
std::unique_ptr<strata_context_impl> impl;
strata_context();
~strata_context();
// Registers the HTTP routes on `http`. Handlers run only once http.is_ready is set, after load().
void init_routes(server_http_context & http);
// fork+exec the engine. Call before any thread exists (before http.start()).
bool start_engine(const common_params & params, const std::string & engine_exe, const std::vector<std::string> & engine_args, std::string & err);
// Loads the vocabulary and chat template from the GGUF (vocab only, no tensors) and waits for the engine's READY.
bool load(common_params & params, std::string & err);
// Blocks the calling thread running the task loop until terminate().
void start_loop();
void terminate();
// Non-blocking: true once the engine process has exited; `why` names the signal or exit code.
bool engine_exited(std::string & why);
bool engine_alive() const;
// the context the engine allocated (READY line)
long long n_ctx() const;
};
+83
View File
@@ -0,0 +1,83 @@
#!/usr/bin/env bash
# UnbiasedStrata: the front end end to end against the fake engine, with a vocabulary-only GGUF from llama.cpp's
# own test models (no GPU, no weights). Checks the HTTP surface a coding agent touches: /health, /v1/models,
# a non-streaming chat completion, a streaming one, a client that disconnects mid-stream, and an engine error.
#
# frontend/tests/e2e.sh <unbiased-strata binary> [model.gguf]
set -u
BIN=${1:?usage: e2e.sh <unbiased-strata> [model.gguf]}
HERE=$(cd "$(dirname "$0")" && pwd)
ROOT=$(cd "$HERE/../.." && pwd)
MODEL=${2:-$ROOT/third_party/llama.cpp/models/ggml-vocab-qwen35.gguf}
PORT=${PORT:-18931}
URL=http://127.0.0.1:$PORT
LOG=$(mktemp "${TMPDIR:-/tmp}/us2-e2e-XXXXXX") # no suffix after the Xs: BSD mktemp rejects it
fail=0
check() { if [ "$1" = 0 ]; then echo "ok $2"; else echo "FAIL $2"; fail=1; fi; }
# j EXPR: evaluate a Python expression over the JSON on stdin (bound to `d`); the test needs python3 anyway, not jq.
j() { python3 -c 'import json,sys; d=json.load(sys.stdin); r=eval(sys.argv[1]); print(json.dumps(r) if isinstance(r,(dict,list)) else ("true" if r is True else "false" if r is False else "null" if r is None else r))' "$1" 2>/dev/null; }
# tokens the fake engine emits: FAKE_TOKENS so the reply does not depend on the template's special tokens
export FAKE_TOKENS="${FAKE_TOKENS:-9707,11,1879,0}" # "Hello, world!" in the Qwen vocabulary
export FAKE_DELAY_MS=${FAKE_DELAY_MS:-0}
"$BIN" --engine "$HERE/fake-engine.py" -m "$MODEL" --host 127.0.0.1 --port "$PORT" --alias fake -- --max-context 4096 > "$LOG" 2>&1 &
PID=$!
trap 'kill $PID 2>/dev/null; wait $PID 2>/dev/null' EXIT
for i in $(seq 1 100); do
if curl -s -o /dev/null -w '%{http_code}' "$URL/health" 2>/dev/null | grep -q 200; then break; fi
if ! kill -0 $PID 2>/dev/null; then echo "FAIL server exited early"; cat "$LOG"; exit 1; fi
sleep 0.2
done
# /health and /v1/models
h=$(curl -s "$URL/health"); check $([ "$(echo "$h" | j 'd["status"]')" = ok ] && echo 0 || echo 1) "/health: $h"
m=$(curl -s "$URL/v1/models"); check $([ "$(echo "$m" | j 'd["data"][0]["id"]')" = fake ] && echo 0 || echo 1) "/v1/models id: $(echo "$m" | j '{k: d["data"][0].get(k) for k in ("id", "context_length")}')"
# non-streaming chat
r=$(curl -s "$URL/v1/chat/completions" -H 'content-type: application/json' -d '{"model":"fake","messages":[{"role":"user","content":"Say hello"}],"max_tokens":32,"temperature":0}')
content=$(echo "$r" | j 'd["choices"][0]["message"]["content"]')
check $([ "$content" = "Hello, world!" ] && echo 0 || echo 1) "chat content: $(echo "$r" | j '{"content": d["choices"][0]["message"]["content"], "finish": d["choices"][0]["finish_reason"], "usage": d["usage"]}')"
check $([ "$(echo "$r" | j 'd["choices"][0]["finish_reason"]')" = stop ] && echo 0 || echo 1) "finish_reason stop"
check $([ "$(echo "$r" | j 'd["usage"]["completion_tokens"]')" = 4 ] && echo 0 || echo 1) "usage.completion_tokens 4"
# streaming chat: role chunk, content deltas, finish chunk, [DONE]
s=$(curl -s -N "$URL/v1/chat/completions" -H 'content-type: application/json' -d '{"model":"fake","stream":true,"messages":[{"role":"user","content":"Say hello"}],"max_tokens":32}')
n_data=$(echo "$s" | grep -c '^data: {')
joined=$(echo "$s" | grep '^data: {' | sed 's/^data: //' | python3 -c 'import json,sys; print("".join((json.loads(l)["choices"][0]["delta"].get("content") or "") for l in sys.stdin if l.strip()), end="")')
check $([ "$joined" = "Hello, world!" ] && echo 0 || echo 1) "stream deltas join to the content ($n_data chunks)"
check $(echo "$s" | grep -q '^data: \[DONE\]' && echo 0 || echo 1) "stream ends with [DONE]"
check $([ "$(echo "$s" | grep '^data: {' | tail -1 | sed 's/^data: //' | j 'd["choices"][0]["finish_reason"]')" = stop ] && echo 0 || echo 1) "stream finish_reason stop"
# a client that disconnects mid-stream: the engine is told to stop and the next request is clean. The fake engine
# reads its env once at start, so this needs a second server whose engine streams a long reply slowly (token 9707,
# "Hello": a raw byte token would not survive the chat parser on the follow-up request).
SLOW_PORT=$((PORT + 1)); SLOW_URL=http://127.0.0.1:$SLOW_PORT; SLOW_LOG=$(mktemp "${TMPDIR:-/tmp}/us2-e2e-slow-XXXXXX")
FAKE_N_TOKENS=100000 FAKE_TOKEN_ID=9707 FAKE_DELAY_MS=10 "$BIN" --engine "$HERE/fake-engine.py" -m "$MODEL" --host 127.0.0.1 --port "$SLOW_PORT" --alias fake -- --max-context 4096 > "$SLOW_LOG" 2>&1 &
SLOW_PID=$!
trap 'kill $PID $SLOW_PID 2>/dev/null; wait $PID $SLOW_PID 2>/dev/null; rm -f "$LOG" "$SLOW_LOG" "$BIG"' EXIT
for i in $(seq 1 100); do
if curl -s -o /dev/null -w '%{http_code}' "$SLOW_URL/health" 2>/dev/null | grep -q 200; then break; fi
if ! kill -0 $SLOW_PID 2>/dev/null; then echo "FAIL slow server exited early"; cat "$SLOW_LOG"; exit 1; fi
sleep 0.2
done
curl -s -N --max-time 1 "$SLOW_URL/v1/chat/completions" -H 'content-type: application/json' -d '{"model":"fake","stream":true,"messages":[{"role":"user","content":"x"}],"max_tokens":4000}' > /dev/null 2>&1
sleep 0.5
r2=$(curl -s --max-time 10 "$SLOW_URL/v1/chat/completions" -H 'content-type: application/json' -d '{"model":"fake","messages":[{"role":"user","content":"again"}],"max_tokens":8}')
check $([ "$(echo "$r2" | j 'd["usage"]["completion_tokens"]')" = 8 ] && [ "$(echo "$r2" | j 'd["choices"][0]["finish_reason"]')" = length ] && echo 0 || echo 1) "request after a disconnected stream: $(echo "$r2" | j '{"finish": d["choices"][0]["finish_reason"], "usage": d["usage"]["completion_tokens"]}')"
check $(grep -q "cancelled by the client" "$SLOW_LOG" && echo 0 || echo 1) "server logged the cancel"
# a prompt that exceeds the context is refused with 400, not 500
big=$(python3 -c 'print("word " * 5000)')
BIG=$(mktemp "${TMPDIR:-/tmp}/us2-e2e-big-XXXXXX")
code=$(curl -s -o "$BIG" -w '%{http_code}' "$URL/v1/chat/completions" -H 'content-type: application/json' -d "{\"model\":\"fake\",\"messages\":[{\"role\":\"user\",\"content\":\"$big\"}]}")
check $([ "$code" = 400 ] && echo 0 || echo 1) "oversize prompt -> $code: $(j 'd["error"]["type"]' < "$BIG")"
# tokenize / detokenize round trip
t=$(curl -s "$URL/tokenize" -H 'content-type: application/json' -d '{"content":"Hello, world!"}' | j 'd["tokens"]')
d=$(curl -s "$URL/detokenize" -H 'content-type: application/json' -d "{\"tokens\":$t}" | j 'd["content"]')
check $([ "$d" = "Hello, world!" ] && echo 0 || echo 1) "tokenize/detokenize round trip: $t"
if [ $fail = 0 ]; then echo "e2e: all checks passed"; else echo "--- server log"; tail -40 "$LOG"; echo "--- slow server log"; tail -20 "$SLOW_LOG"; fi
exit $fail
+162
View File
@@ -0,0 +1,162 @@
// UnbiasedStrata: the engine adapter against the fake engine (frontend/tests/fake-engine.py). No GPU, no model.
//
// c++ -std=c++20 -I frontend frontend/tests/engine_test.cpp -o engine_test && ./engine_test frontend/tests/fake-engine.py
//
// Cases, each the shape of a bug UnbiasedStrata 1 met:
// 1. READY parsed: context and the stop capability
// 2. a request: tokens come back, DONE carries the counts, the adapter is idle afterwards
// 3. cancel: STOP mid-request, the rest is drained to DONE finish=cancel, the next request is clean
// 4. backpressure: a 100k-token burst the caller abandons does not fill the pipe for ever (drain to DONE)
// 5. ERR: a refused request leaves the adapter usable
// 6. the engine dies mid-request: EOF is reported, reap_exit names the exit code
// 7. a DONE whose prompt size does not match is visible to the caller (the context refuses such a reply)
#include "engine.hpp"
#include <cstdio>
#include <cstdlib>
#include <string>
#include <vector>
using strata_frontend::Engine;
using strata_frontend::EngineLine;
static int failures = 0;
#define CHECK(cond) do { if (!(cond)) { std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); ++failures; } } while (0)
struct Run {
std::vector<int32_t> tokens;
EngineLine done;
bool got_done = false, got_err = false, got_eof = false;
std::string err;
};
// read until DONE/ERR/EOF; `cancel_after` tokens -> send STOP; `abandon_after` tokens -> stop reading tokens into
// the vector (the caller is "gone") but keep draining
static Run run(Engine & e, int cancel_after = -1, int timeout_ms = 5000) {
Run r;
EngineLine line;
const int64_t deadline = Engine::now_ms() + timeout_ms;
while (Engine::now_ms() < deadline) {
if (!e.next_line(line, 50)) continue;
switch (line.kind) {
case EngineLine::TOKEN:
r.tokens.push_back(line.token);
if (cancel_after >= 0 && (int) r.tokens.size() == cancel_after) e.stop();
break;
case EngineLine::DONE: r.done = line; r.got_done = true; return r;
case EngineLine::ERR: r.err = line.message; r.got_err = true; return r;
case EngineLine::EOF_: r.got_eof = true; return r;
default: break;
}
}
std::fprintf(stderr, "FAIL: timed out waiting for DONE\n");
++failures;
return r;
}
static bool start(Engine & e, const std::string & script, const std::vector<std::pair<std::string, std::string>> & env) {
for (auto & kv : env) ::setenv(kv.first.c_str(), kv.second.c_str(), 1);
std::string err;
const bool ok = e.start(script, {script}, err) && e.wait_ready(err, 10);
for (auto & kv : env) ::unsetenv(kv.first.c_str());
if (!ok) std::fprintf(stderr, "start: %s\n", err.c_str());
return ok;
}
int main(int argc, char ** argv) {
if (argc < 2) { std::fprintf(stderr, "usage: engine_test <fake-engine.py>\n"); return 2; }
const std::string script = argv[1];
// 1 + 2: READY, one request echoing the prompt
{
Engine e;
CHECK(start(e, script, {{"FAKE_CONTEXT", "2048"}}));
CHECK(e.ready());
CHECK(e.max_context() == 2048);
CHECK(e.can_stop());
CHECK(e.info().count("engine") && e.info().at("engine") == "fake");
CHECK(e.send_request("GEN 10 temperature=0.6", {5, 6, 7}));
CHECK(e.busy());
Run r = run(e);
CHECK(r.got_done);
CHECK((r.tokens == std::vector<int32_t>{5, 6, 7}));
CHECK(r.done.produced == 3 && r.done.prompt_n == 3 && r.done.finish == "stop");
CHECK(!e.busy());
// max_new caps it
CHECK(e.send_request("GEN 2", {1, 2, 3, 4}));
r = run(e);
CHECK(r.got_done && r.tokens.size() == 2 && r.done.finish == "length");
e.quit();
CHECK(!e.alive());
}
// 3: cancel mid-request, then a clean next request
{
Engine e;
CHECK(start(e, script, {{"FAKE_N_TOKENS", "1000"}, {"FAKE_DELAY_MS", "2"}}));
CHECK(e.send_request("GEN 1000", {1}));
Run r = run(e, /* cancel_after */ 5);
CHECK(r.got_done);
CHECK(r.done.finish == "cancel");
CHECK(r.tokens.size() < 1000);
CHECK(e.send_request("GEN 3", {9}));
r = run(e);
CHECK(r.got_done && r.done.finish == "length" && r.tokens.size() == 3);
e.quit();
}
// 4: a burst the caller abandons; the pipe would hold ~64 KB, the burst is ~700 KB
{
Engine e;
CHECK(start(e, script, {{"FAKE_N_TOKENS", "100000"}}));
CHECK(e.send_request("GEN 100000", {1}));
Run r = run(e, /* cancel_after */ 1, /* timeout */ 30000);
CHECK(r.got_done);
// FAKE_N_TOKENS still applies, so the reply is one token of id 100 cut by max_new; what matters is
// that nothing of the abandoned burst leaks into it
CHECK(e.send_request("GEN 1", {2}));
r = run(e);
CHECK(r.got_done && r.tokens.size() == 1 && r.done.finish == "length");
e.quit();
}
// 5: ERR leaves the adapter usable
{
Engine e;
CHECK(start(e, script, {{"FAKE_ERR", "prompt too long"}}));
CHECK(e.send_request("GEN 1", {1}));
Run r = run(e);
CHECK(r.got_err && r.err == "prompt too long");
CHECK(!e.busy());
CHECK(e.alive());
e.quit();
}
// 6: the engine dies mid-request
{
Engine e;
CHECK(start(e, script, {{"FAKE_N_TOKENS", "50"}, {"FAKE_DIE_AFTER", "3"}}));
CHECK(e.send_request("GEN 50", {1}));
Run r = run(e);
CHECK(r.got_eof);
CHECK(r.tokens.size() == 3);
std::string why;
for (int i = 0; i < 50 && !e.reap_exit(why); ++i) ::usleep(10 * 1000);
CHECK(why == "engine exited with code 3");
CHECK(!e.alive());
}
// 7: prompt size mismatch is visible
{
Engine e;
CHECK(start(e, script, {{"FAKE_PROMPT_N", "99"}}));
CHECK(e.send_request("GEN 5", {1, 2}));
Run r = run(e);
CHECK(r.got_done && r.done.prompt_n == 99);
e.quit();
}
if (failures) { std::fprintf(stderr, "%d failure(s)\n", failures); return 1; }
std::printf("engine_test: 7 cases passed\n");
return 0;
}
+109
View File
@@ -0,0 +1,109 @@
#!/usr/bin/env python3
"""A stand-in for strata / strata-poly that speaks the line protocol (docs/BACKENDS.md), for tests without a GPU.
GEN <max_new> [key=value ...] <id,id,...> -> T <id> per token, then DONE
STOP -> the current request ends with finish=cancel
QUIT -> exit 0
Environment variables choose the answers, so one script covers the cases:
FAKE_TOKENS comma-separated ids to emit (default: the prompt ids echoed back, capped by max_new)
FAKE_N_TOKENS emit this many tokens of id FAKE_TOKEN_ID instead (burst tests)
FAKE_TOKEN_ID the id used by FAKE_N_TOKENS (default 100)
FAKE_DELAY_MS sleep this long between tokens (default 0)
FAKE_CONTEXT the context in the READY line (default 4096)
FAKE_ERR if set, answer every GEN with "ERR <text>" instead
FAKE_DIE_AFTER if set, exit 3 after emitting this many tokens of the first request
FAKE_NO_STOP if set, READY without "stop": STOP is ignored and the request runs to its end
FAKE_PROMPT_N if set, lie about the prompt size in DONE (mismatch test)
"""
import os
import select
import sys
import time
out = sys.stdout
def say(s):
out.write(s + "\n")
out.flush()
env = os.environ.get
say("INFO engine=fake batch_slots=0")
say("READY %s%s" % (env("FAKE_CONTEXT", "4096"), "" if env("FAKE_NO_STOP") else " stop"))
first = True
pending = [] # lines read while checking for STOP that are not STOP/QUIT
def readline():
if pending:
return pending.pop(0)
line = sys.stdin.readline()
if line == "":
sys.exit(0)
return line.rstrip("\n")
def stop_requested():
"""Consume what is readable now; True if a STOP was among it."""
stop = False
while select.select([sys.stdin], [], [], 0)[0]:
line = sys.stdin.readline()
if line == "":
sys.exit(0)
line = line.rstrip("\n")
if line == "STOP":
stop = True
elif line == "QUIT":
sys.exit(0)
else:
pending.append(line)
return stop
while True:
line = readline()
if line == "QUIT":
sys.exit(0)
if line == "STOP" or line == "":
continue
parts = line.split()
if parts[0] not in ("GEN", "GENI") or len(parts) < 3:
say("ERR expected: GEN <max_new> <id,id,...>")
continue
max_new = int(parts[1])
prompt = [int(x) for x in parts[-1].split(",") if x]
prompt_n = len(prompt)
if env("FAKE_ERR"):
say("ERR " + env("FAKE_ERR"))
continue
say("RESUME 0")
say("PP %d %d 1 1000" % (prompt_n, prompt_n))
if env("FAKE_N_TOKENS"):
tokens = [int(env("FAKE_TOKEN_ID", "100"))] * int(env("FAKE_N_TOKENS"))
elif env("FAKE_TOKENS"):
tokens = [int(x) for x in env("FAKE_TOKENS").split(",") if x]
else:
tokens = prompt
delay = float(env("FAKE_DELAY_MS", "0")) / 1000.0
die_after = int(env("FAKE_DIE_AFTER", "0") or 0)
produced = 0
finish = "stop"
for t in tokens:
if produced >= max_new:
finish = "length"
break
if stop_requested() and not env("FAKE_NO_STOP"):
finish = "cancel"
break
say("T %d" % t)
produced += 1
if die_after and first and produced >= die_after:
sys.exit(3)
if delay:
time.sleep(delay)
first = False
# DONE <generated> <prompt> <prompt_ms> <decode_ms> <finish> <drafts_accepted> <drafts_offered> <reused>
say("DONE %d %s 12.5 %.1f %s 0 0 0" % (produced, env("FAKE_PROMPT_N", str(prompt_n)), produced * 10.0, finish))
+16
View File
@@ -0,0 +1,16 @@
// UnbiasedStrata: the empty UI asset table (see ui.h).
#include "ui.h"
const llama_ui_asset * llama_ui_find_asset(const std::string & name) {
(void) name;
return nullptr;
}
const std::array<llama_ui_asset, 0> & llama_ui_get_assets() {
static const std::array<llama_ui_asset, 0> empty{};
return empty;
}
bool llama_ui_use_gzip() {
return false;
}
+19
View File
@@ -0,0 +1,19 @@
// UnbiasedStrata: stands in for the ui.h that llama.cpp's tools/ui generates at build time. tools/server/server-http.cpp
// includes it to serve the web UI's embedded assets; this fork ships no UI, so the asset table is empty and every
// lookup misses. Same declarations as tools/ui/ui.h.in with N_ASSETS = 0 and LLAMA_UI_HAS_ASSETS undefined.
#pragma once
#include <array>
#include <string>
struct llama_ui_asset {
std::string name;
const unsigned char * data;
std::size_t size;
std::string etag;
std::string type;
};
const llama_ui_asset * llama_ui_find_asset(const std::string & name);
bool llama_ui_use_gzip();
const std::array<llama_ui_asset, 0> & llama_ui_get_assets();