diff --git a/docs/index.html b/docs/index.html new file mode 100644 index 0000000..b02ce71 --- /dev/null +++ b/docs/index.html @@ -0,0 +1,613 @@ + + + + + + +junction — policy router for OpenAI-compatible endpoints + + + + +
+
+

junction

+

A policy router for OpenAI-compatible model endpoints. It sits in front of + N servers and decides per request which one answers — and what happens when none of + them wants to.

+

+ C99POSIX + no runtime dependenciessingle text config + ~5,200 lines of C94 tests +

+
+
+ +
+ +
+

What it is

+

You run more than one model server. Maybe a paid cloud account, two free tiers, a + workstation that sleeps, a box on the LAN that is only good for small prompts. Your + clients speak /v1/chat/completions and should keep doing so.

+

junction is the thing in between. It reads one text file of rules, picks a target per + request, tries the next one when the first fails, keeps streams intact, and tells you in + the response headers and in /status exactly what it did.

+

The rule language is deliberately close to pf.conf: first match wins, + unknowns are a hard error with a line number, and there is no silent fallback to + "somewhere". A request that matches no rule gets 503 no_matching_rule, + because a gap in the configuration is not a routing decision.

+
+ +
+

Features

+ +
+

Routing

+
    +
  • Per-request rules, first match wins — model glob, path glob, declared + output budget, estimated prompt size, vision/text, endpoint health
  • +
  • Fallback chains: pass a, b, c — targets tried in order
  • +
  • Named pools, reusable and nestable: pool lokal box3, box6
  • +
  • Explicit refusal: block answers 403 instead of rerouting
  • +
  • Model rewrite per target: as "local-name"
  • +
  • Skip reasons named in the 503 body and in /status
  • +
+
+ +
+

Load and cost

+
    +
  • Four selection modes: first, round-robin, least-usage, cost
  • +
  • Weights per endpoint, honoured by round-robin and by the cost score
  • +
  • Balance mode per rule, overriding the global one
  • +
  • Budgets soft/hard in percent, with throttle or skip
  • +
  • Usage from outside: a command prints a number, junction polls it
  • +
  • Off-peak window halves the price of a target inside it
  • +
+
+ +
+

Failure

+
    +
  • Two timeouts: total, and silence — the latter emits a keep-alive + comment so a thinking model is not killed
  • +
  • Per-endpoint connect timeout, separate from the global one
  • +
  • Cooldown after a failed attempt, offline hold after a refused + connection — no retry storm
  • +
  • Queue instead of reject: bounded wait with a position notice
  • +
  • Hooks that decide whether a target is usable, with retry and backoff
  • +
  • Wake-on-LAN once, before the hooks are retried
  • +
+
+ +
+ +
+

Protocol

+
    +
  • Streaming preserved byte for byte, including chunked framing
  • +
  • Chunked request bodies decoded, so upstreams see a length
  • +
  • opencode bridge: session-based API translated to OpenAI in both directions
  • +
  • Header injection per endpoint, plus X-Forwarded-For/Proto
  • +
  • TLS both ways, with a private CA per endpoint
  • +
+
+ +
+

Memory and context

+
    +
  • Tool-output compression: deterministic, no model call, per endpoint — + measured 47,088 → 2,040 bytes on a 900-line log
  • +
  • Original bytes otherwise: compression splices spans, it never + re-serialises the body
  • +
  • Never touches system, user or assistant messages, nor the last N
  • +
  • Bounded everything: body size, cache bytes, inflight count
  • +
+
+ +
+

Operation

+
    +
  • Virtual keys: clients get their own key, restricted to model globs and + endpoint sets — the real upstream key never leaves the host
  • +
  • /status as JSON: endpoints, counters, cache, queue, rules
  • +
  • Admin API: pause, resume, flush cache
  • +
  • Response cache in memory, LRU, respecting Cache-Control
  • +
  • Strict config parsing with line numbers; --check without + starting
  • +
+
+ +
+
+ +
+

Build

+
$ make
+$ sudo make install          # binary, systemd unit, example config
+
+$ junction --config /etc/junction/junction.conf --check
+$ junction --config /etc/junction/junction.conf
+

OpenSSL is the only optional dependency, needed for TLS. Without it, junction builds as + plain HTTP. The flags are -std=c99 -Wall -Wextra -Wpedantic -Wshadow -Wconversion; + the tree builds clean under all of them.

