diff --git a/Makefile b/Makefile index 7c9aaaf..620fb88 100644 --- a/Makefile +++ b/Makefile @@ -12,7 +12,7 @@ LDFLAGS ?= PREFIX ?= /usr/local J_WITH_TLS ?= auto -SRC = src/mesh.c src/mcp.c src/control.c src/control_ops.c src/compress.c src/price.c src/models.c src/config.c src/conn.c src/http.c src/cache.c src/opencode.c src/effort.c src/junction.c +SRC = src/mesh.c src/mcp.c src/control.c src/control_ops.c src/compress.c src/price.c src/models.c src/config.c src/conn.c src/http.c src/cache.c src/opencode.c src/effort.c src/judge.c src/junction.c OBJ = $(SRC:.c=.o) TOOLS = tools/junction-wol diff --git a/README.md b/README.md index c4945f6..f2e304d 100644 --- a/README.md +++ b/README.md @@ -140,6 +140,7 @@ req for "*" pass peer1, cloud ``` req [for ] [path ] [need >N | ] + [judge every N as [cache 5m|1h|off]] ( pass [,...] [as ] | block ) ``` @@ -154,10 +155,43 @@ req [for ] [path ] [need >N | as [cache 5m|1h|off]` — before `pass`: every Nth + request of a conversation is sent to that endpoint with the same body. The rule's + normal targets stay as fallback, so a rate-limited or offline judge still leaves the + worker serving the turn. A judge turn is never answered from junction's response + cache. `cache 1h` adds an Anthropic `cache_control` marker to the last message; the + provider then caches tools, system prompt and the conversation prefix up to that + message. `5m` is cheaper to write, `off` sends no marker. See below. No matching rule → `503 no_matching_rule`: an unmatched request is a config gap, not something to quietly send to a cloud. +### Sampled judge — a virtual model that escalates + +A rule with an exact model name and a `judge` clause becomes a virtual model in +`/v1/models`. The client asks for the virtual name; the worker does the turns, and +every Nth request of the same conversation goes to the judge instead: + +``` +req for "qwen3.6-35b-judged" balance round-robin check none \ + judge every 10 claude-openai0 as "claude-opus-5-5" cache 1h \ + pass qwen3.6-35b as "/models/unsloth/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q8_K_XL.gguf" +``` + +The judge gets the **whole** body, including every previous assistant message, so it +can see what the worker did and correct it. The count is per conversation and per +rule, not global. A conversation is identified by `x-junction-session`, +`x-session-id`, `x-conversation-id` or `x-opencode-session` if the client sends one; +otherwise junction hashes the first system and first user message, which do not change +when a turn is appended. Requests are counted, not user-visible turns: an agent turn +with three tool round-trips counts three times. Use a session header and a larger N +when that matters. + +If the judge fails, the same request is offered to the rule's normal targets. The +fallback gets the original body, without the judge's cache marker. `/v1/models` lists +the virtual model with the smaller context of worker and judge, because the worker +still has to fit ordinary turns. + ### Model policy — what `/v1/models` shows and serves ``` diff --git a/config.example b/config.example index 74c1db0..de52c13 100644 --- a/config.example +++ b/config.example @@ -208,5 +208,15 @@ req for "Qwen3.8-Flash-Next*" check hooks retry 60 pass workstation, peer1, peer # Cheap metadata calls never need a model at all. req path "/v1/models" check none pass peer1, peer2, opencode-go +# A virtual model with a sampled judge: every 10th request of a conversation +# goes to the judge endpoint instead of the worker. The judge comes before +# "pass"; its model is rewritten like any other target's "as". "cache 1h" asks +# Anthropic to cache tools + system + conversation prefix (needs kind remote on +# the Anthropic OpenAI-compatible endpoint, not kind anthropic): +# +# req for "qwen-judged" balance round-robin check none \ +# judge every 10 claude-openai as "claude-opus-5-5" cache 1h \ +# pass peer1 as "qwen3.8" + # Anything unseen is refused rather than silently sent to the opencode-go. req for "*" block diff --git a/src/config.c b/src/config.c index f2aa300..98f4b2b 100644 --- a/src/config.c +++ b/src/config.c @@ -886,6 +886,26 @@ static int parse_rule(char **w, int n, int lineno, j_rule *r, char *err, size_t if (i + 1 >= n) goto bad; snprintf(r->strip, sizeof r->strip, "%s", w[i + 1]); i += 2; + } else if (!strcmp(k, "judge")) { + /* judge every N endpoint as "model" [cache 5m|1h|off] + * Muss vor "pass" stehen: "pass" nimmt den Rest der Zeile als Ziele. */ + if (i + 3 >= n || strcmp(w[i + 1], "every")) goto bad; + long every = 0; + if (as_long(w[i + 2], &every) || every < 1) goto bad; + r->judge_every = (int)every; + snprintf(r->judge_target, sizeof r->judge_target, "%s", w[i + 3]); + i += 4; + if (i + 1 < n && !strcmp(w[i], "as")) { + snprintf(r->judge_as, sizeof r->judge_as, "%s", w[i + 1]); + i += 2; + } + if (i + 1 < n && !strcmp(w[i], "cache")) { + if (!strcmp(w[i + 1], "1h")) r->judge_cache = 2; + else if (!strcmp(w[i + 1], "5m")) r->judge_cache = 1; + else if (!strcmp(w[i + 1], "off")) r->judge_cache = 0; + else goto bad; + i += 2; + } } else if (!strcmp(k, "block")) { r->block = 1; i++; @@ -1361,6 +1381,31 @@ int j_config_load(const char *path, j_config *cfg, char *err, size_t errlen) return -1; } } + if (r->judge_every > 0) { + if (!r->judge_target[0] || !r->judge_as[0]) { + snprintf(err, errlen, + "line %d: judge needs 'every N endpoint as \"model\"'", r->line); + return -1; + } + int found_judge = 0; + for (int e = 0; e < cfg->endpoint_count; e++) + if (!strcmp(cfg->endpoints[e].name, r->judge_target)) { + found_judge = 1; + break; + } + if (!found_judge) { + snprintf(err, errlen, "line %d: judge passes to unknown endpoint '%s'", + r->line, r->judge_target); + return -1; + } + /* The judge is inserted in front of the rule's targets at runtime. */ + if (r->target_count + 1 > J_MAX_TARGETS) { + snprintf(err, errlen, + "line %d: judge needs one more target slot (max %d)", + r->line, J_MAX_TARGETS); + return -1; + } + } } return 0; } diff --git a/src/config.h b/src/config.h index 7813f08..70421bc 100644 --- a/src/config.h +++ b/src/config.h @@ -259,6 +259,13 @@ typedef struct { /* Präfix, das vor dem Weiterleiten vom Modellnamen fällt: `strip "local/"` macht aus * local/qwen3.6-35b das qwen3.6-35b, das die Box kennt. */ char strip[J_NAME_MAX]; + /* Sampled escalation: `judge every N endpoint as "model" [cache 1h]`. + * Every Nth request of a conversation goes to this endpoint instead of the + * rule's targets; if it fails, the rule's targets still serve as fallback. */ + int judge_every; /* 0 = off */ + int judge_cache; /* 0 = off, 1 = 5m, 2 = 1h */ + char judge_target[J_NAME_MAX]; + char judge_as[J_GLOB_MAX]; int target_count; int line; } j_rule; diff --git a/src/judge.c b/src/judge.c new file mode 100644 index 0000000..590dc50 --- /dev/null +++ b/src/judge.c @@ -0,0 +1,336 @@ +/* junction/judge.c — sampled escalation to a stronger model. + * + * The counter is per conversation and per rule. A conversation is identified by a + * session header when the client sends one, otherwise by the first 4 KiB of the + * request body: a chat request grows at the end, so its beginning (model, system + * prompt, tools, first messages) stays stable. That is deliberately a heuristic, + * not a promise; a client that rewrites its early messages gets a new counter. + */ +#define _POSIX_C_SOURCE 200809L + +#include +#include +#include +#include +#include +#include + +#include "judge.h" + +#define JUDGE_SLOTS 256 +#define JUDGE_PROBES 8 +/* After an hour of silence a conversation is over; a late request starts a new + * count instead of inheriting the old one. */ +#define JUDGE_IDLE_S 3600.0 + +typedef struct { + uint64_t key; + unsigned count; + double last; +} judge_slot; + +static judge_slot g_slots[JUDGE_SLOTS]; +static pthread_mutex_t g_slots_mu = PTHREAD_MUTEX_INITIALIZER; + +static double jnow(void) +{ + struct timespec ts; + if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) return 0.0; + return (double)ts.tv_sec + (double)ts.tv_nsec / 1e9; +} + +static uint64_t fnv1a(uint64_t h, const void *data, size_t len) +{ + const unsigned char *p = data; + for (size_t i = 0; i < len; i++) { + h ^= (uint64_t)p[i]; + h *= 1099511628211ULL; + } + return h; +} + +int j_judge_tick(uint64_t conversation, int rule_line, int every) +{ + if (every <= 0) return 0; + if (every == 1) return 1; + + uint64_t key = conversation ? conversation : 1; + key ^= (uint64_t)(unsigned)rule_line * 0x9e3779b97f4a7c15ULL; + if (key == 0) key = 1; + + size_t start = (size_t)(key % JUDGE_SLOTS); + double now = jnow(); + int free_slot = -1; + int oldest = -1; + double oldest_t = 0.0; + + pthread_mutex_lock(&g_slots_mu); + for (int i = 0; i < JUDGE_PROBES; i++) { + size_t ix = (start + (size_t)i) % JUDGE_SLOTS; + judge_slot *s = &g_slots[ix]; + if (s->key == key) { + s->count++; + s->last = now; + int hit = (s->count % (unsigned)every) == 0; + pthread_mutex_unlock(&g_slots_mu); + return hit; + } + if (s->key == 0 || now - s->last > JUDGE_IDLE_S) { + if (free_slot < 0) free_slot = (int)ix; + } + if (oldest < 0 || s->last < oldest_t) { + oldest = (int)ix; + oldest_t = s->last; + } + } + int ix = free_slot >= 0 ? free_slot : oldest; + judge_slot *s = &g_slots[ix]; + s->key = key; + s->count = 1; + s->last = now; + pthread_mutex_unlock(&g_slots_mu); + return 0; +} + +static uint64_t hash_messages(const char *body, const char *end, uint64_t h, int *any); + +uint64_t j_judge_conversation(const char *body, const char *vkey, const char *session) +{ + uint64_t h = 1469598103934665603ULL; + int any = 0; + + if (session && *session) { + h = fnv1a(h, session, strlen(session)); + h = fnv1a(h, "\x1f", 1); + any = 1; + } else if (body && *body) { + /* The system prompt and the first user message do not change when a turn + * is appended. The rest of the conversation does, so it is not part of + * the identity. */ + h = hash_messages(body, body + strlen(body), h, &any); + if (!any) { + size_t n = strlen(body); + if (n > 4096) n = 4096; + h = fnv1a(h, body, n); + h = fnv1a(h, "\x1f", 1); + any = 1; + } + } + if (vkey && *vkey) { + h = fnv1a(h, vkey, strlen(vkey)); + any = 1; + } + if (!any) return 0; + return h ? h : 1; +} + +/* ---------------------------------------------------------------- JSON helpers */ + +static const char *skip_ws(const char *p, const char *end) +{ + while (p < end && isspace((unsigned char)*p)) p++; + return p; +} + +static const char *skip_string(const char *p, const char *end) +{ + if (p >= end || *p != '"') return NULL; + p++; + while (p < end) { + if (*p == '\\') { + if (p + 1 >= end) return NULL; + p += 2; + continue; + } + if (*p == '"') return p + 1; + p++; + } + return NULL; +} + +/* Skip one JSON value, nested objects and arrays included. Braces inside strings + * do not end anything early. */ +static const char *skip_value(const char *p, const char *end) +{ + p = skip_ws(p, end); + if (p >= end) return NULL; + if (*p == '"') return skip_string(p, end); + if (*p != '{' && *p != '[') { + while (p < end && *p != ',' && *p != '}' && *p != ']' && + !isspace((unsigned char)*p)) + p++; + return p; + } + + char stack[64]; + int depth = 0; + while (p < end) { + if (*p == '"') { + p = skip_string(p, end); + if (!p) return NULL; + continue; + } + if (*p == '{' || *p == '[') { + if (depth >= (int)sizeof stack) return NULL; + stack[depth++] = *p++; + } else if (*p == '}' || *p == ']') { + if (depth == 0) return NULL; + char open = stack[--depth]; + if ((*p == '}' && open != '{') || (*p == ']' && open != '[')) return NULL; + p++; + if (depth == 0) return p; + } else { + p++; + } + } + return NULL; +} + +/* Value start of a top-level key. Only the first level is considered, so a tool + * parameter named "messages" cannot be mistaken for the real array. */ +static const char *find_top_value(const char *body, const char *end, const char *key) +{ + const char *p = skip_ws(body, end); + if (p >= end || *p != '{') return NULL; + p++; + for (;;) { + p = skip_ws(p, end); + if (p >= end) return NULL; + if (*p == '}') return NULL; + if (*p != '"') return NULL; + + const char *ks = p; + const char *ke = skip_string(p, end); + if (!ke) return NULL; + size_t klen = (size_t)((ke - 1) - (ks + 1)); + + p = skip_ws(ke, end); + if (p >= end || *p != ':') return NULL; + p = skip_ws(p + 1, end); + + if (klen == strlen(key) && memcmp(ks + 1, key, klen) == 0) + return p; + + p = skip_value(p, end); + if (!p) return NULL; + p = skip_ws(p, end); + if (p < end && *p == ',') { p++; continue; } + if (p < end && *p == '}') return NULL; + return NULL; + } +} + +/* Hash the first system/developer message and the first user message. These are + * the two parts a client keeps while it appends turns. Content is hashed raw + * (string or block array), capped so a giant base64 image does not cost more + * than a few microseconds. */ +static uint64_t hash_messages(const char *body, const char *end, uint64_t h, int *any) +{ + const char *arr = find_top_value(body, end, "messages"); + if (!arr) return h; + arr = skip_ws(arr, end); + if (arr >= end || *arr != '[') return h; + + int have_system = 0, have_user = 0; + const char *p = arr + 1; + while (p < end) { + p = skip_ws(p, end); + if (p >= end || *p == ']') break; + if (*p != '{') { + const char *v = skip_value(p, end); + if (!v) break; + p = v; + } else { + const char *oend = skip_value(p, end); + if (!oend) break; + const char *role_v = find_top_value(p, oend, "role"); + const char *content_v = find_top_value(p, oend, "content"); + if (role_v && content_v) { + const char *re = skip_string(role_v, oend); + const char *ce = skip_value(content_v, oend); + if (re && ce) { + size_t rl = (size_t)((re - 1) - (role_v + 1)); + int is_system = (rl == 6 && memcmp(role_v + 1, "system", 6) == 0) || + (rl == 9 && memcmp(role_v + 1, "developer", 9) == 0); + int is_user = (rl == 4 && memcmp(role_v + 1, "user", 4) == 0); + if ((is_system && !have_system) || (is_user && !have_user)) { + h = fnv1a(h, role_v + 1, rl); + h = fnv1a(h, "\x1f", 1); + size_t cl = (size_t)(ce - content_v); + if (cl > 16384) cl = 16384; + h = fnv1a(h, content_v, cl); + h = fnv1a(h, "\x1e", 1); + if (is_system) have_system = 1; + else have_user = 1; + *any = 1; + if (have_system && have_user) break; + } + } + } + p = oend; + } + p = skip_ws(p, end); + if (p < end && *p == ',') { p++; continue; } + if (p < end && *p == ']') break; + break; + } + return h; +} + +int j_judge_cache_body(const char *body, int ttl_1h, char **out, size_t *outlen) +{ + *out = NULL; + *outlen = 0; + if (!body || !*body) return -1; + /* An explicit marker already in the body wins. Adding a second one would + * either be redundant or land at a place the client did not intend. */ + if (strstr(body, "\"cache_control\"") != NULL) return -1; + + const char *end = body + strlen(body); + const char *arr = find_top_value(body, end, "messages"); + if (!arr) return -1; + arr = skip_ws(arr, end); + if (arr >= end || *arr != '[') return -1; + + const char *p = arr + 1; + const char *last = NULL; + const char *last_end = NULL; + for (;;) { + p = skip_ws(p, end); + if (p >= end) return -1; + if (*p == ']') break; + const char *v = skip_value(p, end); + if (!v) return -1; + if (*p == '{') { + last = p; + last_end = v - 1; + } + p = skip_ws(v, end); + if (p < end && *p == ',') { p++; continue; } + if (p < end && *p == ']') break; + return -1; + } + if (!last || !last_end || *last_end != '}') return -1; + + const char *marker = ttl_1h + ? "\"cache_control\":{\"type\":\"ephemeral\",\"ttl\":\"1h\"}" + : "\"cache_control\":{\"type\":\"ephemeral\"}"; + int empty = (last_end == last + 1); + size_t before = (size_t)(last_end - body); + size_t mlen = strlen(marker); + size_t total = strlen(body) + mlen + (empty ? 0 : 1); + + char *buf = malloc(total + 1); + if (!buf) return -1; + + memcpy(buf, body, before); + size_t o = before; + if (!empty) buf[o++] = ','; + memcpy(buf + o, marker, mlen); + o += mlen; + memcpy(buf + o, last_end, strlen(last_end) + 1); + + *out = buf; + *outlen = total; + return 0; +} diff --git a/src/judge.h b/src/judge.h new file mode 100644 index 0000000..a1cc12e --- /dev/null +++ b/src/judge.h @@ -0,0 +1,33 @@ +/* junction/judge.h — sampled escalation to a stronger model. + * + * A rule can name a judge that handles every Nth request of a conversation. The + * judge sees the same body the worker would have seen, so the full history is + * there; the response is the answer for that turn. Counting is per conversation, + * not global: a conversation is identified by a session header when the client + * sends one, otherwise by the stable beginning of the JSON body (model, system, + * tools, first messages). The tail grows, the beginning does not. + */ +#ifndef JUNCTION_JUDGE_H +#define JUNCTION_JUDGE_H + +#include +#include + +/* Returns 1 when this request is the judge turn. `conversation` comes from + * j_judge_conversation(); `rule_line` keeps counters of different rules apart. + * every <= 0 disables, every == 1 sends everything to the judge. */ +int j_judge_tick(uint64_t conversation, int rule_line, int every); + +/* Stable conversation id: session header if present, else the first 4 KiB of the + * body (the part that does not change when a turn is appended), plus the vkey. + * Returns 0 when there is nothing to identify. */ +uint64_t j_judge_conversation(const char *body, const char *vkey, const char *session); + +/* Add a cache_control marker to the last message of an OpenAI/Anthropic body, + * which caches tools + system + the conversation prefix up to that message. + * ttl_1h: 0 = ephemeral (5 minutes), 1 = one hour. + * Returns 0 and a malloc'ed body when the marker was added; -1 when the body + * already carries one or does not look like a message list. The caller owns *out. */ +int j_judge_cache_body(const char *body, int ttl_1h, char **out, size_t *outlen); + +#endif /* JUNCTION_JUDGE_H */ diff --git a/src/junction.c b/src/junction.c index b78fb6d..378d15c 100644 --- a/src/junction.c +++ b/src/junction.c @@ -15,6 +15,7 @@ #include "compress.h" #include "config.h" #include "models.h" +#include "judge.h" #include "mcp.h" #include "control.h" @@ -3281,10 +3282,27 @@ static void send_mcp_unauthorized(j_conn *c) (void)j_conn_write(c, body, strlen(body), err, sizeof err); } +/* A client that knows its conversation can name it; otherwise the judge falls + * back to the stable beginning of the body. The junction header wins, so a + * constant provider header cannot merge two conversations. */ +static const char *request_session(const j_hdrs *h, char *buf, size_t buflen) +{ + static const char *const names[] = { + "x-junction-session", "x-session-id", "x-conversation-id", "x-opencode-session" + }; + for (size_t i = 0; i < sizeof names / sizeof names[0]; i++) { + if (j_hdrs_find(h, names[i], buf, buflen) == 0 && buf[0] != '\0') + return buf; + } + return NULL; +} + static void handle_client(j_conn *client) { j_buf buf; uint64_t ckey = 0; /* oben, weil 'goto done' die Initialisierung überspringt */ + char *judge_body = NULL; /* dito: 'done' gibt ihn frei */ + size_t judge_len = 0; int flight_leader = 0; j_buf_init(&buf); j_req rq; @@ -3498,6 +3516,7 @@ static void handle_client(j_conn *client) * pool instead of returning 503. The fallback pool's members carry their own * "as" (usually deepseek-v4.1-flash); ctx_fallback_model is the fallback for * members without one. */ + int ctx_fallback_used = 0; if (CFG.ctx_fallback[0] && ctx >= 0) { int fits = 0; for (int t = 0; t < rule_copy.target_count && !fits; t++) { @@ -3536,6 +3555,48 @@ static void handle_client(j_conn *client) } jlog("ctx_fallback", "rule_line=%d ctx=%ld need=%ld pool=%s", rule_copy.line, ctx, need, CFG.ctx_fallback); + ctx_fallback_used = 1; + } + } + } + + /* Sampled escalation: every Nth request of a conversation goes to the judge. + * The judge is inserted in front of the rule's targets, so a failure (429, + * offline, budget) still falls back to the worker instead of failing the turn. + * An oversized context already moved to ctx_fallback; leave that decision alone. */ + int judge_turn = 0; + if (rule->judge_every > 0 && !ctx_fallback_used && rq.body && model[0]) { + char sess[J_HDR_VALUE]; + const char *session = request_session(&rq.hdrs, sess, sizeof sess); + uint64_t conversation = j_judge_conversation(rq.body, vk ? vk->name : "", session); + if (j_judge_tick(conversation, rule->line, rule->judge_every)) { + if (rule_copy.target_count + 1 > J_MAX_TARGETS) { + jlog("judge_skipped", "rule_line=%d reason=target_limit", rule->line); + } else { + if (rule->judge_cache > 0 && + j_judge_cache_body(rq.body, rule->judge_cache == 2, + &judge_body, &judge_len) != 0) { + judge_body = NULL; + judge_len = 0; + } + for (int k = rule_copy.target_count; k > 0; k--) { + snprintf(rule_copy.targets[k], sizeof rule_copy.targets[k], "%s", + rule_copy.targets[k - 1]); + snprintf(rule_copy.target_as[k], sizeof rule_copy.target_as[k], "%s", + rule_copy.target_as[k - 1]); + } + snprintf(rule_copy.targets[0], sizeof rule_copy.targets[0], "%.*s", + (int)sizeof rule_copy.targets[0] - 1, rule->judge_target); + snprintf(rule_copy.target_as[0], sizeof rule_copy.target_as[0], "%.*s", + (int)sizeof rule_copy.target_as[0] - 1, rule->judge_as); + rule_copy.target_count++; + rule_copy.balance = J_BALANCE_FIRST; + judge_turn = 1; + jlog("judge", "rule_line=%d every=%d endpoint=%s model=%s cache=%s " + "conv=%016llx", + rule->line, rule->judge_every, rule->judge_target, rule->judge_as, + judge_body ? (rule->judge_cache == 2 ? "1h" : "5m") : "off", + (unsigned long long)conversation); } } } @@ -3568,7 +3629,10 @@ static void handle_client(j_conn *client) /* a rewritten body must be cached under the model it is actually sent as */ /* Mit zwei möglichen Rümpfen wäre ein Treffer nicht eindeutig: die Antwort auf den * gekürzten Text kann sich von der auf den vollen unterscheiden. Also nicht cachen. */ - int may_cache = comp_body ? 0 : request_is_cacheable(&rq, err, sizeof err); + /* A judge turn must not be answered from the worker's cache: same request, + * different model. */ + int may_cache = (comp_body || judge_turn) ? 0 + : request_is_cacheable(&rq, err, sizeof err); if (may_cache) { ckey = j_cache_key(rq.method, rq.path, model, out_body, out_len); const char *head = NULL, *cbody = NULL; @@ -3823,10 +3887,15 @@ static void handle_client(j_conn *client) continue; } /* Welcher Rumpf geht raus? Ein Ziel mit eigenem Kürzen bekommt den kurzen, - * ein großes den vollen. Beide Schätzungen oben gehören dazu. */ - const char *send_body = (ep_compresses && comp_body) ? comp_body : out_body; - size_t send_len = (ep_compresses && comp_body) ? comp_len : out_len; - if (ep_compresses && comp_body) { + * ein großes den vollen. Der Judge bekommt den vollen Rumpf mit dem + * Cache-Marker; fällt er aus, sieht der Worker wieder den normalen Rumpf. */ + int judge_target = judge_turn && t == 0; + int judge_body_used = judge_target && judge_body != NULL; + const char *send_body = judge_body_used ? judge_body + : ((ep_compresses && comp_body) ? comp_body : out_body); + size_t send_len = judge_body_used ? judge_len + : ((ep_compresses && comp_body) ? comp_len : out_len); + if (!judge_body_used && ep_compresses && comp_body) { /* Erst hier zählen: gekürzt wird zwar für jede Anfrage vorbereitet, aber nur * ein Ziel, das es will, bekommt den kurzen Text. Ein Zähler am Vorbereiten * wäre eine Lüge über die Ersparnis. */ @@ -3912,6 +3981,7 @@ static void handle_client(j_conn *client) done: if (flight_leader && ckey) j_cache_flight_end(ckey); + free(judge_body); free(comp_body); free(rq.body); j_buf_free(&buf); diff --git a/src/models.c b/src/models.c index add9b72..d4dca50 100644 --- a/src/models.c +++ b/src/models.c @@ -322,7 +322,7 @@ long j_models_effective_limit(const char *model, int which) if (strcmp(r->model_glob, model) != 0) continue; /* Pfadspezifische Regeln (z.B. /v1/models) sind keine Modellalias-Ketten. */ if (r->path_glob[0] && strcmp(r->path_glob, "*") != 0) continue; - int is_chain = (r->target_count > 1); + int is_chain = (r->target_count > 1) || r->judge_every > 0; for (int t = 0; !is_chain && t < r->target_count; t++) if (r->target_as[t][0]) is_chain = 1; if (!is_chain) continue; @@ -339,6 +339,16 @@ long j_models_effective_limit(const char *model, int which) if (best <= 0 || lim < best) best = lim; } } + if (r->judge_every > 0 && r->judge_target[0]) { + j_endpoint *ep = find_ep(r->judge_target); + if (ep) { + const char *em = r->judge_as[0] ? r->judge_as : model; + long lim = j_models_limit(ep, em, which); + if (lim <= 0) lim = ep->context; + if (which == 1 && lim <= 0) lim = 0; + if (lim > 0 && (best <= 0 || lim < best)) best = lim; + } + } } return found_rule ? best : 0; } @@ -460,7 +470,7 @@ int j_models_patch_list(const char *json, size_t len, char **out, size_t *out_le if (r->block || r->target_count <= 0) continue; if (!r->model_glob[0] || strchr(r->model_glob, '*') || strchr(r->model_glob, '?')) continue; if (r->path_glob[0] && strcmp(r->path_glob, "*") != 0) continue; - int is_chain = (r->target_count > 1); + int is_chain = (r->target_count > 1) || r->judge_every > 0; for (int t = 0; !is_chain && t < r->target_count; t++) if (r->target_as[t][0]) is_chain = 1; if (!is_chain) continue; const char *name = r->model_glob; diff --git a/tests/judge.sh b/tests/judge.sh new file mode 100644 index 0000000..c9dcb5c --- /dev/null +++ b/tests/judge.sh @@ -0,0 +1,146 @@ +#!/bin/bash +# Wird von tests/run.sh eingebunden: ein virtuelles Modell, bei dem jede N-te +# Anfrage einer Unterhaltung an einen Judge geht. Der Judge sieht den vollen +# Verlauf; fällt er aus, bedient der Worker den Turn. +# +# Die Zählung ist pro Unterhaltung. Der Test hält System-Prompt und erste +# User-Nachricht fest und variiert nur die letzte Nachricht — genau so wächst +# eine Chat-Anfrage. + +echo +echo "== 41. Virtuelles Modell mit sampled Judge ==" + +JW=$((PORT+270)) +JJ=$((PORT+271)) +JP=$((PORT+272)) +JF=$((PORT+273)) +JP2=$((PORT+274)) + +tests/stub $JW "WORKER" > "$TMP/judge_worker.log" 2>&1 & +PIDS+=($!) +tests/stub $JJ "JUDGE" > "$TMP/judge_judge.log" 2>&1 & +PIDS+=($!) +STUB_STATE="$TMP/judge_bad.state" tests/stub $JF "BADJUDGE" --fail-n 100 \ + > "$TMP/judge_bad.log" 2>&1 & +PIDS+=($!) +wait_port $JW 10 || bad "the judge worker stub did not come up" +wait_port $JJ 10 || bad "the judge stub did not come up" +wait_port $JF 10 || bad "the failing judge stub did not come up" + +cat > "$TMP/judge.conf" < "$TMP/judge.log" 2>&1 & +PIDS+=($!) +wait_port "$JP" 10 || bad "the judge instance did not come up" + +SYS="You are a careful reviewer. Keep the answer short and check the previous step." +judge_body() { # judge_body + python3 - "$SYS" "$1" "$2" <<'PY' +import json, sys +print(json.dumps({ + "model": "qwen-judged", + "messages": [ + {"role": "system", "content": sys.argv[1]}, + {"role": "user", "content": sys.argv[2]}, + {"role": "user", "content": sys.argv[3]}, + ], + "max_tokens": 4, +})) +PY +} +judge_ask() { # judge_ask + curl -s -D "$TMP/judge_h.txt" -o "$TMP/judge_b.txt" -m 20 \ + -X POST -H 'Content-Type: application/json' \ + -d "$(judge_body "$2" "$3")" \ + "http://127.0.0.1:$1/v1/chat/completions" + JNAME=$(tr -d '\r' < "$TMP/judge_h.txt" | sed -n 's/^X-Stub-Name: //p') + JCACHE=$(tr -d '\r' < "$TMP/judge_h.txt" | sed -n 's/^X-Stub-Cache-Control: //p') + JMODEL=$(tr -d '\r' < "$TMP/judge_h.txt" | sed -n 's/^X-Stub-Model: //p') +} + +# Unterhaltung A: 3., 6., 9. … Anfrage geht an den Judge. +A=("W" "W" "J" "W" "W" "J") +for i in 1 2 3 4 5 6; do + judge_ask "$JP" "$SYS" "conversation A, turn $i" + if [ "${A[$((i-1))]}" = "J" ]; then + [ "$JNAME" = "JUDGE" ] && ok "turn $i goes to the judge" \ + || bad "turn $i should go to the judge, got '$JNAME'" + [ "$JCACHE" = "1" ] && ok "turn $i carries the cache marker" \ + || bad "turn $i: judge request had no cache_control" + [ "$JMODEL" = "judge-model" ] && ok "turn $i sends the judge model" \ + || bad "turn $i: judge saw model '$JMODEL'" + else + [ "$JNAME" = "WORKER" ] && ok "turn $i stays on the worker" \ + || bad "turn $i should stay on the worker, got '$JNAME'" + [ "$JCACHE" = "0" ] && ok "turn $i has no cache marker for the worker" \ + || bad "turn $i: worker request carried cache_control" + fi +done + +# Unterhaltung B beginnt bei 1, obwohl A schon beim Judge war. +judge_ask "$JP" "A different system prompt for B." "conversation B, turn 1" +[ "$JNAME" = "WORKER" ] && ok "a second conversation starts with the worker" \ + || bad "conversation B inherited A's counter: $JNAME" +judge_ask "$JP" "A different system prompt for B." "conversation B, turn 2" +[ "$JNAME" = "WORKER" ] && ok "the second turn of B is still the worker" \ + || bad "conversation B's second turn hit the judge too early" +judge_ask "$JP" "A different system prompt for B." "conversation B, turn 3" +[ "$JNAME" = "JUDGE" ] && ok "the third turn of B goes to the judge" \ + || bad "conversation B's third turn did not reach the judge" + +contains "$(grep '\[junction\] judge ' "$TMP/judge.log" | head -1)" "cache=1h" \ + "the judge log names the cache TTL" +contains "$(grep '\[junction\] judge ' "$TMP/judge.log" | head -1)" "conv=" \ + "the judge log names the conversation" + +# /v1/models kennt das virtuelle Modell und nimmt die engere Grenze (Worker 8000). +M=$(curl -s -m 10 "http://127.0.0.1:$JP/v1/models") +contains "$M" '"id":"qwen-judged"' "the virtual model is listed" +contains "$M" '"context":8000' "the virtual model keeps the worker's smaller context" + +# Fällt der Judge aus, bedient der Worker den Turn. Der Cache-Marker darf dann +# nicht im Worker-Rumpf landen (der kennt ihn nicht). +cat > "$TMP/judge_fb.conf" < "$TMP/judge_fb.log" 2>&1 & +PIDS+=($!) +wait_port "$JP2" 10 || bad "the judge-fallback instance did not come up" +judge_ask "$JP2" "$SYS" "fallback turn" +[ "$JNAME" = "WORKER" ] && ok "a failing judge falls back to the worker" \ + || bad "the failed judge did not fall back: '$JNAME'" +[ "$JCACHE" = "0" ] && ok "the worker fallback does not receive the judge's cache marker" \ + || bad "the worker fallback received cache_control" +contains "$(cat "$TMP/judge_fb.log")" "upstream_error endpoint=badjudge" \ + "the judge's error body is logged" +contains "$(cat "$TMP/judge_fb.log")" "served_by endpoint=worker" \ + "the fallback is visible in the log" + +# Konfigurationsfehler müssen laut sein. +printf 'endpoint e {\n base http://127.0.0.1:9995/v1\n}\nreq for "vm" judge every 2 missing as "m" pass e\n' \ + > "$TMP/judge_bad_endpoint.conf" +OUT=$(./junction --config "$TMP/judge_bad_endpoint.conf" 2>&1) +contains "$OUT" "judge passes to unknown endpoint" "an unknown judge endpoint is rejected" + +printf 'endpoint e {\n base http://127.0.0.1:9995/v1\n}\nreq for "vm" judge every 0 e as "m" pass e\n' \ + > "$TMP/judge_bad_every.conf" +OUT=$(./junction --config "$TMP/judge_bad_every.conf" 2>&1) +contains "$OUT" "bad arguments" "judge every 0 is rejected" + +printf 'endpoint e {\n base http://127.0.0.1:9995/v1\n}\nreq for "vm" judge every 2 e pass e\n' \ + > "$TMP/judge_no_as.conf" +OUT=$(./junction --config "$TMP/judge_no_as.conf" 2>&1) +contains "$OUT" "judge needs" "a judge without a model is rejected" diff --git a/tests/run.sh b/tests/run.sh index 0771a84..9dea53b 100755 --- a/tests/run.sh +++ b/tests/run.sh @@ -68,7 +68,7 @@ log_has() { # answer requests with somebody else's config), so fail loudly and early. # 8157 gehört auf dieser Maschine dem Hermes-Gateway — der Port wird von keinem # Test benutzt, also darf er die Suite nicht aufhalten. -for port in 8361 8362 8363 8364 8357 8358 8359 8360 8355 8356 8347 8348 8349 8350 8351 8352 8353 8354 8345 8346 8335 8336 8337 8338 8339 8340 8341 8342 8375 8376 8377 8378 8385 8386 8387 8388 8389 8395 8396 8397 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8150 8151 8152 8153 8154 8155 8156 8158 8159 8160 8161 8162 8163 8164 8165 8166 8365 8366 8167 8168 8170 8171 8172 8173 8175 8180 8181 8194 8176 8177 8185 8186 8187 8188 8189 8190 9443 9990 9991 9992 9993 9994 9995 9996; do +for port in 8361 8362 8363 8364 8357 8358 8359 8360 8355 8356 8347 8348 8349 8350 8351 8352 8353 8354 8345 8346 8335 8336 8337 8338 8339 8340 8341 8342 8375 8376 8377 8378 8385 8386 8387 8388 8389 8395 8396 8397 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8150 8151 8152 8153 8154 8155 8156 8158 8159 8160 8161 8162 8163 8164 8165 8166 8365 8366 8405 8406 8407 8408 8409 8167 8168 8170 8171 8172 8173 8175 8180 8181 8194 8176 8177 8185 8186 8187 8188 8189 8190 9443 9990 9991 9992 9993 9994 9995 9996; do if ss -tln 2>/dev/null | grep -q ":$port "; then echo "port $port is busy — a leftover junction/stub is still running:" ss -tlnp 2>/dev/null | grep ":$port " | sed 's/^/ /' @@ -786,6 +786,11 @@ else grep -vE '^\[jenv\]' "$TMP/mcp_env.log" | sed 's/^/ /' | tail -12 fi + +# Virtuelles Modell: jede N-te Anfrage einer Unterhaltung geht an den Judge. +# shellcheck source=tests/judge.sh +. "$(dirname "$0")/judge.sh" + # Gleichzeitigkeit: viele Clients am selben MCP-Eingang, ein langsamer Server # darf die anderen nicht ausbremsen. Zaehlt die Abfragen an die Server mit. echo "== MCP unter Last ==" diff --git a/tests/stub.c b/tests/stub.c index 1d5cc0a..08afd53 100644 --- a/tests/stub.c +++ b/tests/stub.c @@ -258,6 +258,9 @@ int main(int argc, char **argv) find_json_string(req + head_len, "effort", effort, sizeof effort); find_json_string(req + head_len, "type", thinking, sizeof thinking); int has_reasoning = strstr(req + head_len, "\"reasoning\"") != NULL; + /* A judge turn carries a cache_control marker so the provider can reuse + * the conversation prefix. The test reads this header. */ + int has_cache_control = strstr(req + head_len, "\"cache_control\"") != NULL; find_header(req, "X-Custom", custom, sizeof custom); find_header(req, "X-Static", static_hdr, sizeof static_hdr); find_header(req, "X-Forwarded-For", fwd, sizeof fwd); @@ -357,13 +360,15 @@ int main(int argc, char **argv) "X-Stub-Accept: %s\r\n" "X-Stub-Effort: %s\r\nX-Stub-Effort-Set: %d\r\n" "X-Stub-Thinking: %s\r\nX-Stub-Has-Reasoning: %d\r\n" + "X-Stub-Cache-Control: %d\r\n" "X-Stub-XApi-Key: %s\r\n" "X-Stub-Anthropic-Version: %s\r\n" "X-Stub-Anthropic-Versions: %d\r\n" "Connection: close\r\n\r\n%s", strlen(b), name, body_len, custom, static_hdr, fwd, model, authhdr, reasoning, accept, effort, effort[0] ? 1 : 0, thinking, - has_reasoning ? 1 : 0, xapi, av, av_count, b); + has_reasoning ? 1 : 0, has_cache_control ? 1 : 0, + xapi, av, av_count, b); } if (j_conn_write(&client, body, strlen(body), ioerr, sizeof ioerr) < 0) fprintf(stderr, "stub write failed: %s\n", ioerr);