diff --git a/README.md b/README.md index da4e055..4e14b5f 100644 --- a/README.md +++ b/README.md @@ -204,6 +204,12 @@ turn is appended. Requests are counted, not user-visible turns: an agent turn wi three tool round-trips counts three times. Use a session header and a larger N when that matters. +The counter table lives in RAM: 4096 conversations with least-recently-used +eviction, an hour of idle expiry, and a restart that starts every conversation at +zero. The rule's identity is its model/path globs, not its line number, so +inserting a comment or another rule above it keeps the counters with the rule. +These resets change *when* a judge runs, never whether an answer is correct. + `cache` writes an Anthropic-style `cache_control` marker on the last message. Anthropic and gateways that translate the marker honour it. DeepSeek and other OpenAI-compatible providers cache repeated prefixes automatically; there `cache off` diff --git a/src/judge.c b/src/judge.c index a577149..f78f57b 100644 --- a/src/judge.c +++ b/src/judge.c @@ -17,8 +17,11 @@ #include "judge.h" -#define JUDGE_SLOTS 256 -#define JUDGE_PROBES 8 +/* A slot is small; 4096 of them cover far more parallel conversations than one + * junction instance serves. Only when every slot has a live conversation does the + * least-recently-used one get evicted. */ +#define JUDGE_SLOTS 4096 +#define JUDGE_PROBES 32 /* 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 @@ -56,12 +59,21 @@ static int step_for_count(unsigned count, const int *steps, int nsteps) return -1; } -int j_judge_tick(uint64_t conversation, int rule_line, const int *steps, int nsteps) +uint64_t j_judge_rule_id(const char *model_glob, const char *path_glob) +{ + uint64_t h = 1469598103934665603ULL; + h = fnv1a(h, model_glob ? model_glob : "", strlen(model_glob ? model_glob : "")); + h = fnv1a(h, "\x1f", 1); + h = fnv1a(h, path_glob ? path_glob : "", strlen(path_glob ? path_glob : "")); + return h ? h : 1; +} + +int j_judge_tick(uint64_t conversation, uint64_t rule_id, const int *steps, int nsteps) { if (nsteps <= 0) return -1; uint64_t key = conversation ? conversation : 1; - key ^= (uint64_t)(unsigned)rule_line * 0x9e3779b97f4a7c15ULL; + key ^= rule_id * 0x9e3779b97f4a7c15ULL; if (key == 0) key = 1; size_t start = (size_t)(key % JUDGE_SLOTS); @@ -92,7 +104,26 @@ int j_judge_tick(uint64_t conversation, int rule_line, const int *steps, int nst oldest_t = s->last; } } - int ix = free_slot >= 0 ? free_slot : oldest; + int ix = free_slot; + if (ix < 0) { + /* The probe window is full of live counters. Look for an empty or idle + * slot anywhere before evicting; if the table is truly full, evict the + * globally least-recently-used conversation. */ + int lru = -1; + double lru_t = 0.0; + for (int i = 0; i < JUDGE_SLOTS; i++) { + if (g_slots[i].key == 0 || now - g_slots[i].last > JUDGE_IDLE_S) { + lru = i; + break; + } + if (lru < 0 || g_slots[i].last < lru_t) { + lru = i; + lru_t = g_slots[i].last; + } + } + ix = lru >= 0 ? lru : oldest; + } + if (ix < 0) ix = oldest >= 0 ? oldest : (int)(start % JUDGE_SLOTS); judge_slot *s = &g_slots[ix]; s->key = key; s->count = 1; diff --git a/src/judge.h b/src/judge.h index 68d9f19..6672b7c 100644 --- a/src/judge.h +++ b/src/judge.h @@ -13,12 +13,21 @@ #include #include +/* Stable identity of a judge rule: hash of its model and path globs. The line + * number in the file is not part of it, so inserting a comment or another rule + * above it does not move the counters to a different conversation. Counters are + * kept in RAM (4096 conversations, least-recently-used eviction), expire after an + * hour of silence and start at zero again after a restart — sampling is + * statistical, not a correctness guarantee. */ +uint64_t j_judge_rule_id(const char *model_glob, const char *path_glob); + /* Returns the index of the judge step for this request, or -1 for the worker. * `steps` are the cumulative counts inside the chain (strictly ascending), e.g. * {5, 10}: the 5th request is step 0, the 10th is step 1, then the counter * starts again at 0. `conversation` comes from j_judge_conversation(); - * `rule_line` keeps counters of different rules apart. */ -int j_judge_tick(uint64_t conversation, int rule_line, const int *steps, int nsteps); + * `rule_id` comes from j_judge_rule_id(). */ +int j_judge_tick(uint64_t conversation, uint64_t rule_id, + const int *steps, int nsteps); /* 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. diff --git a/src/junction.c b/src/junction.c index 2252e76..97f18c3 100644 --- a/src/junction.c +++ b/src/junction.c @@ -4055,7 +4055,8 @@ static void handle_client_inner(j_conn *client) 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); - int step = j_judge_tick(conversation, rule->line, steps, rule->judge_count); + uint64_t rule_id = j_judge_rule_id(rule->model_glob, rule->path_glob); + int step = j_judge_tick(conversation, rule_id, steps, rule->judge_count); if (step >= 0) { const char *target = rule->judges[step].target; const char *judge_as = rule->judges[step].as; diff --git a/tests/control.py b/tests/control.py index e06a2b2..3c7f151 100755 --- a/tests/control.py +++ b/tests/control.py @@ -94,6 +94,17 @@ def chat(model="m", slow=False): return json.loads(r.read().decode())["model"] +def chat_judge(model="counter"): + req = urllib.request.Request( + f"http://127.0.0.1:{PORT}/v1/chat/completions", + data=json.dumps({"model": model, + "messages": [{"role": "user", "content": "hi"}]}).encode(), + method="POST", headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=15) as r: + body = json.loads(r.read().decode()) + return body.get("model"), r.headers.get("X-Junction-Judge-Served") + + def main(): servers = {} for name in ("a", "b"): @@ -126,6 +137,7 @@ endpoint b {{ pool both a, b +req for "counter" judge every 3 a as "m" pass b req for "*" pass a """ with open(conf, "w") as f: @@ -184,6 +196,27 @@ req for "*" pass a if chat() != "a": failures.append("die Ausgangsregel greift nicht") + # 1b. Der Judge-Zähler hängt an der Regel-Identität, nicht an ihrer + # Zeilennummer. Zwei Anfragen zählen bis 2; schiebt ein config.set + # die Regel durch eine Kommentarzeile nach unten, muss die dritte + # Anfrage trotzdem den Judge treffen. + m1, j1 = chat_judge() + m2, j2 = chat_judge() + if (m1, m2) != ("b", "b") or j1 or j2: + failures.append(f"Judge-Zähler Start: {m1}/{j1}, {m2}/{j2}") + text = ctrl({"cmd": "config.get"}).get("text") or "" + shifted = text.replace('req for "counter"', + '# shifted by one line\nreq for "counter"', 1) + r = ctrl({"cmd": "config.set", "text": shifted}) + if not r.get("ok"): + failures.append(f"config.set für den Judge-Zähler: {str(r)[:160]}") + m3, j3 = chat_judge() + if m3 != "a" or j3 != "1": + failures.append(f"Judge-Zähler überlebte die Zeilenverschiebung nicht: {m3}/{j3}") + # Die Regel wieder entfernen, damit die späteren Schritte weiterhin mit + # genau einer Regel arbeiten. + ctrl({"cmd": "rules.delete", "name": "counter"}) + # 2. neue Regel setzen, die sofort gewinnen muss (erste passende gewinnt, # also ersetzen wir die bestehende Regel für dasselbe Modell). r = ctrl({"cmd": "rules.set", "text": 'req for "*" pass b'}) @@ -333,10 +366,11 @@ req for "*" pass a print((proc.stderr.read() or b"").decode()[-1500:]) sys.exit(1) - print("PASS: 12 Prüfungen — Monatsauskunft (spend.get), Anfrage-Log (requests.tail), " + print("PASS: 13 Prüfungen — Monatsauskunft (spend.get), Anfrage-Log (requests.tail), " "ping/status, Regel sofort wirksam, Regel löschen, Endpunkt pausieren, " - "Konfiguration lesen/schreiben, Live-Regel-Pools, Config-Swap wartet auf " - "laufende Anfrage, kaputte Konfiguration abgelehnt, TCP-Kanal") + "Konfiguration lesen/schreiben, Live-Regel-Pools, Judge-Zähler überlebt " + "eine Zeilenverschiebung, Config-Swap wartet auf laufende Anfrage, " + "kaputte Konfiguration abgelehnt, TCP-Kanal") if __name__ == "__main__":