+
+ +
+

How a request is decided

+

A client asks for model: "chat" with roughly 3,000 prompt tokens and + no declared output budget. Rules are read top to bottom:

+
req path "/v1/models" check none pass cloud      no match - different path
+req for "*embed*" check none pass embed           no match - different model
+req vision pass workstation, cloud as "v"         no match - no image
+req ctx <2000 pass workstation                    no match - prompt is larger
+req ctx <50000 pass ollama1, cloud                match    - 3,000 is below 50,000
+

The matched rule lists two targets. junction asks the first; if its connection is + refused, that target is marked offline for offline_hold_s and the second one is + tried within the same request. Every response says which target answered:

+
X-Junction-Endpoint: ollama1
+X-Junction-Ms: 412
+X-Junction-Cache: off
+
+ +
+

Full reference configuration

+

Every key the parser knows, each with the reasoning behind it. Copy the file and delete + the parts you do not need — not the comments.

+
# ============================================================================
+#  junction — vollständige Referenzkonfiguration
+# ============================================================================
+#
+# Diese Datei enthält JEDEN Schlüssel, den der Parser kennt, jeweils mit einer
+# Erklärung und einem sinnvollen Wert. Sie ist zum Abschreiben gedacht: für den
+# Betrieb die überflüssigen Endpunkte löschen, nicht die Erklärungen.
+#
+# Grammatik: Schlüsselwort, Argumente, geschweifte Klammern. `#` ist Kommentar,
+# doppelte Anführungszeichen fassen Wörter zusammen. Ein unbekanntes Schlüsselwort
+# ist ein harter Fehler mit Zeilennummer — es gibt keine stillen Tippfehler.
+#
+# Prüfen ohne zu starten:   junction --config diese-datei --check
+# ============================================================================
+
+
+# ---------------------------------------------------------------- Zuhörer
+#
+# Wohin junction lauscht. Ohne `tls` reines HTTP. Mit `tls` zwei Zertifikatspfade
+# in dieser Reihenfolge: Zertifikat, Schlüssel.
+#
+# Loopback ist die richtige Wahl, wenn der Prozess echte Upstream-Schlüssel in
+# seiner Umgebung hält — er ist dann kein offener Proxy für LAN oder VPN.
+listen 127.0.0.1:8090
+# listen 0.0.0.0:8443 tls /etc/junction/tls/cert.pem /etc/junction/tls/key.pem
+
+# Präfix jeder Logzeile. Steht hier, damit im Code kein Produktname auftaucht.
+log_prefix junction
+
+
+# ---------------------------------------------------------------- Zeitlimits
+#
+# Verbindungsaufbau zum Endpunkt. Ein Fehlschlag hier heißt sofort "offline" —
+# das ist kein Wiederholfall, ein nicht antwortender Rechner wird nicht besser,
+# wenn man ihn zweimal fragt.
+connect_timeout_ms 1500
+
+# Wie lange ein Endpunkt nach einem Verbindungsfehler als offline gilt, bevor
+# ihn der nächste Versuch wieder prüft. Sekunden.
+offline_hold_s 20
+
+# Obergrenze für einen Anfragekörper. Schutz gegen einen Client, der den Router
+# als Speicher missbraucht.
+max_body_bytes 67108864
+
+
+# ---------------------------------------------------------------- Nebenläufigkeit
+#
+# Wie viele Anfragen gleichzeitig zu Upstreams unterwegs sein dürfen. Der Rest
+# wartet in einer Schlange, statt abgewiesen zu werden.
+max_inflight 8
+
+# Wie lange ein Wartender höchstens in der Schlange steht, bevor er eine Antwort
+# bekommt. Sekunden. Danach: Fehlerereignis, bei Streamern gefolgt von [DONE].
+queue_timeout 300
+
+
+# ---------------------------------------------------------------- Antwort-Cache
+#
+# Nur im Speicher, LRU, Schlüssel ist Methode + Pfad + Modell + Körper. Streams
+# werden nie zwischengespeichert. `Cache-Control: no-store/private` des Upstreams
+# und `no-cache` des Clients werden respektiert.
+#
+# 0 bedeutet: Cache aus. Ein Cache auf einem Router, der Modelle mit
+# unterschiedlichen Temperaturen bedient, ist meist falsch — deshalb hier aus.
+cache_ttl 0
+cache_entries 0
+cache_bytes 0
+
+
+# ---------------------------------------------------------------- Prompt-Größe
+#
+# Zeichen pro Token für die Schätzung, die Regeln mit `ctx` benutzen. 0 (Standard) heißt:
+# keine Schätzung, und eine Regel mit ctx-Bedingung wird beim Laden abgelehnt — besser ein
+# Fehler als eine Regel, die still nie greift.
+#
+# Der Wert ist eine Annahme über die Tokenisierung, keine Messung. Base64-Bilddaten werden
+# bei der Zählung übersprungen, sonst zählt ein Foto als Hunderttausend Token.
+ctx_chars_per_token 4
+
+
+# ---------------------------------------------------------------- Auswahlreihenfolge
+#
+# Wie Ziele INNERHALB einer Regel geordnet werden, wenn mehrere genannt sind:
+#   first        in der Reihenfolge der Regel (reiner Failover)
+#   round-robin  reihum, gleichmäßig
+#   least-usage  kleinster eigener Verbrauch zuerst (Prozent des Budgets)
+#   cost         Verbrauch × Preis; im Off-Peak-Fenster halbiert sich der Preis
+balance cost
+
+
+# ---------------------------------------------------------------- virtuelle Schlüssel
+#
+# Clients bekommen diese Schlüssel, nie den echten Upstream-Schlüssel. Der Wert
+# steht in einer Umgebungsdatei (0600 root), hier steht nur der Name der Variable.
+#
+#   vkey "name" token_env VAR allow "<modell-glob>" [endpoints "a,b"]
+#
+# `allow` begrenzt die Modelle, `endpoints` zusätzlich die Ziele. Ein Schlüssel,
+# der nur DeepSeek darf, kann keinen GPT-Aufruf auslösen, selbst wenn eine Regel
+# es erlauben würde.
+vkey "webui"     token_env VKEY_WEBUI     allow "deepseek-*"
+vkey "navigator" token_env VKEY_NAVIGATOR allow "*" endpoints "ollama1,ollama2"
+vkey "hermes"    token_env VKEY_HERMES    allow "*"
+
+
+# ============================================================================
+#  Endpunkte
+# ============================================================================
+
+# ---------------------------------------------------------------- Abo-Cloud
+#
+# Der teuerste Weg pro Anfrage, aber bezahlt: die Grenzkosten sind fast null.
+# `cost` ist hier ein Vergleichsgewicht, kein Geldbetrag.
+endpoint cloud {
+    base https://opencode.ai/zen/go/v1
+    kind cloud
+    context 200000
+
+    # Niedrigere Zahl gewinnt, wenn eine Regel mehrere Ziele ohne eigene
+    # Reihenfolge nennt. Relevant nur bei balance first.
+    priority 90
+
+    # Gesamtzeit für eine Anfrage und Stille-Zeit bis "still_working" im Log
+    # steht. Zwei Werte, weil ein denkendes Modell nicht hängt.
+    timeout 900
+    idle_timeout 120
+
+    # Eigenes Verbindungs-Zeitlimit: dieses Ziel steht hinter einem Tunnel, ein
+    # ausgefallener Aufbau soll die Kette nach 400 ms weiterreichen, nicht nach 1,5 s.
+    connect_timeout_ms 400
+
+    tls_verify on
+    api_key_env OPENCODE_GO_API_KEY
+
+    # Manche Upstreams hinter Cloudflare weisen fremde User-Agents ab (403/1010)
+    # und verlangen eine Session-Kennung. header ist wiederholbar.
+    header "User-Agent: Mozilla/5.0 (X11; Linux x86_64) client/1.0"
+    header "x-opencode-session: ses-webui-01"
+
+    # Verbrauch von außen messen: das Skript gibt eine Zahl aus, junction pollt sie.
+    usage_cmd /usr/local/libexec/junction-usage-opencode.sh
+    usage_poll 120
+
+    # Weiche und harte Grenze in Prozent. Über soft wird gedrosselt, über hard
+    # übersprungen — aber nur, wenn eine Regel noch ein anderes Ziel nennt.
+    budget soft 85
+    budget hard 96
+    on_soft delay 2
+    on_hard skip
+
+    cost 0.1
+    cache off
+}
+
+# ---------------------------------------------------------------- Guthaben-Cloud, zwei Konten
+#
+# Zwei Konten desselben Anbieters, je mit eigenem Monatsguthaben. Beide Endpunkte
+# sind gleich aufgebaut; unterschieden werden sie nur durch Schlüssel, Verbrauchs-
+# messung und Priorität.
+# Gewicht: höher = häufiger. Unter round-robin bekommt ein Ziel mit Gewicht 3 drei
+# Plätze in der Runde, unter cost/least-usage zählt sein Verbrauch nur ein Drittel.
+endpoint ollama1 {
+    weight 3
+    base https://ollama.com/v1
+    kind cloud
+    context 128000
+    priority 50
+    timeout 900
+    idle_timeout 120
+    tls_verify on
+    api_key_env OLLAMA_KEY1
+
+    usage_cmd "/usr/local/libexec/junction-usage-ollama.sh 1"
+    usage_poll 180
+    budget soft 80
+    budget hard 95
+    on_soft delay 1
+    on_hard skip
+
+    # Fenster, in dem dieser Endpunkt billiger ist: von 18:00 bis 12:00 des
+    # Folgetages. Ein Fenster, nicht zwei — "Wochenende ganztägig" lässt sich
+    # damit nicht ausdrücken.
+    offpeak 18:00-12:00
+    cost 1.5
+}
+
+endpoint ollama2 {
+    base https://ollama.com/v1
+    kind cloud
+    context 128000
+    priority 50
+    timeout 900
+    idle_timeout 120
+    tls_verify on
+    api_key_env OLLAMA_KEY2
+    usage_cmd "/usr/local/libexec/junction-usage-ollama.sh 2"
+    usage_poll 180
+    budget soft 80
+    budget hard 95
+    on_soft delay 1
+    on_hard skip
+    offpeak 18:00-12:00
+    cost 1.5
+}
+
+# ---------------------------------------------------------------- lokaler Rechner mit Aufwecken
+#
+# Der interessante Fall: eine Workstation, die schläft. `wake` läuft einmal,
+# bevor die Haken wiederholt werden — erst wecken, dann warten.
+endpoint workstation {
+    base http://192.0.2.20:8080/v1
+    kind local
+    context 128000
+    priority 10
+    timeout 1800
+    idle_timeout 30
+
+    # Haken: Exit 0 heißt benutzbar, alles andere "noch nicht". Der Grund, den
+    # der Haken auf stdout schreibt, landet in /status und im 503-Körper.
+    hook /usr/local/share/junction/hooks/check-http.sh
+
+    # Wie lange insgesamt auf den Rechner gewartet wird und in welchem Abstand.
+    hook_retry 180
+    hook_backoff 5
+
+    # Einmaliger Weckruf vor dem ersten Wiederholen.
+    wake /usr/local/share/junction/hooks/wake-wol.sh
+
+    # Statischer Kopfzeilen-Zusatz pro Endpunkt.
+    header "X-Box: workstation"
+
+    # Kann dieser Endpunkt Bilder? on = ja, off = nein, weglassen = keine Prüfung.
+    # Ein Text-Endpunkt wird für eine Bildanfrage übersprungen, statt sie anzunehmen
+    # und mit leerem Inhalt zu antworten.
+    vision off
+
+    # Ein lokaler Rechner kostet Strom, kein Geld. Kleines Gewicht, damit er im
+    # Vergleich gewinnt, solange er wach ist.
+    cost 0.0
+    cache on
+    tls_verify off
+}
+
+# ---------------------------------------------------------------- privates TLS mit eigener CA
+endpoint private-tls {
+    base https://llm.internal.example/v1
+    kind remote
+    context 32000
+    priority 30
+    timeout 600
+    idle_timeout 90
+    cooldown 120
+    tls_verify on
+    tls_ca /etc/junction/ca/internal-ca.pem
+    api_key_env INTERNAL_KEY
+    cache on
+}
+
+# ---------------------------------------------------------------- opencode serve
+#
+# opencode spricht kein OpenAI-Protokoll: seine API ist sitzungsorientiert
+# (/api/session, /prompt, /model, /message). Mit `kind opencode` übersetzt junction das
+# in beide Richtungen, sodass ein Client weiter /v1/chat/completions spricht.
+#
+# Zwei Werte kommen aus Kommandos, weil opencode sie nicht festhält: der Hintergrund-
+# dienst bindet einen freien Port, und er erzeugt bei jedem Start ein neues Passwort.
+endpoint opencode {
+    base http://127.0.0.1:4096
+    kind opencode
+    context 200000
+    timeout 600
+    idle_timeout 120
+    auth_basic opencode
+    pass_cmd /usr/local/libexec/opencode-password.sh
+    # Nur nötig, wenn der Dienst auf einem zufälligen Port läuft:
+    # base_cmd "/usr/local/bin/opencode service status"
+    cost 0.0
+}
+
+# ---------------------------------------------------------------- Einbetter, klein und billig
+endpoint embed {
+    base http://192.168.1.10:11434/v1
+    kind local
+    context 8192
+    priority 10
+    timeout 120
+    idle_timeout 45
+    # Nach einem Fehlschlag so viele Sekunden Pause, statt bei jeder Anfrage neu
+    # in ein Timeout zu laufen.
+    cooldown 30
+    cache on
+}
+
+
+# ============================================================================
+#  Regeln — erste Übereinstimmung gewinnt
+# ============================================================================
+#
+#   req [for <modell-glob>] [path <glob>] [need >N | <N | N]
+#       [check hooks|none] [retry <s>]
+#       ( pass <ziel>[,<ziel>...] [as <modell>] | block )
+#
+# for   — Modellname aus dem Anfragekörper, fnmatch-Muster
+# path  — Pfad, fnmatch-Muster
+# need  — das vom Client ANGEGEBENE Ausgabebudget (max_tokens /
+#         max_completion_tokens). Kein Raten, keine Zeichenzählung: eine Anfrage
+#         ohne Angabe erfüllt keine need-Regel. >64000 heißt "mehr als 64k
+#         angefordert"; ein Endpunkt mit kleinerem context wird dann übersprungen.
+# check — haken (Standard des Endpunkts) oder none (Haken überspringen, z.B. bei
+#         Modell-Listen, die auch dann sinnvoll sind, wenn nichts läuft)
+# retry — Wartezeit für Haken, überschreibt hook_retry dieser Regel
+# as    — schreibt das Modellfeld NUR für dieses Ziel um. Der erste Ziel bekommt
+#         die lokale Kennung, der letzte die angefragte.
+
+# Modell-Liste: kein Haken nötig, sie beantwortet auch ein schlafender Rechner.
+req path "/v1/models" check none pass cloud
+
+# Einbetter laufen lokal, egal was sonst gilt.
+req for "*embed*" check none pass embed
+
+# Die freien opencode-Modelle gehen an den opencode-Endpunkt, alles andere nicht.
+req for "opencode/*" pass opencode
+req for "*-free" pass opencode
+
+# Bildanfragen: immer an das Bildmodell, unabhängig vom angefragten Namen. Erst der
+# eigene Rechner (kostet nichts), dann die Cloud — dort mit umgeschriebenem Modellnamen.
+# "as" gilt für das Ziel direkt davor, nicht für die ganze Regel.
+req vision pass workstation, cloud as "vision-capable-model"
+
+# Kleine Anfragen an den eigenen Rechner, mittlere an das Guthaben, große an das Abo mit
+# dem großen Kontext. Reihenfolge zählt: das engste Fenster zuerst, sonst fängt das
+# größere alles ab. Die Zahlen sind Politik und gehören hierher, nicht in den Code.
+req ctx <2000 pass workstation
+req ctx <50000 pass ollama1, cloud
+req ctx >50000 pass cloud
+
+# Große Budgets kann der lokale Rechner nicht halten — also gar nicht erst hin.
+req need >64000 pass cloud, ollama1
+
+# Ein Modell, das es nur lokal gibt, mit lokalem Namen; sonst dieselbe Anfrage
+# an die Cloud weitergereicht.
+req for "*coder*" retry 300 pass workstation as "qwen3.8-flash-next-q1m", cloud
+
+# Ein Modell, das es nicht geben darf. 403, kein stilles Umleiten.
+req for "blocked-*" block
+
+# Alles Übrige: erst der wache lokale Rechner, dann die Cloud, dann Guthaben.
+# Kein Treffer für eine Anfrage bedeutet 503 no_matching_rule — eine Lücke in der
+# Konfiguration ist kein Fall für "irgendwohin schicken".
+# Ketten einen Namen geben. Ein Pool darf auch auf einen anderen verweisen; beim Laden
+# wird er aufgelöst, damit eine Regel nicht jedes Mal fünf Ziele ausschreiben muss.
+pool lokal   ollama1, ollama2
+pool alles   cloud, lokal
+
+# Ein Endpunkt darf auch in einer Zeile stehen, wenn er klein ist:
+#   endpoint kurz { base http://127.0.0.1:8080/v1; timeout 60 }
+
+# Diese eine Regel will reines Failover, egal was global eingestellt ist.
+req for "starr*" balance first pass workstation, cloud
+
+req for "*" check hooks pass workstation, cloud, ollama1, ollama2
+
+
+# ============================================================================
+#  Steuerung zur Laufzeit
+# ============================================================================
+#
+#   GET  /status                 Endpunkte, Zähler, Cache, Regeln, Schlange
+#   POST /admin/pause/<name>     dort nicht mehr routen
+#   POST /admin/resume/<name>    Pause, Abkühlung und Offline zurücksetzen
+#   POST /admin/flush/cache      jeden zwischengespeicherten Antwortkörper verwerfen
+#
+# Alles andere wird an den Endpunkt weitergeleitet, den die Regeln wählen.
+# Jede Antwort trägt X-Junction-Endpoint, X-Junction-Ms und X-Junction-Cache.
+
+
+ +
+

