From aaa289ab01e62ef2022cc189a3e7d86a3fc61569 Mon Sep 17 00:00:00 2001 From: Hermes Date: Thu, 19 Nov 2026 11:37:04 +0000 Subject: [PATCH] review: anchor every round to the user's question, and let one request set the depth The review prompt was generic ("check for factual errors, missing constraints..."), and a long tool history pulled the reviewer toward whatever the last tool returned: a mikronix session answered with makronix tasks, and the rounds grew the wrong answer instead of correcting it. Each round now carries the last user message and the answer so far, says to keep the same question, scope and language, and says this is not a spelling or style check. A request may also set its own depth without editing the rule: X-Junction-Review-Rounds: N 0..12 X-Junction-Effort: off|low|medium|high|max 0/4/7/9/12 The explicit number wins over the name, invalid values fall back to the rule, and both headers are stripped before the upstream call. 0 disables the review for that request (one provider call, no review headers). The rule stays the default, so nothing changes for clients that send neither header. tests/review.sh: the prompt carries the question and the answer and says it is not a spelling check; depth 0, 3, effort medium and an out-of-range 99 are checked against the stub's call counts. tests/run.sh: 550 OK, PASS. Measured against a 4B on kontron: 0 rounds 7.4s, 2 rounds 34.9s, 4 rounds 62.3s, 7 rounds 104.3s -- all with the same correct answer, so the depth is a latency knob, not a quality fix for a model that already answers the question. --- README.md | 31 +++++++++++++--- config.example | 6 ++- src/junction.c | 35 ++++++++++++++++++ src/review.c | 97 ++++++++++++++++++++++++++++++++++++++++++++++--- tests/review.sh | 51 ++++++++++++++++++++++++++ 5 files changed, 208 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index cdbfd18..a260f7b 100644 --- a/README.md +++ b/README.md @@ -265,10 +265,29 @@ the same endpoint and hold the same slot, so a local box sees its own prompt cac still uses the normal failover. - **Cost:** `review 2` means three provider calls. They are visible in `/spend` and count against the vkey budget. +- **Anchor:** every review round gets the user's request and the answer so far + again, with "keep the same question, scope and language" and "this is not a + spelling or style check" in the instruction. A long tool history otherwise + pulls the reviewer toward whatever the last tool returned instead of the + question. - **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`). +**Per request.** The rule is the default, but one request can ask for a different +depth without editing the config: + +``` +curl -H 'X-Junction-Review-Rounds: 7' ... # 7 rounds, 0..12 +curl -H 'X-Junction-Effort: medium' ... # off=0, low/default=4, + # medium=7, high=9, max=12 +``` + +The explicit number wins over the effort name. Out-of-range or malformed values +fall back to the rule. `X-Junction-Review-Rounds: 0` turns the review off for +that request (one provider call, no review headers). Both headers last for one +request only and are never forwarded upstream. + ### Judge/review limits and headers — one place The clauses are safe defaults, but they have hard edges. This is the complete @@ -296,9 +315,10 @@ list; the code lives in `src/judge.c`, `src/review.c` and `review_serve` in **Review** -- `review N` accepts **0–4**; `review 5` is rejected at config load and by - `rules.set`. N rounds mean **N+1** provider calls (the worker answer plus N - reviews), all billed and counted in `/spend` and the vkey budget. +- `review N` in the config accepts **0–4**; `review 5` is rejected at config + load and by `rules.set`. A per-request header can raise the depth to **12** + (see "Per request" above). N rounds mean **N+1** provider calls (the worker + answer plus N reviews), all billed and counted in `/spend` and the vkey budget. - Review calls use the same endpoint and model as the worker and run sequentially. Each review request carries at least **4096** `max_tokens` (or `max_completion_tokens`), even when the client asked for less; the first worker @@ -307,8 +327,9 @@ list; the code lives in `src/judge.c`, `src/review.c` and `review_serve` in `stream:false` and without `stream_options`; the client still gets SSE frames built from the final answer if it asked for a stream. - The review prompt is appended to the same conversation after the worker or - previous answer. Only the final answer is written to the client; intermediate - answers and the prompt never leak. + previous answer. It carries the user's request and the answer so far and says + to keep the same question, scope and language; only the final answer is + written to the client, intermediate answers and the prompt never leak. - Review only applies to `POST /v1/chat/completions` on OpenAI-compatible endpoints. `kind anthropic`/`kind opencode`, other paths and non-chat requests are forwarded unreviewed with `X-Junction-Review-Skipped: protocol`. diff --git a/config.example b/config.example index 979df26..e8bf60d 100644 --- a/config.example +++ b/config.example @@ -238,8 +238,10 @@ req path "/v1/models" check none pass peer1, peer2, opencode-go # through unreviewed. "review 2" means three provider calls. # # Limits and failure behavior (full table in README, "Judge/review limits and -# headers"): at most 4 judge steps and 4 review rounds (review 5 is a config -# error). Review calls carry at least 4096 max_tokens; the first worker call +# headers"): at most 4 judge steps and 4 review rounds in the config (review 5 is +# a config error). A request may raise the review depth to 12 for itself with +# X-Junction-Review-Rounds: N, or X-Junction-Effort: off|low|medium|high|max +# (0/4/7/9/12). Review calls carry at least 4096 max_tokens; the first worker call # keeps the client's budget. n>1, content arrays, non-empty tool_calls and a # spent vkey budget skip the remaining rounds and deliver the original or last # good answer; X-Junction-Review-Skipped names the reason. Judge counters are diff --git a/src/junction.c b/src/junction.c index 7ebe738..31cb5ee 100644 --- a/src/junction.c +++ b/src/junction.c @@ -4021,6 +4021,40 @@ static void hdr_note(const char *event, const char *name) name && name[0] ? name : "?", J_MAX_HDRS, seen); } +/* One request may ask for a deeper (or no) self-review than its rule: + * X-Junction-Review-Rounds: N 0..12 + * X-Junction-Effort: off|low|medium|high|max -> 0|4|7|9|12 + * The explicit number wins over the name; neither persists beyond this request. */ +static int review_depth(const j_req *rq, int rule_default) +{ + char v[64]; + + if (j_hdrs_find(&rq->hdrs, "X-Junction-Review-Rounds", v, sizeof v) == 0) { + char *end = NULL; + long n = strtol(v, &end, 10); + if (end != v) { + while (*end == ' ' || *end == '\t') end++; + if (*end == '\0' && n >= 0 && n <= 12) { + jlog("review_override", "rounds=%ld source=header", n); + return (int)n; + } + } + } + if (j_hdrs_find(&rq->hdrs, "X-Junction-Effort", v, sizeof v) == 0) { + int n = -1; + if (!strcasecmp(v, "off") || !strcasecmp(v, "none")) n = 0; + else if (!strcasecmp(v, "low") || !strcasecmp(v, "default")) n = 4; + else if (!strcasecmp(v, "medium")) n = 7; + else if (!strcasecmp(v, "high")) n = 9; + else if (!strcasecmp(v, "max")) n = 12; + if (n >= 0) { + jlog("review_override", "rounds=%d source=effort", n); + return n; + } + } + return rule_default; +} + static void handle_client_inner(j_conn *client) { j_buf buf; @@ -4270,6 +4304,7 @@ static void handle_client_inner(j_conn *client) send_simple(client, 403, "Forbidden", body); goto done; } + rule->review_count = review_depth(&rq, rule->review_count); t_review_count = rule->review_count; /* If no target of this rule can hold ctx + need, try the configured fallback diff --git a/src/review.c b/src/review.c index a3e3d7a..3795f7a 100644 --- a/src/review.c +++ b/src/review.c @@ -10,10 +10,15 @@ #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. " \ +#define REVIEW_PROMPT_HEAD "The user asked:\n\n" +#define REVIEW_PROMPT_MID "\n\nYour answer so far:\n\n" +#define REVIEW_PROMPT_TAIL \ + "Review your previous answer against the user's request. Check it for " \ + "factual errors, missing constraints, contradictions, and unsafe " \ + "assumptions. Keep the same question, scope and language: do not drift to " \ + "another project or topic, and do not add facts the user did not ask for. " \ + "This is not a spelling or style check. If the answer 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) @@ -392,6 +397,61 @@ static int raise_max_tokens(const char *body, char **out, size_t *outlen) return 0; } +/* The last user message, so every review round can put the actual question next + * to the answer it is judging. A reviewer that only sees a growing tool history + * drifts to whatever the last tool returned; the question is the anchor. */ +static int last_user_text(const char *body, char **out, size_t *outlen) +{ + *out = NULL; + *outlen = 0; + 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 = skip_ws(arr + 1, end); + const char *last = NULL, *last_end = NULL; + while (p < end && *p != ']') { + const char *v_end, *role, *content; + if (*p != '{') return -1; + v_end = skip_value(p, end); + if (!v_end) return -1; + role = find_top_value(p, v_end, "role"); + content = find_top_value(p, v_end, "content"); + if (role != NULL && content != NULL) { + role = skip_ws(role, v_end); + content = skip_ws(content, v_end); + if (role < v_end && *role == '"' && content < v_end && + *content == '"') { + const char *re = skip_string(role, v_end); + const char *ce = skip_string(content, v_end); + if (re != NULL && ce != NULL && (re - role) == 6 && + memcmp(role + 1, "user", 4) == 0) { + last = content; + last_end = ce; + } + } + } + p = skip_ws(v_end, end); + if (p < end && *p == ',') { + p = skip_ws(p + 1, end); + continue; + } + break; + } + if (last == NULL) return -1; + size_t slen = (size_t)((last_end - 1) - (last + 1)); + char *buf = malloc(slen + 1); + if (buf == NULL) return -1; + if (json_unescape(last + 1, slen, buf, slen + 1) < 0) { + free(buf); + return -1; + } + *out = buf; + *outlen = slen; + return 0; +} + int j_review_body(const char *body, const char *answer, char **out, size_t *outlen) { *out = NULL; @@ -413,6 +473,31 @@ int j_review_body(const char *body, const char *answer, char **out, size_t *outl const char *inner = skip_ws(arr + 1, close); int empty = (inner >= close); + j_buf prompt; + j_buf_init(&prompt); + char *question = NULL; + size_t qlen = 0; + int have_q = last_user_text(body, &question, &qlen) == 0; + int prc = 0; + + if (have_q) + prc = j_buf_append(&prompt, REVIEW_PROMPT_HEAD, + strlen(REVIEW_PROMPT_HEAD)) != 0 || + j_buf_append(&prompt, question, qlen) != 0 || + j_buf_append(&prompt, REVIEW_PROMPT_MID, + strlen(REVIEW_PROMPT_MID)) != 0 || + j_buf_append(&prompt, answer, strlen(answer)) != 0 || + j_buf_append(&prompt, "\n\n", 2) != 0; + if (!prc) + prc = j_buf_append(&prompt, REVIEW_PROMPT_TAIL, + strlen(REVIEW_PROMPT_TAIL)) != 0; + free(question); + if (prc != 0) { + j_buf_free(&prompt); + free(raised); + return -1; + } + j_buf b; j_buf_init(&b); const char *ins = empty ? "{\"role\":\"assistant\",\"content\":" @@ -422,13 +507,15 @@ int j_review_body(const char *body, const char *answer, char **out, size_t *outl 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 || + app_json_string(&b, prompt.data) != 0 || j_buf_append(&b, "}", 1) != 0 || j_buf_append(&b, close, strlen(close)) != 0) { j_buf_free(&b); + j_buf_free(&prompt); free(raised); return -1; } + j_buf_free(&prompt); *out = b.data; *outlen = b.len; free(raised); diff --git a/tests/review.sh b/tests/review.sh index e08c66e..e56f7ba 100644 --- a/tests/review.sh +++ b/tests/review.sh @@ -90,6 +90,14 @@ 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")" "The user asked:" \ + "each review round carries the user's question" +contains "$(cat "$TMP/review-dump.txt")" "Say OK." \ + "the review prompt carries the original user text" +contains "$(cat "$TMP/review-dump.txt")" "Your answer so far:" \ + "each review round names the answer it is reviewing" +contains "$(cat "$TMP/review-dump.txt")" "not a spelling or style check" \ + "the review prompt says it is not a spelling check" 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" \ @@ -190,6 +198,49 @@ then ok "streamed tool calls keep their index and their own names" else bad "streamed tool calls were merged or lost their index" fi +# Per-request review depth: the rule stays the default, the header overrides it +# for one request. 0 turns the review off, N raises it (0..12), effort names map +# to 4/7/9/12. +: > "$TMP/review.state" +D0=$(curl -s -D "$TMP/depth0.h" -m 30 -X POST -H 'Content-Type: application/json' \ + -H 'X-Junction-Review-Rounds: 0' -d "$REVIEW_BODY" \ + "http://127.0.0.1:$RJ/v1/chat/completions") +[ "$(tr -d '\n' < "$TMP/review.state")" = "1" ] \ + && ok "review rounds 0: only the worker call" \ + || bad "review rounds 0 made '$(tr -d '\n' < "$TMP/review.state")' calls" +case "$(tr -d '\r' < "$TMP/depth0.h")" in + *"X-Junction-Review"*) bad "review rounds 0 still announced a review" ;; + *) ok "review rounds 0 sends no review header" ;; +esac + +: > "$TMP/review.state" +D3=$(curl -s -D "$TMP/depth3.h" -m 30 -X POST -H 'Content-Type: application/json' \ + -H 'X-Junction-Review-Rounds: 3' -d "$REVIEW_BODY" \ + "http://127.0.0.1:$RJ/v1/chat/completions") +[ "$(tr -d '\n' < "$TMP/review.state")" = "4" ] \ + && ok "review rounds 3: worker plus three reviews" \ + || bad "review rounds 3 made '$(tr -d '\n' < "$TMP/review.state")' calls instead of 4" +contains "$(tr -d '\r' < "$TMP/depth3.h")" "X-Junction-Review: 3" \ + "review rounds 3 is named in the response" + +: > "$TMP/review.state" +DE=$(curl -s -D "$TMP/effort.h" -m 60 -X POST -H 'Content-Type: application/json' \ + -H 'X-Junction-Effort: medium' -d "$REVIEW_BODY" \ + "http://127.0.0.1:$RJ/v1/chat/completions") +[ "$(tr -d '\n' < "$TMP/review.state")" = "8" ] \ + && ok "effort medium: worker plus seven reviews" \ + || bad "effort medium made '$(tr -d '\n' < "$TMP/review.state")' calls instead of 8" +contains "$(tr -d '\r' < "$TMP/effort.h")" "X-Junction-Review: 7" \ + "effort medium reports seven rounds" + +: > "$TMP/review.state" +D99=$(curl -s -D "$TMP/depth99.h" -m 30 -X POST -H 'Content-Type: application/json' \ + -H 'X-Junction-Review-Rounds: 99' -d "$REVIEW_BODY" \ + "http://127.0.0.1:$RJ/v1/chat/completions") +[ "$(tr -d '\n' < "$TMP/review.state")" = "3" ] \ + && ok "an out-of-range depth falls back to the rule" \ + || bad "an out-of-range depth made '$(tr -d '\n' < "$TMP/review.state")' calls instead of 3" + # /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"