Cache nur für vorhersagbare Antworten

Der Cache war seit dem ersten Tag da, aber standardmäßig aus — und das aus einem Grund,
der sich mit einem Schalter allein nicht beheben ließ: er hat jedes identische Paar aus
Pfad und Rumpf gleich behandelt. Zwei Anfragen mit Temperatur 0.7 sind aber nicht
identisch, sie sind nur gleich formuliert. Der zweite Fragesteller hätte die Antwort des
ersten bekommen.

Neu:

  cache_deterministic_only on     (Standard)

Damit landet nur im Cache, was reproduzierbar ist — Temperatur genau 0, oder ein Aufruf
an /v1/embeddings, wo derselbe Text immer denselben Vektor ergibt. Alles andere trägt
X-Junction-Cache: off und geht durch.

Gemessen: temp 0 → miss, hit, hit, hit; temp 0.7 → off, off; ohne Angabe → off.
Einbetter → beim zweiten Aufruf hit.

100 Prüfungen, keine Fehler. Der alte Cache-Test fragte ohne Temperatur und musste
mitziehen; die Einbetter-Prüfung fragte nur einmal und prüfte damit den leeren Cache.
This commit is contained in:
Hermes committed 2026-11-05 09:29:53 +00:00
1 parent d33b7a1d10
commit 0503540760
7 files changed
+737 -2

No files matched your search