Known limits

+
Named on purpose. A router that hides its edges gets trusted further + than it should.
+ + + + + + + + + + + + + + +
LimitWhat it means in practice
one off-peak windowA target can be cheaper inside a single daily time range. "All + weekend" is not expressible.
flat chainsA rule lists targets; a target cannot call another rule. Branching by + subject matter needs more rules, not nested ones.
one processState — counters, cooldowns, cache — lives in memory. Restarting the + router resets it, and there is no clustering.
estimated contextPrompt size is estimated from characters per token, a number you + supply. It is an assumption, not a tokenizer.
no auth beyond keysVirtual keys separate clients and limit what they may ask for. There is + no user database, no quota accounting per person.
compression is not memoryIt shortens what is sent. It cannot bring anything back later — that + needs a tool the model calls, which lives in the agent, not the router.
+
+ +
+

junction · version 0.1 · C99 and POSIX · built and tested on + Debian with gcc and clang

+

Free software under the MIT licence. Written to be read: roughly 5,200 lines of C across + twelve files, plus 1,200 lines of test scripts.

+
+ +
+ + diff --git a/examples/full-reference.conf b/examples/full-reference.conf index 2ad39c6..4c0a058 100644 --- a/examples/full-reference.conf +++ b/examples/full-reference.conf @@ -67,6 +67,12 @@ cache_ttl 0 cache_entries 0 cache_bytes 0 +# Nur Anfragen zwischenspeichern, deren Antwort vorhersagbar ist: Temperatur 0, oder +# ein Einbetter (derselbe Text ergibt immer denselben Vektor). Eine Antwort mit +# Temperatur 0.7 zwischenzuspeichern hieße, dem zweiten Fragesteller eine fremde +# Antwort zu geben — das ist keine Ersparnis, sondern eine falsche Antwort. +cache_deterministic_only on + # ---------------------------------------------------------------- Prompt-Größe # diff --git a/src/config.c b/src/config.c index f5e32cb..b9fb60e 100644 --- a/src/config.c +++ b/src/config.c @@ -82,6 +82,7 @@ void j_config_defaults(j_config *cfg) cfg->cache_entries = 128; cfg->cache_bytes = 32L * 1024 * 1024; cfg->ctx_chars_per_token = 0; + cfg->cache_deterministic_only = 1; cfg->compress = J_COMPRESS_OFF; cfg->compress_keep = 4; cfg->compress_min_bytes = 2048; /* Schaetzung aus, bis sie ausdruecklich gesetzt wird */ @@ -162,6 +163,13 @@ static int global_kw(j_config *cfg, char **w, int n, int lineno, char *err, size if (!strcmp(k, "cache_ttl")) { if (n != 2 || as_double(w[1], &cfg->cache_ttl_s)) goto bad; return 0; } if (!strcmp(k, "cache_entries")) { if (n != 2 || as_long(w[1], &cfg->cache_entries)) goto bad; return 0; } if (!strcmp(k, "cache_bytes")) { if (n != 2 || as_long(w[1], &cfg->cache_bytes)) goto bad; return 0; } + if (!strcmp(k, "cache_deterministic_only")) { + if (n != 2) goto bad; + if (!strcmp(w[1], "on")) cfg->cache_deterministic_only = 1; + else if (!strcmp(w[1], "off")) cfg->cache_deterministic_only = 0; + else goto bad; + return 0; + } if (!strcmp(k, "compress")) { if (n != 2) goto bad; if (!strcmp(w[1], "off")) cfg->compress = J_COMPRESS_OFF; diff --git a/src/config.h b/src/config.h index 2d22eec..0dcd573 100644 --- a/src/config.h +++ b/src/config.h @@ -214,6 +214,8 @@ typedef struct { /* Kürzen von Werkzeugausgaben im Anfrageweg. Standard: aus. * Bewusst global und nicht pro Regel: gekürzt wird, bevor der Regelvergleich den * Kontext schätzt — eine Regel kann also nicht darüber entscheiden. */ + int cache_deterministic_only; /* nur Anfragen mit Temperatur 0 zwischenspeichern */ + int compress; /* J_COMPRESS_OFF | J_COMPRESS_TOOL */ int compress_keep; /* so viele Nachrichten am Ende bleiben vollständig */ int compress_min_bytes; /* kleinere Ausgaben werden nicht angefasst */ diff --git a/src/junction.c b/src/junction.c index ece0792..53aedbc 100644 --- a/src/junction.c +++ b/src/junction.c @@ -120,6 +120,24 @@ static int json_bool_value(const char *body, const char *key) return !strncmp(p, "true", 4); } +/* Liest eine Zahl. Rückgabe: 1 = gefunden, 0 = nicht vorhanden, -1 = kein Wert. */ +static int json_num_value(const char *body, const char *key, double *out) +{ + if (!body) return 0; + char pat[64]; + snprintf(pat, sizeof pat, "\"%s\"", key); + const char *p = strstr(body, pat); + if (!p) return 0; + p += strlen(pat); + while (*p && (*p == ':' || isspace((unsigned char)*p) || *p == '"')) p++; + if (!*p) return -1; + char *end = NULL; + double v = strtod(p, &end); + if (end == p) return -1; + *out = v; + return 1; +} + static void json_str_value(const char *body, const char *key, char *out, size_t outlen) { char pat[64]; @@ -1483,6 +1501,24 @@ static int request_is_cacheable(const j_req *rq, char *why, size_t whylen) snprintf(why, whylen, "client_no_cache"); return 0; } + + /* Eine Antwort mit Temperatur über null ist nicht reproduzierbar. Sie + * zwischenzuspeichern hieße, dem zweiten Fragesteller eine fremde Antwort zu geben — + * das ist keine Ersparnis, das ist eine falsche Antwort. Einbetter sind ausgenommen: + * sie liefern für denselben Text immer denselben Vektor. */ + if (CFG.cache_deterministic_only) { + if (strstr(rq->path, "embedding")) return 1; + double temp = 0; + int found = json_num_value(rq->body, "temperature", &temp); + if (found != 1) { + snprintf(why, whylen, "temperature_unknown"); + return 0; + } + if (temp > 0.0) { + snprintf(why, whylen, "temperature_gt_zero"); + return 0; + } + } return 1; } diff --git a/tests/cache.sh b/tests/cache.sh new file mode 100644 index 0000000..f707b9c --- /dev/null +++ b/tests/cache.sh @@ -0,0 +1,65 @@ +#!/bin/bash +# Wird von tests/run.sh eingebunden: Antwort-Cache und seine Grenze. + +echo "== 22. Cache nur für vorhersagbare Antworten ==" + +XPORT=$((PORT+51)) +cat > "$TMP/cache.conf" < "$TMP/cache.log" 2>&1 & +PIDS+=($!) +sleep 0.8 + +ask() { # ask -> Cache-Zustand aus dem Kopf + curl -s -m 10 -D - -o /dev/null -X POST -H 'Content-Type: application/json' -d "$1" \ + "http://127.0.0.1:$XPORT/v1/chat/completions" \ + | tr -d '\r' | sed -n 's/^[Xx]-[Jj]unction-[Cc]ache: //p' +} + +DET='{"model":"m","messages":[{"role":"user","content":"dieselbe frage"}],"max_tokens":5,"temperature":0}' +HOT='{"model":"m","messages":[{"role":"user","content":"dieselbe frage"}],"max_tokens":5,"temperature":0.7}' +NONE='{"model":"m","messages":[{"role":"user","content":"dieselbe frage"}],"max_tokens":5}' + +[ "$(ask "$DET")" = "miss" ] && ok "first deterministic request misses the cache" \ + || bad "first deterministic request did not report a miss" +[ "$(ask "$DET")" = "hit" ] && ok "second identical request is served from the cache" \ + || bad "second identical request was not cached" + +if [ "$(ask "$HOT")" = "off" ]; then + ok "a request with temperature above zero is never cached" +else + bad "a non-deterministic request was routed through the cache" +fi + +if [ "$(ask "$NONE")" = "off" ]; then + ok "a request without a stated temperature is not cached" +else + bad "a request without a temperature was cached anyway" +fi + +# Einbetter sind reproduzierbar: derselbe Text ergibt denselben Vektor. +EMB='{"model":"e","input":"derselbe text"}' +emb_state() { + curl -s -m 10 -D - -o /dev/null -X POST -H 'Content-Type: application/json' -d "$EMB" \ + "http://127.0.0.1:$XPORT/v1/embeddings" | tr -d '\r' \ + | sed -n 's/^[Xx]-[Jj]unction-[Cc]ache: //p' +} +emb_state >/dev/null # erster Aufruf füllt +OUT=$(emb_state) +if [ "$OUT" = "hit" ]; then + ok "an embedding request is cached without asking for a temperature" +else + bad "an embedding request was not cached (state: ${OUT:-none})" +fi + +STATUS=$(curl -s -m 5 "http://127.0.0.1:$XPORT/status") +case "$STATUS" in + *'"hits":'*) ok "/status reports cache counters" ;; + *) bad "/status has no cache counters" ;; +esac diff --git a/tests/run.sh b/tests/run.sh index 6394143..ab347c1 100755 --- a/tests/run.sh +++ b/tests/run.sh @@ -20,7 +20,7 @@ contains() { case "$1" in *"$2"*) ok "$3";; *) bad "$3 (missing '$2')";; esac; } # A leftover process on a test port produces confusing failures (a stale junction can # answer requests with somebody else's config), so fail loudly and early. -for port in 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8165 8166 8167 8168 8175 8176 8177 9443 9990 9991 9992 9993 9994 9995 9996; do +for port in 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8165 8166 8167 8168 8175 8176 8177 8185 8186 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/^/ /' @@ -262,7 +262,8 @@ contains "$RESP" "X-Stub-Body-Len: ${#BODY}" "decoded body reached the endpoint # same request twice: the second must come out of the cache (own body — the chunked # request above already filled the cache for its own body) -CBODY='{"model":"cachemodel","messages":[{"role":"user","content":"cache me once"}],"max_tokens":8}' +# Temperatur 0, weil der Cache sonst bewusst nicht greift (siehe Abschnitt 22). +CBODY='{"model":"cachemodel","messages":[{"role":"user","content":"cache me once"}],"max_tokens":8,"temperature":0}' R1=$(curl -s -m 10 -D- -o /dev/null -X POST -H 'Content-Type: application/json' -d "$CBODY" \ "http://127.0.0.1:$FEAT/v1/chat/completions") contains "$R1" "X-Junction-Cache: miss" "first request is a cache miss" @@ -635,6 +636,10 @@ contains "$OUT" "bad arguments" "an impossible offpeak window is rejected" # shellcheck source=tests/compress.sh . "$(dirname "$0")/compress.sh" +# Antwort-Cache und seine Grenze. +# shellcheck source=tests/cache.sh +. "$(dirname "$0")/cache.sh" + echo if [ "$FAILED" -eq 0 ]; then echo "PASS"; else echo "FAILURES"; fi exit "$FAILED"