diff --git a/Makefile b/Makefile index 620fb88..8abf59b 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/judge.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/review.c src/junction.c OBJ = $(SRC:.c=.o) TOOLS = tools/junction-wol diff --git a/README.md b/README.md index eb16776..da4e055 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,12 @@ serves it — and what to do when none of them wants to. - **Header passthrough.** Client headers are forwarded (hop-by-hop removed), static headers can be added per endpoint, and `X-Forwarded-For`/`Proto` are appended. Every response carries `X-Junction-Endpoint`, `X-Junction-Ms`, `X-Junction-Cache`. + A sampled judge adds `X-Junction-Judge`, `X-Junction-Judge-Step`, + `X-Junction-Judge-Every`, `X-Junction-Judge-Model`, `X-Junction-Judge-Served`. + A self-review adds `X-Junction-Review`, `X-Junction-Review-Rounds`, + `X-Junction-Review-Model`, `X-Junction-Review-Skipped`. A streaming response + carries the planned judge/review in the head; a reviewed stream puts the actual + outcome in a `junction` object in its final chunk. A worked, annotated configuration for a mixed local/cloud setup is in `examples/olivia.conf`; `config.example` is the same grammar, reduced to the bones. @@ -139,7 +145,7 @@ req for "*" pass peer1, cloud ``` req [for ] [path ] [need >N | ] + [check hooks|none] [retry ] [review N] [judge every N [as ] [cache 5m|1h|off]]... ( pass [,...] [as ] | block ) ``` @@ -150,6 +156,9 @@ req [for ] [path ] [need >N | ` — override `hook_retry` ("wait up to N s for the box"). +- `review N` — before `pass`: N hidden self-review rounds after the first answer. + Only the last answer reaches the client; tool-call answers pass through + unreviewed. See below. - `pass a, b` — try `a`, then `b` on failure. - `as ` — **after a target**, rewrite the `model` field for that target only: `pass peer-a as "qwen3.8-flash-next-q1m", peer-b, cloud` sends the local id to the @@ -205,6 +214,35 @@ fallback gets the original body, without the judge's cache marker. `/v1/models` the virtual model with the smaller context of worker and judge, because the worker still has to fit ordinary turns. +### Self-review — the worker checks itself + +`review N` keeps the worker, but hides N review rounds before the answer is released: + +``` +req for "qwen3.6-35b-checked" balance round-robin check none \ + review 2 \ + pass qwen3.6-35b as "/models/unsloth/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q8_K_XL.gguf" +``` + +The worker answers first. Junction then appends that answer plus a fixed review +instruction to the **same conversation** and sends it back to the same endpoint/model. +That happens N times; only the last answer is written to the client. The intermediate +answers and the review text never reach the client. The review calls are sequential on +the same endpoint and hold the same slot, so a local box sees its own prompt cache again. + +- **Streaming:** the client gets SSE comments while the rounds run, then the final + answer as one final chunk plus `[DONE]`. Non-streaming waits and gets one JSON answer. +- **Tools:** an answer with `tool_calls` is passed through unreviewed; reviewing a tool + call as text would be a different request than the one the client must execute. +- **Failure:** if a review round fails, the last good answer is delivered and + `X-Junction-Review-Skipped` / the `junction` chunk names the reason. The first call + still uses the normal failover. +- **Cost:** `review 2` means three provider calls. They are visible in `/spend` and + count against the vkey budget. +- **Cache:** the original conversation prefix stays the same; only the previous answer + and the review instruction are new. DeepSeek/OpenAI-compatible providers reuse the + prefix automatically; Anthropic endpoints need their explicit marker (see `cache`). + ### Model policy — what `/v1/models` shows and serves ``` diff --git a/config.example b/config.example index 523e19e..121a1ba 100644 --- a/config.example +++ b/config.example @@ -224,6 +224,14 @@ req path "/v1/models" check none pass peer1, peer2, opencode-go # ascending. A pool is allowed as the judge; its members keep their own "as". # "cache" is for Anthropic-style cache_control; DeepSeek/OpenAI-compatible # providers cache prefixes automatically, so leave it off there. +# +# Self-review keeps the worker and hides N review rounds: +# +# req for "qwen-checked" review 2 pass peer1 as "qwen3.8" +# +# The worker's first answer plus a review instruction go back to the same model +# N times; only the last answer reaches the client. Tool-call answers pass +# through unreviewed. "review 2" means three provider calls. # 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 cea53a3..9c66a79 100644 --- a/src/config.c +++ b/src/config.c @@ -886,6 +886,14 @@ 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, "review")) { + /* review N — N hidden self-review rounds after the first answer. + * Muss vor "pass" stehen. */ + if (i + 1 >= n) goto bad; + long count = 0; + if (as_long(w[i + 1], &count) || count < 0 || count > J_MAX_REVIEWS) goto bad; + r->review_count = (int)count; + i += 2; } else if (!strcmp(k, "judge")) { /* judge every N endpoint|pool [as "model"] [cache 5m|1h|off] * Repeatable; the counts are cumulative and the chain resets after its @@ -1391,6 +1399,11 @@ int j_config_load(const char *path, j_config *cfg, char *err, size_t errlen) return -1; } } + if (r->review_count > 0 && r->block) { + snprintf(err, errlen, + "line %d: review on a block rule has no target to review", r->line); + return -1; + } if (r->judge_count > 0) { int max_judge_slots = 0; for (int j = 0; j < r->judge_count; j++) { diff --git a/src/config.h b/src/config.h index 6d72537..8296516 100644 --- a/src/config.h +++ b/src/config.h @@ -55,6 +55,7 @@ #define J_MAX_MODEL_PATTERNS 32 #define J_MAX_POOLS 16 #define J_MAX_JUDGES 4 +#define J_MAX_REVIEWS 4 #define J_MAX_MCP 16 #define J_MAX_CACHE_PEERS 8 /* Endliche Latenzgrenzen in Sekunden; dazu kommt der +Inf-Eimer. */ @@ -271,6 +272,7 @@ typedef struct { char as[J_GLOB_MAX]; } judges[J_MAX_JUDGES]; int judge_count; + int review_count; /* hidden self-review rounds before the answer */ int target_count; int line; } j_rule; diff --git a/src/control_ops.c b/src/control_ops.c index ac3b136..2fcf475 100644 --- a/src/control_ops.c +++ b/src/control_ops.c @@ -106,10 +106,10 @@ static char *ops_rules_list(size_t *len) "%s{\"index\":%d,\"line\":%d,\"model\":\"%s\",\"path\":\"%s\"," "\"block\":%s,\"need_min\":%ld,\"need_max\":%ld," "\"ctx_min\":%ld,\"ctx_max\":%ld,\"vision\":%d,\"targets\":\"%s\"," - "\"judge\":\"%s\"}", + "\"judge\":\"%s\",\"review\":%d}", i ? "," : "", i, r->line, model, path, r->block ? "true" : "false", r->need_min, r->need_max, - r->ctx_min, r->ctx_max, r->vision, tgt, jgt); + r->ctx_min, r->ctx_max, r->vision, tgt, jgt, r->review_count); j_buf_append(&b, one, (size_t)n); } j_rules_write_unlock(); diff --git a/src/junction.c b/src/junction.c index 90970d9..e6c95aa 100644 --- a/src/junction.c +++ b/src/junction.c @@ -16,6 +16,7 @@ #include "config.h" #include "models.h" #include "judge.h" +#include "review.h" #include "mcp.h" #include "control.h" @@ -74,6 +75,19 @@ static __thread int t_retry_after_s; static __thread j_conn *t_heartbeat; static __thread double t_heartbeat_started; +/* Judge/review metadata for the response headers. Set before the target loop and + * read by forward_step, sse_open and review_serve. Thread-local like the rest. */ +static __thread int t_judge_active; +static __thread int t_judge_served; +static __thread int t_judge_step; +static __thread int t_judge_every; +static __thread char t_judge_target[J_NAME_MAX]; +static __thread char t_judge_model[J_GLOB_MAX]; +static __thread int t_review_count; +static __thread int t_review_done; +static __thread char t_review_model[J_GLOB_MAX]; +static __thread char t_review_skipped[32]; + #define STATE_LOCK() pthread_mutex_lock(&g_state_mu) #define STATE_UNLOCK() pthread_mutex_unlock(&g_state_mu) @@ -519,12 +533,33 @@ static int read_request(j_conn *c, j_buf *buf, j_req *rq, char *err, size_t errl static int sse_open(j_conn *client) { char err[128]; - const char *head = "HTTP/1.1 200 OK\r\n" - "Content-Type: text/event-stream\r\n" - "Cache-Control: no-cache\r\n" - "X-Accel-Buffering: no\r\n" - "Connection: close\r\n\r\n"; - return j_conn_write(client, head, strlen(head), err, sizeof err) < 0 ? -1 : 0; + char head[2048]; + int n = snprintf(head, sizeof head, + "HTTP/1.1 200 OK\r\n" + "Content-Type: text/event-stream\r\n" + "Cache-Control: no-cache\r\n" + "X-Accel-Buffering: no\r\n"); + if (n < 0 || (size_t)n >= sizeof head) return -1; + if (t_judge_active) { + int w = snprintf(head + n, sizeof head - (size_t)n, + "X-Junction-Judge: %s\r\n" + "X-Junction-Judge-Step: %d\r\n" + "X-Junction-Judge-Every: %d\r\n" + "X-Junction-Judge-Model: %s\r\n", + t_judge_target, t_judge_step, t_judge_every, t_judge_model); + if (w < 0 || (size_t)w >= sizeof head - (size_t)n) return -1; + n += w; + } + if (t_review_count > 0) { + int w = snprintf(head + n, sizeof head - (size_t)n, + "X-Junction-Review: %d\r\n", t_review_count); + if (w < 0 || (size_t)w >= sizeof head - (size_t)n) return -1; + n += w; + } + int w = snprintf(head + n, sizeof head - (size_t)n, "Connection: close\r\n\r\n"); + if (w < 0 || (size_t)w >= sizeof head - (size_t)n) return -1; + n += w; + return j_conn_write(client, head, (size_t)n, err, sizeof err) < 0 ? -1 : 0; } static int sse_comment(j_conn *client, const char *fmt, ...) @@ -929,10 +964,10 @@ static char *build_status(size_t *len_out) used += (size_t)snprintf(out + used, cap - used, "%s{\"line\":%d,\"model\":\"%s\",\"path\":\"%s\",\"block\":%s,\"need_min\":%ld," "\"need_max\":%ld,\"ctx_min\":%ld,\"ctx_max\":%ld,\"vision\":%d," - "\"targets\":\"%s\",\"judge\":\"%s\"}", + "\"targets\":\"%s\",\"judge\":\"%s\",\"review\":%d}", i ? "," : "", r->line, r->model_glob, r->path_glob, r->block ? "true" : "false", r->need_min, r->need_max, - r->ctx_min, r->ctx_max, r->vision, chain, judges); + r->ctx_min, r->ctx_max, r->vision, chain, judges, r->review_count); } used += (size_t)snprintf(out + used, cap - used, "],"); /* MCP: welche Server angebunden sind, wie viele Werkzeuge sie liefern und @@ -1909,6 +1944,46 @@ static const j_pool *find_pool(const char *name) return NULL; } +/* Did this endpoint actually serve the judge step (endpoint or one of its pool + * members)? Used for X-Junction-Judge-Served; a worker fallback stays 0. */ +static int judge_endpoint_matches(const char *name) +{ + if (!t_judge_active) return 0; + const j_pool *p = find_pool(t_judge_target); + if (p) { + for (int i = 0; i < p->count; i++) + if (!strcmp(p->targets[i], name)) return 1; + return 0; + } + return !strcmp(t_judge_target, name); +} + +/* The same metadata on every path: normal JSON responses get it in forward_step, + * review_serve builds its own head, and sse_open writes the planned part. */ +static void add_route_meta_headers(j_hdrs *h) +{ + char v[32]; + if (t_judge_active) { + j_hdrs_set(h, "X-Junction-Judge", t_judge_target); + snprintf(v, sizeof v, "%d", t_judge_step); + j_hdrs_set(h, "X-Junction-Judge-Step", v); + snprintf(v, sizeof v, "%d", t_judge_every); + j_hdrs_set(h, "X-Junction-Judge-Every", v); + j_hdrs_set(h, "X-Junction-Judge-Model", t_judge_model); + j_hdrs_set(h, "X-Junction-Judge-Served", t_judge_served ? "1" : "0"); + } + if (t_review_count > 0) { + snprintf(v, sizeof v, "%d", t_review_count); + j_hdrs_set(h, "X-Junction-Review", v); + snprintf(v, sizeof v, "%d", t_review_done); + j_hdrs_set(h, "X-Junction-Review-Rounds", v); + if (t_review_model[0]) + j_hdrs_set(h, "X-Junction-Review-Model", t_review_model); + if (t_review_skipped[0]) + j_hdrs_set(h, "X-Junction-Review-Skipped", t_review_skipped); + } +} + static char *rewrite_model(const char *body, const char *new_model) { if (!body) return NULL; @@ -2645,7 +2720,8 @@ static void log_upstream_error_body(j_conn *up, j_upstream_resp *r, const char * static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq, const char *out_body, size_t out_len, const char *as_model, const char *rq_model, const char *cache_state, double req_started, - int head_sent, const char *vkey_name, char *err, size_t errlen) + int head_sent, const char *vkey_name, j_buf *capture, + char *err, size_t errlen) { char host[J_NAME_MAX], port[16], prefix[J_URL_MAX]; int tls = 0; @@ -2878,6 +2954,16 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq, free(body_alloc); return -1; } + /* A review call must not write an error into the client's open stream: it is an + * internal extra call, and the caller keeps the last good answer. */ + if (capture && (r.status < 200 || r.status >= 300)) { + log_upstream_error_body(&up, &r, ep->name); + snprintf(err, errlen, "upstream_status_%d", r.status); + resp_free(&r); + j_conn_close(&up); + free(body_alloc); + return -1; + } /* Once the stream head is out the caller has a 200; anything that goes wrong from * here has to be an event, and failing over is no longer possible. */ if (head_sent && r.status >= 400) { @@ -2914,8 +3000,9 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq, char cc[J_HDR_VALUE]; int resp_no_store = !j_hdrs_find(&r.hdrs, "Cache-Control", cc, sizeof cc) && (strstr(cc, "no-store") || strstr(cc, "private")); - int store = (CFG.cache_ttl_s > 0) && (ep->cache_on != 0) && (r.status == 200) && - !resp_no_store && out_len > 0 && !json_bool_value(out_body, "stream"); + int store = (capture == NULL) && (CFG.cache_ttl_s > 0) && (ep->cache_on != 0) && + (r.status == 200) && !resp_no_store && out_len > 0 && + !json_bool_value(out_body, "stream"); /* Verbrauch lässt sich nur zählen, wenn die Antwort ganz vorliegt. Bei gesetzter * Preistabelle wird deshalb auch ohne Cache vollständig gelesen — ein nicht @@ -2928,9 +3015,13 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq, char msbuf[32]; snprintf(msbuf, sizeof msbuf, "%ld", (long)((now_s() - req_started) * 1000.0)); + if (r.status >= 200 && r.status < 300 && + t_judge_active && judge_endpoint_matches(ep->name)) + t_judge_served = 1; j_hdrs_set(&r.hdrs, "X-Junction-Endpoint", ep->name); j_hdrs_set(&r.hdrs, "X-Junction-Ms", msbuf); j_hdrs_set(&r.hdrs, "X-Junction-Cache", cache_state); + add_route_meta_headers(&r.hdrs); /* Verbrauch und Kosten über den Block hinaus, damit die Logzeile auch dann * geschrieben wird, wenn die Antwort keine Nutzungszahlen trägt: eine Anfrage, die @@ -2938,7 +3029,8 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq, long l_in = 0, l_out = 0, l_cached = 0; double l_cost = -1.0; - if ((store || want_usage || want_models_rewrite) && !head_sent) { + if ((store || want_usage || want_models_rewrite || capture) && + (!head_sent || capture)) { char *body = NULL; size_t body_len = 0; if (read_full_body(&up, &r.buf, r.body_off, r.chunked, r.content_length, @@ -3030,27 +3122,42 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq, } } - /* cache the serialized head *with* its final headers, then send the same bytes */ - char *headcopy = malloc(HDR_BLOCK_MAX); - size_t headused = 0; - if (headcopy) { - headused = (size_t)snprintf(headcopy, HDR_BLOCK_MAX, "HTTP/1.1 %d %s\r\n", - r.status, r.reason[0] ? r.reason : "OK"); - j_hdrs tmp = r.hdrs; - headused += j_hdrs_serialize(&tmp, headcopy + headused, HDR_BLOCK_MAX - headused, - 1, 1); - uint64_t fill_key = j_cache_key(rq->method, rq->path, rq_model, cache_body, cache_len); - j_cache_put(fill_key, headcopy, headused, body, body_len, CFG.cache_ttl_s); - /* Der Nachbar soll dieselbe Antwort nicht noch einmal bezahlen. Der Aufruf - * kehrt sofort zurück; ein nicht erreichbarer Nachbar kostet hier nichts. */ - j_mesh_store(fill_key, headcopy, headused, body, body_len, CFG.cache_ttl_s); - free(headcopy); + if (!capture) { + /* cache the serialized head *with* its final headers, then send the same bytes */ + char *headcopy = malloc(HDR_BLOCK_MAX); + size_t headused = 0; + if (headcopy) { + headused = (size_t)snprintf(headcopy, HDR_BLOCK_MAX, "HTTP/1.1 %d %s\r\n", + r.status, r.reason[0] ? r.reason : "OK"); + j_hdrs tmp = r.hdrs; + headused += j_hdrs_serialize(&tmp, headcopy + headused, HDR_BLOCK_MAX - headused, + 1, 1); + uint64_t fill_key = j_cache_key(rq->method, rq->path, rq_model, cache_body, cache_len); + j_cache_put(fill_key, headcopy, headused, body, body_len, CFG.cache_ttl_s); + /* Der Nachbar soll dieselbe Antwort nicht noch einmal bezahlen. Der Aufruf + * kehrt sofort zurück; ein nicht erreichbarer Nachbar kostet hier nichts. */ + j_mesh_store(fill_key, headcopy, headused, body, body_len, CFG.cache_ttl_s); + free(headcopy); + } } double now_ms = (now_s() - req_started) * 1000.0; reqlog_append(vkey_name, (as_model && as_model[0]) ? as_model : rq_model, ep->name, r.status, now_ms, upstream_part(now_ms), t_queue_ms, t_rule_line, cache_state, t_req_retries, l_in, l_out, l_cached, l_cost >= 0 ? l_cost : 0.0); + if (capture) { + int crc = j_buf_append(capture, body, body_len); + free(body); + resp_free(&r); + j_conn_close(&up); + free(body_alloc); + t_heartbeat = NULL; + if (crc != 0) { + snprintf(err, errlen, "capture_failed"); + return -1; + } + return 0; + } int rc = send_head(client, r.status, r.reason, &r.hdrs, (long)body_len, err, errlen); if (rc == 0 && body_len && j_conn_write(client, body, body_len, err, errlen) < 0) rc = -1; @@ -3086,6 +3193,17 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq, t_rule_line, cache_state, t_req_retries, l_in, l_out, l_cached, l_cost >= 0 ? l_cost : 0.0); } + /* The head is already out, so the actual outcome travels as an SSE comment. + * Review turns get the richer `junction` object in their final chunk instead. */ + if (rc == 0 && (t_judge_active || t_review_count > 0)) { + char note[256]; + int n = snprintf(note, sizeof note, + ": junction: judge_served=%d endpoint=%s review_rounds=%d\n\n", + t_judge_served, ep->name, t_review_done); + if (n > 0 && (size_t)n < sizeof note && + j_conn_write(client, note, (size_t)n, err, errlen) < 0) + rc = -1; + } t_heartbeat = NULL; resp_free(&r); j_conn_close(&up); @@ -3118,7 +3236,7 @@ static int forward_with_retry(j_conn *client, j_endpoint *ep, const j_req *rq, const char *body, size_t len, const char *as_model, const char *rq_model, const char *cache_state, double started, int head_sent, const char *vkey_name, - char *err, size_t errlen) + j_buf *capture, char *err, size_t errlen) { int tries = CFG.retry_num > 0 ? CFG.retry_num : 0; /* Ein Schlüssel mehr im Pool ist ein Versuch mehr: sonst käme das zweite Konto @@ -3149,7 +3267,7 @@ static int forward_with_retry(j_conn *client, j_endpoint *ep, const j_req *rq, t_req_retries++; } rc = forward_step(client, ep, rq, body, len, as_model, rq_model, cache_state, - started, head_sent, vkey_name, err, errlen); + started, head_sent, vkey_name, capture, err, errlen); if (rc == 0 || rc == -2) return rc; if (!err_retryable(err)) return rc; } @@ -3167,6 +3285,156 @@ static int forward_with_retry(j_conn *client, j_endpoint *ep, const j_req *rq, return rc; } +/* Hidden self-review: the first answer is buffered, then review_count calls append + * that answer and the review instruction to the same conversation. Only the last + * answer is written to the client. A failed review is not fatal; the last good + * answer is delivered. Tool-call answers are passed through unreviewed. */ +static int review_serve(j_conn *client, j_endpoint *ep, const j_req *rq, + const char *body, const char *as_model, + const char *rq_model, int review_count, int streaming, + double started, const char *vkey_name, char *err, size_t errlen) +{ + char *ns = NULL; + size_t ns_len = 0; + t_review_count = review_count; + t_review_done = 0; + t_review_skipped[0] = '\0'; + snprintf(t_review_model, sizeof t_review_model, "%s", + as_model[0] ? as_model : rq_model); + if (j_review_nonstream(body, &ns, &ns_len) != 0) { + snprintf(t_review_skipped, sizeof t_review_skipped, "body"); + snprintf(err, errlen, "review_body"); + return -1; + } + + j_buf cap; + j_buf_init(&cap); + int rc = forward_with_retry(client, ep, rq, ns, ns_len, as_model, rq_model, + "off", now_s(), streaming, vkey_name, &cap, err, errlen); + if (rc != 0) { + free(ns); + j_buf_free(&cap); + return rc; + } + + char *answer = NULL; + int tools = 0; + int have_answer = (j_review_extract(cap.data, &answer, &tools) == 0 && + answer != NULL && answer[0] != '\0'); + char *current = have_answer ? answer : NULL; + if (!have_answer) free(answer); + + if (tools) { + snprintf(t_review_skipped, sizeof t_review_skipped, "tool_calls"); + jlog("review", "round=0 endpoint=%s skipped=tool_calls", ep->name); + } else if (!have_answer) { + snprintf(t_review_skipped, sizeof t_review_skipped, "no_text"); + } + + char *last_json = strdup(cap.data ? cap.data : ""); + if (!last_json) { + free(current); + free(ns); + j_buf_free(&cap); + snprintf(err, errlen, "review_oom"); + return -1; + } + + for (int round = 1; round <= review_count && current && !tools; round++) { + char *rb = NULL; + size_t rb_len = 0; + if (j_review_body(ns, current, &rb, &rb_len) != 0) { + snprintf(t_review_skipped, sizeof t_review_skipped, "body"); + jlog("review", "round=%d endpoint=%s skipped=body", round, ep->name); + break; + } + j_buf_reset(&cap); + int rrc = forward_with_retry(client, ep, rq, rb, rb_len, as_model, rq_model, + "off", now_s(), streaming, vkey_name, &cap, + err, errlen); + free(rb); + if (rrc != 0) { + snprintf(t_review_skipped, sizeof t_review_skipped, "error"); + jlog("review", "round=%d endpoint=%s ok=0 error=%s", round, ep->name, err); + break; + } + char *next = NULL; + int next_tools = 0; + if (j_review_extract(cap.data, &next, &next_tools) != 0 || + next == NULL || next[0] == '\0' || next_tools) { + snprintf(t_review_skipped, sizeof t_review_skipped, "%s", + next_tools ? "tool_calls" : "no_text"); + jlog("review", "round=%d endpoint=%s skipped=%s", round, ep->name, + next_tools ? "tool_calls" : "no_text"); + free(next); + break; + } + free(current); + current = next; + char *fresh = strdup(cap.data ? cap.data : ""); + if (fresh) { + free(last_json); + last_json = fresh; + } + t_review_done++; + jlog("review", "round=%d endpoint=%s ok=1 chars=%zu", round, ep->name, + strlen(current)); + } + + char jt[2 * J_NAME_MAX], jm[2 * J_GLOB_MAX], rm[2 * J_GLOB_MAX]; + char rs[128], en[2 * J_NAME_MAX]; + json_escape(t_judge_active ? t_judge_target : "", jt, sizeof jt); + json_escape(t_judge_active ? t_judge_model : "", jm, sizeof jm); + json_escape(t_review_model, rm, sizeof rm); + json_escape(t_review_skipped, rs, sizeof rs); + json_escape(ep->name, en, sizeof en); + char meta[2048]; + snprintf(meta, sizeof meta, + "{\"review_rounds\":%d,\"review_model\":\"%s\"," + "\"review_skipped\":\"%s\",\"judge\":\"%s\"," + "\"judge_model\":\"%s\",\"judge_step\":%d,\"judge_every\":%d," + "\"judge_served\":%d,\"endpoint\":\"%s\"}", + t_review_done, rm, rs, jt, jm, t_judge_step, t_judge_every, + t_judge_served, en); + + if (streaming) { + char *frames = NULL; + size_t flen = 0; + if (j_review_sse(last_json, rq_model, meta, &frames, &flen) != 0) { + sse_error(client, 502, "review: no answer to stream"); + rc = -2; + } else { + rc = j_conn_write(client, frames, flen, err, errlen) < 0 ? -2 : 0; + free(frames); + } + } else { + j_hdrs h; + j_hdrs_init(&h); + char cl[32], ms[32]; + snprintf(cl, sizeof cl, "%zu", strlen(last_json)); + snprintf(ms, sizeof ms, "%ld", (long)((now_s() - started) * 1000.0)); + j_hdrs_set(&h, "Content-Type", "application/json"); + j_hdrs_set(&h, "Content-Length", cl); + j_hdrs_set(&h, "Connection", "close"); + j_hdrs_set(&h, "X-Junction-Endpoint", ep->name); + j_hdrs_set(&h, "X-Junction-Ms", ms); + j_hdrs_set(&h, "X-Junction-Cache", "off"); + add_route_meta_headers(&h); + int hrc = send_head(client, 200, "OK", &h, (long)strlen(last_json), + err, errlen); + if (hrc == 0) + hrc = j_conn_write(client, last_json, strlen(last_json), + err, errlen) < 0 ? -1 : 0; + rc = hrc == 0 ? 0 : -2; + } + + free(current); + free(last_json); + free(ns); + j_buf_free(&cap); + return rc; +} + /* --------------------------------------------------------------- connection */ static int request_is_cacheable(const j_req *rq, char *why, size_t whylen) { @@ -3315,6 +3583,16 @@ static void handle_client(j_conn *client) size_t judge_len = 0; int flight_leader = 0; j_buf_init(&buf); + t_judge_active = 0; + t_judge_served = 0; + t_judge_step = 0; + t_judge_every = 0; + t_judge_target[0] = '\0'; + t_judge_model[0] = '\0'; + t_review_count = 0; + t_review_done = 0; + t_review_model[0] = '\0'; + t_review_skipped[0] = '\0'; j_req rq; char err[512] = ""; if (read_request(client, &buf, &rq, err, sizeof err)) { @@ -3521,6 +3799,7 @@ static void handle_client(j_conn *client) send_simple(client, 403, "Forbidden", body); goto done; } + t_review_count = rule->review_count; /* If no target of this rule can hold ctx + need, try the configured fallback * pool instead of returning 503. The fallback pool's members carry their own @@ -3625,6 +3904,13 @@ static void handle_client(j_conn *client) rule_copy.balance = J_BALANCE_FIRST; judge_turn = 1; judge_slots = slots; + t_judge_active = 1; + t_judge_served = 0; + t_judge_step = step; + t_judge_every = rule->judges[step].every; + snprintf(t_judge_target, sizeof t_judge_target, "%s", target); + snprintf(t_judge_model, sizeof t_judge_model, "%s", + judge_as[0] ? judge_as : "pool"); jlog("judge", "rule_line=%d step=%d every=%d target=%s slots=%d model=%s " "cache=%s conv=%016llx", rule->line, step, rule->judges[step].every, target, slots, @@ -3665,7 +3951,7 @@ static void handle_client(j_conn *client) * gekürzten Text kann sich von der auf den vollen unterscheiden. Also nicht cachen. */ /* A judge turn must not be answered from the worker's cache: same request, * different model. */ - int may_cache = (comp_body || judge_turn) ? 0 + int may_cache = (comp_body || judge_turn || rule->review_count > 0) ? 0 : request_is_cacheable(&rq, err, sizeof err); if (may_cache) { ckey = j_cache_key(rq.method, rq.path, model, out_body, out_len); @@ -3942,9 +4228,25 @@ static void handle_client(j_conn *client) * umschreiben, sonst steht der Name nur im Router anders da als bei der Box. */ const char *send_model = rule->target_as[t][0] ? rule->target_as[t] : (eff_model != model ? eff_model : ""); - int rc = forward_with_retry(client, ep, &rq, send_body, send_len, send_model, eff_model, - may_cache ? "miss" : "off", started, head_sent, - vk ? vk->name : "", err, sizeof err); + snprintf(t_review_model, sizeof t_review_model, "%s", + send_model[0] ? send_model : eff_model); + t_review_done = 0; + t_review_skipped[0] = '\0'; + int can_review = rule->review_count > 0 && + !strncmp(rq.path, "/v1/chat/completions", 20) && + strcmp(ep->kind, "opencode") != 0 && + strcmp(ep->kind, "anthropic") != 0; + if (rule->review_count > 0 && !can_review) { + snprintf(t_review_skipped, sizeof t_review_skipped, "protocol"); + jlog("review_skipped", "endpoint=%s reason=protocol", ep->name); + } + int rc = can_review + ? review_serve(client, ep, &rq, send_body, send_model, eff_model, + rule->review_count, streaming, started, + vk ? vk->name : "", err, sizeof err) + : forward_with_retry(client, ep, &rq, send_body, send_len, send_model, eff_model, + may_cache ? "miss" : "off", started, head_sent, + vk ? vk->name : "", NULL, err, sizeof err); STATE_LOCK(); ep->inflight--; STATE_UNLOCK(); diff --git a/src/models.c b/src/models.c index 9c55708..266b734 100644 --- a/src/models.c +++ b/src/models.c @@ -329,7 +329,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) || r->judge_count > 0; + int is_chain = (r->target_count > 1) || r->judge_count > 0 || r->review_count > 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; @@ -494,7 +494,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) || r->judge_count > 0; + int is_chain = (r->target_count > 1) || r->judge_count > 0 || r->review_count > 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/src/review.c b/src/review.c new file mode 100644 index 0000000..39a2eba --- /dev/null +++ b/src/review.c @@ -0,0 +1,416 @@ +/* junction/review.c — hidden self-review rounds for OpenAI chat bodies. */ +#define _POSIX_C_SOURCE 200809L + +#include +#include +#include +#include +#include + +#include "http.h" +#include "review.h" + +#define REVIEW_PROMPT \ + "Review your previous answer carefully. Check it for factual errors, missing " \ + "constraints, contradictions, and unsafe assumptions. If it is correct, repeat " \ + "it verbatim. If it is wrong or incomplete, return the corrected final answer. " \ + "Return only the final answer text, with no commentary about the review." + +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; +} + +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; +} + +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 || *p == '}' || *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; } + return NULL; + } +} + +static int app_json_string(j_buf *b, const char *s) +{ + if (j_buf_append(b, "\"", 1) != 0) return -1; + for (const unsigned char *p = (const unsigned char *)s; *p; p++) { + char tmp[8]; + size_t n = 1; + switch (*p) { + case '"': tmp[0] = '\\'; tmp[1] = '"'; n = 2; break; + case '\\': tmp[0] = '\\'; tmp[1] = '\\'; n = 2; break; + case '\n': tmp[0] = '\\'; tmp[1] = 'n'; n = 2; break; + case '\r': tmp[0] = '\\'; tmp[1] = 'r'; n = 2; break; + case '\t': tmp[0] = '\\'; tmp[1] = 't'; n = 2; break; + default: + if (*p < 0x20) { + snprintf(tmp, sizeof tmp, "\\u%04x", (unsigned)*p); + n = strlen(tmp); + } else { + tmp[0] = (char)*p; + } + break; + } + if (j_buf_append(b, tmp, n) != 0) return -1; + } + return j_buf_append(b, "\"", 1); +} + +static int hexval(int c) +{ + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + return -1; +} + +static int append_utf8(char *out, size_t cap, size_t *o, unsigned cp) +{ + if (cp < 0x80) { + if (*o + 1 >= cap) return -1; + out[(*o)++] = (char)cp; + } else if (cp < 0x800) { + if (*o + 2 >= cap) return -1; + out[(*o)++] = (char)(0xC0 | (cp >> 6)); + out[(*o)++] = (char)(0x80 | (cp & 0x3F)); + } else if (cp < 0x10000) { + if (*o + 3 >= cap) return -1; + out[(*o)++] = (char)(0xE0 | (cp >> 12)); + out[(*o)++] = (char)(0x80 | ((cp >> 6) & 0x3F)); + out[(*o)++] = (char)(0x80 | (cp & 0x3F)); + } else { + if (cp > 0x10FFFF || *o + 4 >= cap) return -1; + out[(*o)++] = (char)(0xF0 | (cp >> 18)); + out[(*o)++] = (char)(0x80 | ((cp >> 12) & 0x3F)); + out[(*o)++] = (char)(0x80 | ((cp >> 6) & 0x3F)); + out[(*o)++] = (char)(0x80 | (cp & 0x3F)); + } + return 0; +} + +static int json_unescape(const char *s, size_t len, char *out, size_t cap) +{ + size_t o = 0; + for (size_t i = 0; i < len; i++) { + char c = s[i]; + if (c != '\\') { + if (o + 1 >= cap) return -1; + out[o++] = c; + continue; + } + if (++i >= len) return -1; + switch (s[i]) { + case 'n': c = '\n'; break; + case 'r': c = '\r'; break; + case 't': c = '\t'; break; + case 'b': c = '\b'; break; + case 'f': c = '\f'; break; + case '"': c = '"'; break; + case '\\': c = '\\'; break; + case '/': c = '/'; break; + case 'u': { + unsigned cp = 0; + if (i + 4 >= len) return -1; + for (int k = 1; k <= 4; k++) { + int h = hexval((unsigned char)s[i + (size_t)k]); + if (h < 0) return -1; + cp = cp * 16u + (unsigned)h; + } + i += 4; + if (cp >= 0xD800 && cp <= 0xDBFF && i + 6 < len && + s[i + 1] == '\\' && s[i + 2] == 'u') { + unsigned lo = 0; + for (int k = 3; k <= 6; k++) { + int h = hexval((unsigned char)s[i + (size_t)k]); + if (h < 0) return -1; + lo = lo * 16u + (unsigned)h; + } + if (lo >= 0xDC00 && lo <= 0xDFFF) { + cp = 0x10000u + ((cp - 0xD800u) << 10) + (lo - 0xDC00u); + i += 6; + } + } + if (append_utf8(out, cap, &o, cp) != 0) return -1; + continue; + } + default: + if (o + 1 >= cap) return -1; + out[o++] = s[i]; + continue; + } + if (o + 1 >= cap) return -1; + out[o++] = c; + } + out[o] = '\0'; + return (int)o; +} + +int j_review_nonstream(const char *body, char **out, size_t *outlen) +{ + *out = NULL; + *outlen = 0; + if (!body) return -1; + const char *end = body + strlen(body); + const char *v = find_top_value(body, end, "stream"); + if (v) { + v = skip_ws(v, end); + if (v + 4 <= end && !memcmp(v, "true", 4)) { + j_buf b; + j_buf_init(&b); + if (j_buf_append(&b, body, (size_t)(v - body)) != 0 || + j_buf_append(&b, "false", 5) != 0 || + j_buf_append(&b, v + 4, strlen(v + 4)) != 0) { + j_buf_free(&b); + return -1; + } + *out = b.data; + *outlen = b.len; + return 0; + } + } + size_t n = strlen(body); + char *copy = malloc(n + 1); + if (!copy) return -1; + memcpy(copy, body, n + 1); + *out = copy; + *outlen = n; + return 0; +} + +int j_review_body(const char *body, const char *answer, char **out, size_t *outlen) +{ + *out = NULL; + *outlen = 0; + if (!body || !answer) 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 *arr_end = skip_value(arr, end); + if (!arr_end) return -1; + const char *close = arr_end - 1; /* the closing ']' */ + if (close < arr || *close != ']') return -1; + const char *inner = skip_ws(arr + 1, close); + int empty = (inner >= close); + + j_buf b; + j_buf_init(&b); + const char *ins = empty ? "{\"role\":\"assistant\",\"content\":" + : ",{\"role\":\"assistant\",\"content\":"; + const char *urole = "},{\"role\":\"user\",\"content\":"; + if (j_buf_append(&b, body, (size_t)(close - body)) != 0 || + j_buf_append(&b, ins, strlen(ins)) != 0 || + app_json_string(&b, answer) != 0 || + j_buf_append(&b, urole, strlen(urole)) != 0 || + app_json_string(&b, REVIEW_PROMPT) != 0 || + j_buf_append(&b, "}", 1) != 0 || + j_buf_append(&b, close, strlen(close)) != 0) { + j_buf_free(&b); + return -1; + } + *out = b.data; + *outlen = b.len; + return 0; +} + +static const char *first_choice(const char *json, const char *end, + const char **choice_end, const char **message, + const char **message_end) +{ + const char *choices = find_top_value(json, end, "choices"); + if (!choices) return NULL; + choices = skip_ws(choices, end); + if (choices >= end || *choices != '[') return NULL; + const char *choice = skip_ws(choices + 1, end); + if (choice >= end || *choice != '{') return NULL; + const char *cend = skip_value(choice, end); + if (!cend) return NULL; + const char *msg = find_top_value(choice, cend, "message"); + if (!msg) return NULL; + msg = skip_ws(msg, cend); + if (msg >= cend || *msg != '{') return NULL; + const char *mend = skip_value(msg, cend); + if (!mend) return NULL; + *choice_end = cend; + *message = msg; + *message_end = mend; + return choice; +} + +int j_review_extract(const char *json, char **answer, int *tool_calls) +{ + *answer = NULL; + *tool_calls = 0; + if (!json) return -1; + const char *end = json + strlen(json); + const char *cend = NULL, *msg = NULL, *mend = NULL; + (void)first_choice(json, end, &cend, &msg, &mend); + if (!msg || !mend) return -1; + if (find_top_value(msg, mend, "tool_calls")) *tool_calls = 1; + const char *content = find_top_value(msg, mend, "content"); + if (!content) return -1; + content = skip_ws(content, mend); + if (content >= mend || *content != '"') return -1; + const char *s = content + 1; + const char *cend_str = skip_string(content, mend); + if (!cend_str) return -1; + size_t slen = (size_t)((cend_str - 1) - s); + char *buf = malloc(slen + 1); + if (!buf) return -1; + int got = json_unescape(s, slen, buf, slen + 1); + if (got <= 0) { + free(buf); + return -1; + } + *answer = buf; + return 0; +} + +static void finish_reason(const char *choice, const char *cend, char *out, size_t cap) +{ + snprintf(out, cap, "stop"); + const char *v = find_top_value(choice, cend, "finish_reason"); + if (!v) return; + v = skip_ws(v, cend); + if (v >= cend || *v != '"') return; + const char *e = skip_string(v, cend); + if (!e) return; + size_t len = (size_t)((e - 1) - (v + 1)); + if (len == 0 || len >= cap) return; + if (json_unescape(v + 1, len, out, cap) < 0) + snprintf(out, cap, "stop"); +} + +int j_review_sse(const char *json, const char *model, const char *meta, + char **out, size_t *outlen) +{ + *out = NULL; + *outlen = 0; + if (!json) return -1; + const char *end = json + strlen(json); + const char *cend = NULL, *msg = NULL, *mend = NULL; + const char *choice = first_choice(json, end, &cend, &msg, &mend); + if (!choice || !msg || !mend) return -1; + + char finish[48]; + finish_reason(choice, cend, finish, sizeof finish); + char id[64]; + long now = (long)time(NULL); + snprintf(id, sizeof id, "chatcmpl-review-%ld", now); + + j_buf b; + j_buf_init(&b); + char head[512]; + int n = snprintf(head, sizeof head, + "data: {\"id\":\"%s\",\"object\":\"chat.completion.chunk\",\"created\":%ld," + "\"model\":", id, now); + if (n < 0 || (size_t)n >= sizeof head || + j_buf_append(&b, head, (size_t)n) != 0 || + app_json_string(&b, model && model[0] ? model : "junction") != 0 || + j_buf_append(&b, ",\"choices\":[{\"index\":0,\"delta\":", + strlen(",\"choices\":[{\"index\":0,\"delta\":")) != 0 || + j_buf_append(&b, msg, (size_t)(mend - msg)) != 0 || + j_buf_append(&b, ",\"finish_reason\":null}]}\n\n", + strlen(",\"finish_reason\":null}]}\n\n")) != 0) { + j_buf_free(&b); + return -1; + } + + n = snprintf(head, sizeof head, + "data: {\"id\":\"%s\",\"object\":\"chat.completion.chunk\",\"created\":%ld," + "\"model\":", id, now); + if (n < 0 || (size_t)n >= sizeof head || + j_buf_append(&b, head, (size_t)n) != 0 || + app_json_string(&b, model && model[0] ? model : "junction") != 0 || + j_buf_append(&b, ",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":", + strlen(",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":")) != 0 || + app_json_string(&b, finish) != 0 || + j_buf_append(&b, "}]", strlen("}]")) != 0) { + j_buf_free(&b); + return -1; + } + if (meta && *meta) { + if (j_buf_append(&b, ",\"junction\":", strlen(",\"junction\":")) != 0 || + j_buf_append(&b, meta, strlen(meta)) != 0) { + j_buf_free(&b); + return -1; + } + } + if (j_buf_append(&b, "}\n\ndata: [DONE]\n\n", + strlen("}\n\ndata: [DONE]\n\n")) != 0) { + j_buf_free(&b); + return -1; + } + *out = b.data; + *outlen = b.len; + return 0; +} diff --git a/src/review.h b/src/review.h new file mode 100644 index 0000000..35ec1cf --- /dev/null +++ b/src/review.h @@ -0,0 +1,32 @@ +/* junction/review.h — hidden self-review rounds for an OpenAI chat request. + * + * The worker answers first; `review N` sends the original conversation plus that + * answer and a fixed review instruction back to the same model N times. Only the + * last answer is shown to the client. The helpers here are pure JSON work; the + * HTTP part stays in junction.c and uses the normal endpoint/auth/rewrite path. + */ +#ifndef JUNCTION_REVIEW_H +#define JUNCTION_REVIEW_H + +#include + +/* Copy a request body with `stream` forced to false. Needed because the review + * path buffers the answer and a chunked SSE body would not be parseable. */ +int j_review_nonstream(const char *body, char **out, size_t *outlen); + +/* Append one assistant answer and the review instruction to the messages array of + * an already non-streaming request body. */ +int j_review_body(const char *body, const char *answer, char **out, size_t *outlen); + +/* Extract choices[0].message.content from an OpenAI chat completion. Returns 0 and + * a malloc'ed answer; -1 when there is no text. *tool_calls is set when the message + * carries tool_calls, because such an answer must pass through unreviewed. */ +int j_review_extract(const char *json, char **answer, int *tool_calls); + +/* Turn a completed OpenAI JSON response into the SSE frames the client expects: + * one chunk carrying the raw message (text, reasoning, tool_calls), a stop chunk, + * and [DONE]. `model` is what the client asked for. */ +int j_review_sse(const char *json, const char *model, const char *meta, + char **out, size_t *outlen); + +#endif /* JUNCTION_REVIEW_H */ diff --git a/tests/judge.sh b/tests/judge.sh index b364023..7d5544f 100644 --- a/tests/judge.sh +++ b/tests/judge.sh @@ -72,6 +72,12 @@ judge_ask() { # judge_ask JMODEL=$(tr -d '\r' < "$TMP/judge_h.txt" | sed -n 's/^X-Stub-Model: //p') JAV=$(tr -d '\r' < "$TMP/judge_h.txt" | sed -n 's/^X-Stub-Anthropic-Version: //p') JAVC=$(tr -d '\r' < "$TMP/judge_h.txt" | sed -n 's/^X-Stub-Anthropic-Versions: //p') + JJUDGE=$(tr -d '\r' < "$TMP/judge_h.txt" | sed -n 's/^X-Junction-Judge: //p') + JJSTEP=$(tr -d '\r' < "$TMP/judge_h.txt" | sed -n 's/^X-Junction-Judge-Step: //p') + JJEVERY=$(tr -d '\r' < "$TMP/judge_h.txt" | sed -n 's/^X-Junction-Judge-Every: //p') + JJMODEL=$(tr -d '\r' < "$TMP/judge_h.txt" | sed -n 's/^X-Junction-Judge-Model: //p') + JJSERVED=$(tr -d '\r' < "$TMP/judge_h.txt" | sed -n 's/^X-Junction-Judge-Served: //p') + JENDPOINT=$(tr -d '\r' < "$TMP/judge_h.txt" | sed -n 's/^X-Junction-Endpoint: //p') } # Unterhaltung A: 3., 6., 9. … Anfrage geht an den Judge. @@ -85,6 +91,18 @@ for i in 1 2 3 4 5 6; do || 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'" + [ "$JJUDGE" = "judge" ] && ok "turn $i names the judge in the headers" \ + || bad "turn $i: X-Junction-Judge='$JJUDGE'" + [ "$JJSTEP" = "0" ] && ok "turn $i names the judge step" \ + || bad "turn $i: judge step '$JJSTEP'" + [ "$JJEVERY" = "3" ] && ok "turn $i names the judge interval" \ + || bad "turn $i: judge every '$JJEVERY'" + [ "$JJMODEL" = "judge-model" ] && ok "turn $i names the judge model" \ + || bad "turn $i: judge model header '$JJMODEL'" + [ "$JJSERVED" = "1" ] && ok "turn $i says the judge served" \ + || bad "turn $i: judge served '$JJSERVED'" + [ "$JENDPOINT" = "judge" ] && ok "turn $i names the serving endpoint" \ + || bad "turn $i: endpoint '$JENDPOINT'" if [ "$i" = "3" ]; then [ "$JAV" = "2025-01-01" ] && ok "the client's anthropic-version wins" \ || bad "the judge saw anthropic-version '$JAV'" @@ -96,6 +114,10 @@ for i in 1 2 3 4 5 6; do || 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" + [ -z "$JJUDGE" ] && ok "turn $i has no judge header" \ + || bad "turn $i: worker turn carries judge '$JJUDGE'" + [ "$JENDPOINT" = "worker" ] && ok "turn $i names the worker endpoint" \ + || bad "turn $i: endpoint '$JENDPOINT'" fi done @@ -109,6 +131,8 @@ judge_ask "$JP" "qwen-judged" "A different system prompt for B." "conversation B judge_ask "$JP" "qwen-judged" "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" +[ "$JJUDGE" = "judge" ] && [ "$JJSERVED" = "1" ] && ok "conversation B's judge is visible in the headers" \ + || bad "conversation B's judge headers are wrong: '$JJUDGE'/'$JJSERVED'" contains "$(grep '\[junction\] judge ' "$TMP/judge.log" | head -1)" "cache=1h" \ "the judge log names the cache TTL" @@ -139,6 +163,12 @@ judge_ask "$JP2" "qwen-judged" "$SYS" "fallback turn" || 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" +[ "$JJUDGE" = "badjudge" ] && ok "the fallback header names the attempted judge" \ + || bad "the fallback judge header is '$JJUDGE'" +[ "$JJSERVED" = "0" ] && ok "the fallback header says the judge did not serve" \ + || bad "the fallback judge served header is '$JJSERVED'" +[ "$JENDPOINT" = "worker" ] && ok "the fallback header names the worker" \ + || bad "the fallback endpoint header is '$JENDPOINT'" 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" \ @@ -166,6 +196,12 @@ judge_ask "$JP3" "vm-pool" "$SYS" "pool judge turn" || bad "the pool judge saw model '$JMODEL'" [ "$JCACHE" = "0" ] && ok "cache off sends no marker to the pool judge" \ || bad "the pool judge received cache_control" +[ "$JJUDGE" = "judgepool" ] && ok "the header names the judge pool" \ + || bad "the pool judge header is '$JJUDGE'" +[ "$JJMODEL" = "pool" ] && ok "the header says the judge model is the pool" \ + || bad "the pool judge model header is '$JJMODEL'" +[ "$JJSERVED" = "1" ] && ok "the pool judge header says it served" \ + || bad "the pool judge served header is '$JJSERVED'" contains "$(cat "$TMP/judge_pool.log")" "target=judgepool slots=2" \ "the judge log names the pool and its slot count" contains "$(cat "$TMP/judge_pool.log")" "failed endpoint=badjudge" \ @@ -194,19 +230,27 @@ for i in 1 2 3 4 5 6 7 8 9 10; do want=${CHAIN[$((i-1))]} case "$want" in W) [ "$JNAME" = "WORKER" ] && ok "chain call $i stays on the worker" \ - || bad "chain call $i should be the worker, got '$JNAME'" ;; + || bad "chain call $i should be the worker, got '$JNAME'" + [ -z "$JJUDGE" ] && ok "chain call $i has no judge header" \ + || bad "chain call $i: worker carries judge '$JJUDGE'" ;; A) [ "$JNAME" = "JUDGE" ] && ok "chain call $i goes to the deepseek judge" \ || bad "chain call $i should be the deepseek judge, got '$JNAME'" [ "$JMODEL" = "judge-a-model" ] && ok "chain call $i uses judge-a model" \ || bad "chain call $i model '$JMODEL'" [ "$JCACHE" = "0" ] && ok "chain call $i sends no marker to deepseek" \ - || bad "chain call $i carried cache_control for deepseek" ;; + || bad "chain call $i carried cache_control for deepseek" + [ "$JJUDGE" = "judgea" ] && [ "$JJSTEP" = "0" ] && [ "$JJEVERY" = "3" ] \ + && [ "$JJSERVED" = "1" ] && ok "chain call $i names the deepseek judge" \ + || bad "chain call $i judge headers are wrong" ;; B) [ "$JNAME" = "JUDGE2" ] && ok "chain call $i goes to the claude judge" \ || bad "chain call $i should be the claude judge, got '$JNAME'" [ "$JMODEL" = "judge-b-model" ] && ok "chain call $i uses judge-b model" \ || bad "chain call $i model '$JMODEL'" [ "$JCACHE" = "1" ] && ok "chain call $i carries the claude cache marker" \ - || bad "chain call $i had no cache_control for claude" ;; + || bad "chain call $i had no cache_control for claude" + [ "$JJUDGE" = "judge2" ] && [ "$JJSTEP" = "1" ] && [ "$JJEVERY" = "5" ] \ + && [ "$JJSERVED" = "1" ] && ok "chain call $i names the claude judge" \ + || bad "chain call $i judge headers are wrong" ;; esac done contains "$(grep 'step=0 every=3 target=judgea' "$TMP/judge_chain.log" | head -1)" \ diff --git a/tests/review.sh b/tests/review.sh new file mode 100644 index 0000000..4f8b1a9 --- /dev/null +++ b/tests/review.sh @@ -0,0 +1,125 @@ +#!/bin/bash +# Wird von tests/run.sh eingebunden: review N lässt dasselbe Modell die eigene +# Antwort N-mal prüfen. Der Client sieht nur die letzte Fassung; Tool-Calls gehen +# ungeprüft durch. Die Stub-Antworten wechseln pro Aufruf, damit die Runden +# nachweisbar sind. + +echo +echo "== 42. Self-Review: N versteckte Runden, nur die letzte Antwort ==" + +RW=$((PORT+280)) +RJ=$((PORT+281)) +RT=$((PORT+282)) +RJT=$((PORT+283)) + +STUB_STATE="$TMP/review.state" STUB_ANSWERS="first answer|second answer|third answer" \ + tests/stub $RW "REVIEWER" > "$TMP/review_stub.log" 2>&1 & +PIDS+=($!) +STUB_STATE="$TMP/review_tools.state" STUB_ANSWERS="tool answer" STUB_TOOLS=1 \ + tests/stub $RT "TOOLER" > "$TMP/review_tools_stub.log" 2>&1 & +PIDS+=($!) +wait_port $RW 10 || bad "the review stub did not come up" +wait_port $RT 10 || bad "the tool-review stub did not come up" + +cat > "$TMP/review.conf" < "$TMP/review.log" 2>&1 & +PIDS+=($!) +wait_port "$RJ" 10 || bad "the review instance did not come up" + +REVIEW_BODY='{"model":"vm-reviewed","messages":[{"role":"system","content":"Be terse."},{"role":"user","content":"Say OK."}],"max_tokens":8}' + +# Non-streaming: drei Aufrufe (Original + 2 Reviews), nur "third answer" kommt an. +R=$(curl -s -D "$TMP/review_h.txt" -m 30 -X POST -H 'Content-Type: application/json' \ + -d "$REVIEW_BODY" "http://127.0.0.1:$RJ/v1/chat/completions") +contains "$R" "third answer" "the client gets the last reviewed answer" +case "$R" in *"first answer"*|*"second answer"*) + bad "an intermediate answer leaked to the client" ;; + *) ok "no intermediate answer leaked to the client" ;; +esac +CALLS=$(tr -d '\n' < "$TMP/review.state") +[ "$CALLS" = "3" ] && ok "review 2 means three model calls" \ + || bad "expected 3 model calls, got '$CALLS'" +contains "$(cat "$TMP/review.log")" "round=1 endpoint=worker ok=1" \ + "the first review round is logged" +contains "$(cat "$TMP/review.log")" "round=2 endpoint=worker ok=1" \ + "the second review round is logged" +contains "$(cat "$TMP/review-dump.txt")" "Review your previous answer" \ + "the review prompt reached the model" +contains "$(cat "$TMP/review-dump.txt")" "first answer" \ + "the first answer was fed back into the first review" +contains "$(cat "$TMP/review-dump.txt")" "second answer" \ + "the second answer was fed back into the second review" +RH=$(tr -d '\r' < "$TMP/review_h.txt") +contains "$RH" "X-Junction-Review: 2" "the response header names the review count" +contains "$RH" "X-Junction-Review-Rounds: 2" "the response header names the completed rounds" +contains "$RH" "X-Junction-Review-Model: worker-model" "the response header names the review model" +contains "$RH" "X-Junction-Endpoint: worker" "the response header names the endpoint" + +# Streaming: dieselben Runden, aber der Client bekommt eine finale SSE-Antwort. +rm -f "$TMP/review.state" +SSE_BODY='{"model":"vm-reviewed","stream":true,"messages":[{"role":"system","content":"Be terse."},{"role":"user","content":"Say OK."}],"max_tokens":8}' +SSE=$(curl -s -N -D "$TMP/review_sh.txt" -m 30 -X POST -H 'Content-Type: application/json' \ + -d "$SSE_BODY" "http://127.0.0.1:$RJ/v1/chat/completions") +contains "$(tr -d '\r' < "$TMP/review_sh.txt")" "X-Junction-Review: 2" \ + "the stream head names the review count" +contains "$SSE" '"junction":{"review_rounds":2' \ + "the final stream chunk carries the review outcome" +contains "$SSE" 'data: [DONE]' "the review stream ends with [DONE]" +contains "$SSE" "third answer" "the stream carries the last reviewed answer" +case "$SSE" in *"first answer"*|*"second answer"*) + bad "an intermediate answer leaked into the stream" ;; + *) ok "no intermediate answer leaked into the stream" ;; +esac +CALLS=$(tr -d '\n' < "$TMP/review.state") +[ "$CALLS" = "3" ] && ok "the streaming path also runs three calls" \ + || bad "the streaming path ran '$CALLS' calls instead of 3" + +# Tool-Call-Antworten werden nicht als Text geprüft, sondern durchgereicht. +cat > "$TMP/review_tools.conf" < "$TMP/review_tools.log" 2>&1 & +PIDS+=($!) +wait_port "$RJT" 10 || bad "the tool-review instance did not come up" +RTC=$(curl -s -D "$TMP/review_tools_h.txt" -m 20 -X POST -H 'Content-Type: application/json' \ + -d '{"model":"vm-tools","messages":[{"role":"user","content":"do it"}],"max_tokens":8,"tools":[{"type":"function","function":{"name":"doit","parameters":{"type":"object"}}}]}' \ + "http://127.0.0.1:$RJT/v1/chat/completions") +contains "$RTC" '"tool_calls"' "a tool-call answer passes through unreviewed" +contains "$(cat "$TMP/review_tools.log")" "skipped=tool_calls" \ + "the skipped review is logged" +RTH=$(tr -d '\r' < "$TMP/review_tools_h.txt") +contains "$RTH" "X-Junction-Review-Rounds: 0" "the tool turn reports zero review rounds" +contains "$RTH" "X-Junction-Review-Skipped: tool_calls" \ + "the tool turn names why the review was skipped" +TCALLS=$(tr -d '\n' < "$TMP/review_tools.state") +[ "$TCALLS" = "1" ] && ok "no review call was made for the tool-call answer" \ + || bad "the tool-call answer caused '$TCALLS' model calls" + +# /v1/models und /status kennen das virtuelle Modell und die Rundenzahl. +M=$(curl -s -m 10 "http://127.0.0.1:$RJ/v1/models") +contains "$M" '"id":"vm-reviewed"' "the reviewed virtual model is listed" +ST=$(curl -s -m 10 "http://127.0.0.1:$RJ/status") +contains "$ST" '"review":2' "the status names the review count" + +# Konfigurationsfehler müssen laut sein. +printf 'endpoint e {\n base http://127.0.0.1:9995/v1\n}\nreq for "vm" review 5 pass e\n' \ + > "$TMP/review_bad_count.conf" +OUT=$(./junction --config "$TMP/review_bad_count.conf" 2>&1) +contains "$OUT" "bad arguments" "review 5 is rejected" + +printf 'endpoint e {\n base http://127.0.0.1:9995/v1\n}\nreq for "vm" review 2 block\n' \ + > "$TMP/review_block.conf" +OUT=$(./junction --config "$TMP/review_block.conf" 2>&1) +contains "$OUT" "review on a block rule" "review on a block rule is rejected" diff --git a/tests/run.sh b/tests/run.sh index e615930..2458042 100755 --- a/tests/run.sh +++ b/tests/run.sh @@ -71,7 +71,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 8405 8406 8407 8408 8409 8410 8411 8412 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 8410 8411 8412 8415 8416 8417 8418 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/^/ /' @@ -794,6 +794,10 @@ fi # shellcheck source=tests/judge.sh . "$(dirname "$0")/judge.sh" +# Self-Review: N versteckte Runden, nur die letzte Antwort geht an den Client. +# shellcheck source=tests/review.sh +. "$(dirname "$0")/review.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 08afd53..09c7120 100644 --- a/tests/stub.c +++ b/tests/stub.c @@ -136,6 +136,9 @@ int main(int argc, char **argv) } else if (!strcmp(argv[i], "--tls") && i + 2 < argc) { cert = argv[++i]; key = argv[++i]; } } + const char *answers_env = getenv("STUB_ANSWERS"); + const char *tools_env = getenv("STUB_TOOLS"); + char tlserr[256]; if (cert && j_tls_server_start(cert, key, tlserr, sizeof tlserr)) { fprintf(stderr, "stub tls: %s\n", tlserr); @@ -208,9 +211,41 @@ int main(int argc, char **argv) /* Nur Chat-Anfragen zählen: junction holt beim Start GET /v1/models, und diese * eine Anfrage darf das Fehlerkontingent des Tests nicht verbrauchen. */ int counts = !strncmp(req, "POST", 4) && strstr(req, "/chat/completions"); - if (fail_n > 0 && counts && request_serial() <= fail_n) forced = 503; + int serial = 0, have_serial = 0; + if (counts && (fail_n > 0 || (answers_env && *answers_env))) { + serial = request_serial(); + have_serial = 1; + } + if (fail_n > 0 && counts && have_serial && serial <= fail_n) forced = 503; else if (deny_auth[0] && strstr(authhdr, deny_auth)) forced = 429; + /* STUB_ANSWERS="first|second|third": the n-th chat request answers with + * the n-th entry (the last entry repeats). This is how the self-review + * test sees a different answer on every round. */ + char selected_answer[1024] = ""; + if (answers_env && *answers_env && counts && have_serial) { + const char *q = answers_env; + int idx = 1; + for (;;) { + const char *bar = strchr(q, '|'); + size_t len = bar ? (size_t)(bar - q) : strlen(q); + if (idx == serial) { + if (len >= sizeof selected_answer) len = sizeof selected_answer - 1; + memcpy(selected_answer, q, len); + selected_answer[len] = '\0'; + break; + } + if (!bar) { + if (len >= sizeof selected_answer) len = sizeof selected_answer - 1; + memcpy(selected_answer, q, len); + selected_answer[len] = '\0'; + break; + } + q = bar + 1; + idx++; + } + } + char *head_end = strstr(req, "\r\n\r\n"); size_t head_len = head_end ? (size_t)(head_end + 4 - req) : used; char cl[32]; @@ -261,6 +296,27 @@ int main(int argc, char **argv) /* 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; + int has_review = strstr(req + head_len, "Review your previous answer") != NULL; + int has_prev = 0; + if (answers_env && *answers_env && counts && have_serial && serial > 1) { + const char *q = answers_env; + int idx = 1; + for (;;) { + const char *bar = strchr(q, '|'); + size_t len = bar ? (size_t)(bar - q) : strlen(q); + if (idx == serial - 1) { + char prev[1024]; + if (len >= sizeof prev) len = sizeof prev - 1; + memcpy(prev, q, len); + prev[len] = '\0'; + has_prev = strstr(req + head_len, prev) != NULL; + break; + } + if (!bar) break; + q = bar + 1; + idx++; + } + } 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); @@ -346,11 +402,23 @@ int main(int argc, char **argv) "X-Stub-Accept: %s\r\n" "Connection: close\r\n\r\n%s", strlen(b), name, body_len, accept, b); } else { - char b[512]; - snprintf(b, sizeof b, - "{\"id\":\"stub\",\"model\":\"%s\",\"choices\":[{\"index\":0," - "\"message\":{\"role\":\"assistant\",\"content\":\"served by %s\"}}]}", - name, name); + char b[4096]; + if (tools_env && *tools_env) + snprintf(b, sizeof b, + "{\"id\":\"stub\",\"model\":\"%s\",\"choices\":[{\"index\":0," + "\"message\":{\"role\":\"assistant\",\"content\":null," + "\"tool_calls\":[{\"id\":\"call_1\",\"type\":\"function\"," + "\"function\":{\"name\":\"doit\",\"arguments\":\"{}\"}}]}," + "\"finish_reason\":\"tool_calls\"}]}", + name); + else { + char default_answer[256]; + snprintf(default_answer, sizeof default_answer, "served by %s", name); + snprintf(b, sizeof b, + "{\"id\":\"stub\",\"model\":\"%s\",\"choices\":[{\"index\":0," + "\"message\":{\"role\":\"assistant\",\"content\":\"%s\"}}]}", + name, selected_answer[0] ? selected_answer : default_answer); + } snprintf(body, sizeof body, "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n" "Content-Length: %zu\r\n" @@ -361,6 +429,7 @@ int main(int argc, char **argv) "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-Review: %d\r\nX-Stub-Prev: %d\r\n" "X-Stub-XApi-Key: %s\r\n" "X-Stub-Anthropic-Version: %s\r\n" "X-Stub-Anthropic-Versions: %d\r\n" @@ -368,6 +437,7 @@ int main(int argc, char **argv) strlen(b), name, body_len, custom, static_hdr, fwd, model, authhdr, reasoning, accept, effort, effort[0] ? 1 : 0, thinking, has_reasoning ? 1 : 0, has_cache_control ? 1 : 0, + has_review ? 1 : 0, has_prev ? 1 : 0, xapi, av, av_count, b); } if (j_conn_write(&client, body, strlen(body), ioerr, sizeof ioerr) < 0)