+613
View File
@@ -0,0 +1,613 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="description" content="junction — a policy router for OpenAI-compatible model endpoints. C99 and POSIX, one config file, no runtime dependencies.">
<meta name="keywords" content="llm router, openai compatible, failover, load balancing, c99, posix, self-hosted">
<title>junction — policy router for OpenAI-compatible endpoints</title>
<style type="text/css">
html,body{margin:0;padding:0}
body{background:#0d1117;color:#c9d1d9;font:15px/1.6 "Helvetica Neue",Helvetica,Arial,sans-serif}
a{color:#6ea8fe;text-decoration:none}
a:hover{text-decoration:underline}
.wrap{width:960px;margin:0 auto;padding:0 20px}
.masthead{border-bottom:1px solid #21262d;background:#0a0e14;padding:38px 0 30px}
h1{font:600 34px/1.1 "Helvetica Neue",Helvetica,Arial,sans-serif;margin:0;color:#f0f6fc;letter-spacing:-.5px}
h1 span{color:#6ea8fe}
.tag{color:#8b949e;font-size:16px;margin:10px 0 0;max-width:640px}
.meta{margin:18px 0 0;font-size:12.5px;color:#6b7787;letter-spacing:.02em}
.meta b{color:#c9d1d9;font-weight:600}
h2{font-size:13px;text-transform:uppercase;letter-spacing:.14em;color:#8b949e;
font-weight:600;margin:0 0 14px;padding:0 0 8px;border-bottom:1px solid #21262d}
h3{font-size:15px;margin:0 0 6px;color:#f0f6fc;font-weight:600}
p{margin:0 0 12px;max-width:660px}
.sec p{max-width:660px}
.sec pre+p{max-width:660px}
.sec{padding:34px 0;border-bottom:1px solid #161b22}
.col{float:left;width:300px;margin:0 20px 22px 0}
.col-last{margin-right:0}
.clear{clear:both;height:0;overflow:hidden}
ul.feat{margin:0;padding:0 0 0 16px}
ul.feat li{margin:0 0 7px;color:#a8b3c1}
ul.feat li b{color:#e6edf3;font-weight:600}
table.grid{width:100%;border-collapse:collapse;margin:0 0 6px}
table.grid th{text-align:left;font-size:11.5px;text-transform:uppercase;letter-spacing:.1em;
color:#6b7787;font-weight:600;padding:0 10px 8px 0;border-bottom:1px solid #21262d}
table.grid td{padding:8px 10px 8px 0;border-bottom:1px solid #161b22;vertical-align:top;font-size:14px}
table.grid td.k{color:#7ee2b8;font-family:"SFMono-Regular",Consolas,"Liberation Mono",monospace;font-size:13px;white-space:nowrap}
table.grid td.d{color:#a8b3c1}
pre{background:#0a0e14;border:1px solid #21262d;padding:16px;overflow:auto;
font:12.5px/1.5 "SFMono-Regular",Consolas,"Liberation Mono",monospace;color:#9fb0c4;margin:0 0 14px}
pre b{color:#e6edf3;font-weight:600}
code{font-family:"SFMono-Regular",Consolas,"Liberation Mono",monospace;font-size:13px;
background:#161b22;padding:1px 5px;color:#7ee2b8}
.note{background:#161b22;border-left:3px solid #d29922;padding:12px 14px;margin:0 0 14px;font-size:13.5px;color:#a8b3c1}
.foot{padding:26px 0 40px;color:#6b7787;font-size:12.5px}
.foot p{margin:0 0 6px}
.badge{display:inline-block;border:1px solid #30363d;padding:3px 9px;margin:0 6px 6px 0;
font-size:12px;color:#a8b3c1;letter-spacing:.03em}
</style>
</head>
<body>
<div class="masthead">
<div class="wrap">
<h1>junc<span>tion</span></h1>
<p class="tag">A policy router for OpenAI-compatible model endpoints. It sits in front of
N servers and decides <em>per request</em> which one answers — and what happens when none of
them wants to.</p>
<p class="meta">
<span class="badge">C99</span><span class="badge">POSIX</span>
<span class="badge">no runtime dependencies</span><span class="badge">single text config</span>
<span class="badge">~5,200 lines of C</span><span class="badge">94 tests</span>
</p>
</div>
</div>
<div class="wrap">
<div class="sec">
<h2>What it is</h2>
<p>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 <code>/v1/chat/completions</code> and should keep doing so.</p>
<p>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 <code>/status</code> exactly what it did.</p>
<p>The rule language is deliberately close to <code>pf.conf</code>: first match wins,
unknowns are a hard error with a line number, and there is no silent fallback to
&quot;somewhere&quot;. A request that matches no rule gets <code>503 no_matching_rule</code>,
because a gap in the configuration is not a routing decision.</p>
</div>
<div class="sec">
<h2>Features</h2>
<div class="col">
<h3>Routing</h3>
<ul class="feat">
<li><b>Per-request rules</b>, first match wins — model glob, path glob, declared
output budget, estimated prompt size, vision/text, endpoint health</li>
<li><b>Fallback chains</b>: <code>pass a, b, c</code> — targets tried in order</li>
<li><b>Named pools</b>, reusable and nestable: <code>pool lokal box3, box6</code></li>
<li><b>Explicit refusal</b>: <code>block</code> answers 403 instead of rerouting</li>
<li><b>Model rewrite per target</b>: <code>as &quot;local-name&quot;</code></li>
<li><b>Skip reasons named</b> in the 503 body and in <code>/status</code></li>
</ul>
</div>
<div class="col">
<h3>Load and cost</h3>
<ul class="feat">
<li><b>Four selection modes</b>: first, round-robin, least-usage, cost</li>
<li><b>Weights</b> per endpoint, honoured by round-robin and by the cost score</li>
<li><b>Balance mode per rule</b>, overriding the global one</li>
<li><b>Budgets</b> soft/hard in percent, with throttle or skip</li>
<li><b>Usage from outside</b>: a command prints a number, junction polls it</li>
<li><b>Off-peak window</b> halves the price of a target inside it</li>
</ul>
</div>
<div class="col col-last">
<h3>Failure</h3>
<ul class="feat">
<li><b>Two timeouts</b>: total, and silence — the latter emits a keep-alive
comment so a thinking model is not killed</li>
<li><b>Per-endpoint connect timeout</b>, separate from the global one</li>
<li><b>Cooldown</b> after a failed attempt, <b>offline hold</b> after a refused
connection — no retry storm</li>
<li><b>Queue instead of reject</b>: bounded wait with a position notice</li>
<li><b>Hooks</b> that decide whether a target is usable, with retry and backoff</li>
<li><b>Wake-on-LAN</b> once, before the hooks are retried</li>
</ul>
</div>
<div class="clear"></div>
<div class="col">
<h3>Protocol</h3>
<ul class="feat">
<li><b>Streaming preserved</b> byte for byte, including chunked framing</li>
<li><b>Chunked request bodies</b> decoded, so upstreams see a length</li>
<li><b>opencode bridge</b>: session-based API translated to OpenAI in both directions</li>
<li><b>Header injection</b> per endpoint, plus X-Forwarded-For/Proto</li>
<li><b>TLS both ways</b>, with a private CA per endpoint</li>
</ul>
</div>
<div class="col">
<h3>Memory and context</h3>
<ul class="feat">
<li><b>Tool-output compression</b>: deterministic, no model call, per endpoint —
measured 47,088 &rarr; 2,040 bytes on a 900-line log</li>
<li><b>Original bytes otherwise</b>: compression splices spans, it never
re-serialises the body</li>
<li><b>Never touches</b> system, user or assistant messages, nor the last N</li>
<li><b>Bounded everything</b>: body size, cache bytes, inflight count</li>
</ul>
</div>
<div class="col col-last">
<h3>Operation</h3>
<ul class="feat">
<li><b>Virtual keys</b>: clients get their own key, restricted to model globs and
endpoint sets — the real upstream key never leaves the host</li>
<li><b>/status</b> as JSON: endpoints, counters, cache, queue, rules</li>
<li><b>Admin API</b>: pause, resume, flush cache</li>
<li><b>Response cache</b> in memory, LRU, respecting Cache-Control</li>
<li><b>Strict config parsing</b> with line numbers; <code>--check</code> without
starting</li>
</ul>
</div>
<div class="clear"></div>
</div>
<div class="sec">
<h2>Build</h2>
<pre>$ make
$ sudo make install # binary, systemd unit, example config
$ junction --config /etc/junction/junction.conf --check
$ junction --config /etc/junction/junction.conf</pre>
<p>OpenSSL is the only optional dependency, needed for TLS. Without it, junction builds as
plain HTTP. The flags are <code>-std=c99 -Wall -Wextra -Wpedantic -Wshadow -Wconversion</code>;
the tree builds clean under all of them.</p>
</div>
<div class="sec">
<h2>How a request is decided</h2>
<p>A client asks for <code>model: &quot;chat&quot;</code> with roughly 3,000 prompt tokens and
no declared output budget. Rules are read top to bottom:</p>
<pre>req path "/v1/models" check none pass cloud <b>no match</b> - different path
req for "*embed*" check none pass embed <b>no match</b> - different model
req vision pass workstation, cloud as "v" <b>no match</b> - no image
req ctx &lt;2000 pass workstation <b>no match</b> - prompt is larger
req ctx &lt;50000 pass ollama1, cloud <b>match</b> - 3,000 is below 50,000</pre>
<p>The matched rule lists two targets. junction asks the first; if its connection is
refused, that target is marked offline for <code>offline_hold_s</code> and the second one is
tried within the same request. Every response says which target answered:</p>
<pre>X-Junction-Endpoint: ollama1
X-Junction-Ms: 412
X-Junction-Cache: off</pre>
</div>
<div class="sec">
<h2>Full reference configuration</h2>
<p>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.</p>
<pre># ============================================================================
# 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 "&lt;modell-glob&gt;" [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 &lt;modell-glob&gt;] [path &lt;glob&gt;] [need &gt;N | &lt;N | N]
# [check hooks|none] [retry &lt;s&gt;]
# ( pass &lt;ziel&gt;[,&lt;ziel&gt;...] [as &lt;modell&gt;] | 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. &gt;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 &lt;2000 pass workstation
req ctx &lt;50000 pass ollama1, cloud
req ctx &gt;50000 pass cloud
# Große Budgets kann der lokale Rechner nicht halten — also gar nicht erst hin.
req need &gt;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/&lt;name&gt; dort nicht mehr routen
# POST /admin/resume/&lt;name&gt; 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.
</pre>
</div>
<div class="sec">
<h2>Known limits</h2>
<div class="note">Named on purpose. A router that hides its edges gets trusted further
than it should.</div>
<table class="grid">
<tr><th style="width:34%">Limit</th><th>What it means in practice</th></tr>
<tr><td class="k">one off-peak window</td>
<td class="d">A target can be cheaper inside a single daily time range. &quot;All
weekend&quot; is not expressible.</td></tr>
<tr><td class="k">flat chains</td>
<td class="d">A rule lists targets; a target cannot call another rule. Branching by
subject matter needs more rules, not nested ones.</td></tr>
<tr><td class="k">one process</td>
<td class="d">State — counters, cooldowns, cache — lives in memory. Restarting the
router resets it, and there is no clustering.</td></tr>
<tr><td class="k">estimated context</td>
<td class="d">Prompt size is estimated from characters per token, a number you
supply. It is an assumption, not a tokenizer.</td></tr>
<tr><td class="k">no auth beyond keys</td>
<td class="d">Virtual keys separate clients and limit what they may ask for. There is
no user database, no quota accounting per person.</td></tr>
<tr><td class="k">compression is not memory</td>
<td class="d">It 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.</td></tr>
</table>
</div>
<div class="foot">
<p><b>junction</b> &middot; version 0.1 &middot; C99 and POSIX &middot; built and tested on
Debian with gcc and clang</p>
<p>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.</p>
</div>
</div>
</body>
</html>
+6
View File
@@ -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
#
+8
View File
@@ -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;
+2
View File
@@ -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 */
+36
View File
@@ -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;
}
+65
View File
@@ -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" <<CFG
listen 127.0.0.1:$XPORT
cache_ttl 300
cache_entries 50
cache_bytes 2000000
endpoint a { base http://127.0.0.1:$P_GATED/v1 }
req for "*" pass a
CFG
./junction --config "$TMP/cache.conf" > "$TMP/cache.log" 2>&1 &
PIDS+=($!)
sleep 0.8
ask() { # ask <body> -> 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
+7 -2
View File
@@ -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"