judge: Zähler an stabile Regel-Identität binden, Tabelle vergrößern

Der Judge-Zähler hing an der Zeilennummer der Regel. Ein config.set, das
oberhalb eine Kommentar- oder Regelzeile einfügt, verschob die Regel und
gab ihr damit einen frischen Zähler; die Kette konnte zu früh oder gar
nicht auslösen.

j_judge_rule_id hasht jetzt model/path-Glob der Regel und ersetzt die
Zeilennummer als Schlüssel. Die Tabelle wächst von 256 auf 4096 Plätze;
bei vollem Probe-Fenster wird zuerst irgendwo ein freier oder abgelaufener
Platz gesucht und erst dann die global am längsten unbenutzte
Unterhaltung verdrängt. Statt 8 werden 32 Plätze geprobt.

Die Semantik ist in judge.h und README dokumentiert: RAM, LRU-Verdrängung,
eine Stunde Idle-Ablauf, Reset nach dem letzten Kettenschritt und beim
Neustart. Das beeinflusst nur, wann ein Judge läuft, nie die Korrektheit
einer Antwort.

Test in control.py: zwei Anfragen zählen bis 2, ein config.set mit einer
eingefügten Kommentarzeile verschiebt die Regel, die dritte Anfrage geht
trotzdem an den Judge (Served: 1). Die Testregel wird danach entfernt,
damit die übrigen Schritte weiter mit einer Regel arbeiten.

Tests: 484 OK, 0 FAIL.
This commit is contained in:
Hermes committed 2026-11-18 08:28:34 +00:00
1 parent 43e3f11c88
commit 2c649691e2
5 files changed
+92 -11

No files matched your search

+6
View File
@@ -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`
+36 -5
View File
@@ -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;
+11 -2
View File
@@ -13,12 +13,21 @@
#include <stddef.h>
#include <stdint.h>
/* 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.
+2 -1
View File
@@ -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;
+37 -3
View File
@@ -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__":