diff --git a/src/junction.c b/src/junction.c index d854d02..a69463a 100644 --- a/src/junction.c +++ b/src/junction.c @@ -3360,6 +3360,58 @@ static int forward_with_retry(j_conn *client, j_endpoint *ep, const j_req *rq, return rc; } +/* Sum the usage of all calls a review needed: the client sees the last answer, + * but paid for the original plus every round. Cost uses the same price table and + * billed model name forward_step uses; an unknown price stays unknown instead of + * turning into zero. */ +typedef struct { + long in, out, cached; + double cost; + int seen; + int cost_known; +} review_usage; + +static void review_usage_add(review_usage *u, const char *body, const char *model, + int offpeak) +{ + if (!body) return; + long in = 0, out = 0, cached = 0; + if (!usage_from_body(body, strlen(body), &in, &out, &cached)) return; + u->in += in; + u->out += out; + u->cached += cached; + u->seen = 1; + double cost = j_price_cost(model, in, cached, out, offpeak); + if (cost < 0) u->cost_known = 0; + else u->cost += cost; +} + +/* Add a top-level "junction": member to a completed JSON object. The SSE + * path already carries the same object in its final chunk; non-streaming answers + * get it inserted here, because the provider's own usage only covers the last + * call. Returns a malloc'ed copy or NULL when the body is not a JSON object. */ +static char *json_with_meta(const char *body, const char *key, const char *json) +{ + if (!body) return NULL; + const char *end = body + strlen(body); + const char *close = end; + while (close > body && isspace((unsigned char)close[-1])) close--; + if (close <= body || close[-1] != '}') return NULL; + close--; + size_t pre = (size_t)(close - body); + size_t klen = strlen(key), vlen = strlen(json); + size_t cap = pre + klen + vlen + strlen(close + 1) + 8; + char *out = malloc(cap); + if (!out) return NULL; + int n = snprintf(out, cap, "%.*s,\"%s\":%s}%s", (int)pre, body, key, json, + close + 1); + if (n < 0 || (size_t)n >= cap) { + free(out); + return NULL; + } + return out; +} + /* Is the monthly budget of this vkey still open? handle_client checks it once when * the request arrives, but every review round costs another provider call. A hard * budget must stop the rounds, not be overdrawn by up to review_count calls. An @@ -3391,6 +3443,8 @@ static int review_serve(j_conn *client, j_endpoint *ep, const j_req *rq, { char *ns = NULL; size_t ns_len = 0; + review_usage rev = { 0, 0, 0, 0.0, 0, 1 }; + const char *billed = as_model[0] ? as_model : rq_model; t_review_count = review_count; t_review_done = 0; t_review_skipped[0] = '\0'; @@ -3414,6 +3468,7 @@ static int review_serve(j_conn *client, j_endpoint *ep, const j_req *rq, j_buf_free(&cap); return rc; } + review_usage_add(&rev, cap.data, billed, ep->offpeak_active); char *answer = NULL; int tools = 0; @@ -3466,6 +3521,7 @@ static int review_serve(j_conn *client, j_endpoint *ep, const j_req *rq, jlog("review", "round=%d endpoint=%s ok=0 error=%s", round, ep->name, err); break; } + review_usage_add(&rev, cap.data, billed, ep->offpeak_active); char *next = NULL; int next_tools = 0; const char *next_why = NULL; @@ -3498,14 +3554,26 @@ static int review_serve(j_conn *client, j_endpoint *ep, const j_req *rq, json_escape(t_review_model, rm, sizeof rm); json_escape(t_review_skipped, rs, sizeof rs); json_escape(ep->name, en, sizeof en); + char usage_json[256] = ""; + if (rev.seen) { + char cost_json[64] = ""; + if (rev.cost_known) + snprintf(cost_json, sizeof cost_json, ",\"cost_usd\":%.6f", rev.cost); + else + snprintf(cost_json, sizeof cost_json, ",\"cost_unknown\":1"); + snprintf(usage_json, sizeof usage_json, + ",\"usage\":{\"prompt_tokens\":%ld,\"completion_tokens\":%ld," + "\"cached_tokens\":%ld,\"total_tokens\":%ld}%s", + rev.in, rev.out, rev.cached, rev.in + rev.out, cost_json); + } char meta[2048]; snprintf(meta, sizeof meta, "{\"review_rounds\":%d,\"review_model\":\"%s\"," "\"review_skipped\":\"%s\",\"judge\":\"%s\"," "\"judge_model\":\"%s\",\"judge_step\":%d,\"judge_every\":%d," - "\"judge_served\":%d,\"endpoint\":\"%s\"}", + "\"judge_served\":%d,\"endpoint\":\"%s\"%s}", t_review_done, rm, rs, jt, jm, t_judge_step, t_judge_every, - t_judge_served, en); + t_judge_served, en, usage_json); if (streaming) { char *frames = NULL; @@ -3520,8 +3588,11 @@ static int review_serve(j_conn *client, j_endpoint *ep, const j_req *rq, } else { j_hdrs h; j_hdrs_init(&h); - char cl[32], ms[32]; - snprintf(cl, sizeof cl, "%zu", strlen(last_json)); + char cl[32], ms[32], v[32]; + char *with_meta = json_with_meta(last_json, "junction", meta); + const char *payload = with_meta ? with_meta : last_json; + size_t payload_len = strlen(payload); + snprintf(cl, sizeof cl, "%zu", payload_len); snprintf(ms, sizeof ms, "%ld", (long)((now_s() - started) * 1000.0)); j_hdrs_set(&h, "Content-Type", "application/json"); j_hdrs_set(&h, "Content-Length", cl); @@ -3529,12 +3600,23 @@ static int review_serve(j_conn *client, j_endpoint *ep, const j_req *rq, j_hdrs_set(&h, "X-Junction-Endpoint", ep->name); j_hdrs_set(&h, "X-Junction-Ms", ms); j_hdrs_set(&h, "X-Junction-Cache", "off"); + if (rev.seen) { + snprintf(v, sizeof v, "%ld", rev.in); + j_hdrs_set(&h, "X-Junction-Review-Tokens-In", v); + snprintf(v, sizeof v, "%ld", rev.out); + j_hdrs_set(&h, "X-Junction-Review-Tokens-Out", v); + if (rev.cost_known) { + snprintf(v, sizeof v, "%.6f", rev.cost); + j_hdrs_set(&h, "X-Junction-Review-Cost-Usd", v); + } + } add_route_meta_headers(&h); - int hrc = send_head(client, 200, "OK", &h, (long)strlen(last_json), + int hrc = send_head(client, 200, "OK", &h, (long)payload_len, err, errlen); if (hrc == 0) - hrc = j_conn_write(client, last_json, strlen(last_json), + hrc = j_conn_write(client, payload, payload_len, err, errlen) < 0 ? -1 : 0; + free(with_meta); rc = hrc == 0 ? 0 : -2; } diff --git a/tests/review.sh b/tests/review.sh index 68e5263..bc025fb 100644 --- a/tests/review.sh +++ b/tests/review.sh @@ -17,6 +17,8 @@ RA=$((PORT+286)) RAJ=$((PORT+287)) RS=$((PORT+288)) RSJ=$((PORT+289)) +RU=$((PORT+290)) +RUJ=$((PORT+291)) STUB_STATE="$TMP/review.state" STUB_ANSWERS="first answer|second answer|third answer" \ tests/stub $RW "REVIEWER" > "$TMP/review_stub.log" 2>&1 & @@ -33,11 +35,15 @@ PIDS+=($!) STUB_STATE="$TMP/review_so.state" STUB_ANSWERS="so answer|so reviewed" \ STUB_REJECT_STREAM_OPTIONS=1 tests/stub $RS "STRICT" > "$TMP/review_so_stub.log" 2>&1 & PIDS+=($!) +STUB_STATE="$TMP/review_usage.state" STUB_ANSWERS="usage one|usage two|usage three" \ + STUB_USAGE=1 tests/stub $RU "USAGE" > "$TMP/review_usage_stub.log" 2>&1 & +PIDS+=($!) wait_port $RW 10 || bad "the review stub did not come up" wait_port $RT 10 || bad "the tool-review stub did not come up" wait_port $RB 10 || bad "the 400 stub did not come up" wait_port $RA 10 || bad "the content-array stub did not come up" wait_port $RS 10 || bad "the strict stub did not come up" +wait_port $RU 10 || bad "the usage stub did not come up" cat > "$TMP/review.conf" < "$TMP/review_usage_prices.conf" <<'CFG' +# test/review in cached out +test/review 1.0 0.0 2.0 +CFG +cat > "$TMP/review_usage.conf" < "$TMP/review_usage.log" 2>&1 & +PIDS+=($!) +wait_port "$RUJ" 10 || bad "the usage-review instance did not come up" +UOUT=$(curl -s -D "$TMP/review_usage_h.txt" -m 20 -X POST -H 'Content-Type: application/json' \ + -d '{"model":"vm-usage","messages":[{"role":"user","content":"hi"}],"max_tokens":8}' \ + "http://127.0.0.1:$RUJ/v1/chat/completions") +contains "$UOUT" "usage three" "the usage test gets the last reviewed answer" +contains "$UOUT" '"junction":{"review_rounds":2' "the final JSON carries the junction object" +contains "$UOUT" '"usage":{"prompt_tokens":3600,"completion_tokens":900,"cached_tokens":0,"total_tokens":4500}' \ + "the junction object sums the usage of all three calls" +contains "$UOUT" '"cost_usd":0.005400' "the junction object sums the cost of all three calls" +UH=$(tr -d '\r' < "$TMP/review_usage_h.txt") +contains "$UH" "X-Junction-Review-Tokens-In: 3600" "the header carries the summed input tokens" +contains "$UH" "X-Junction-Review-Tokens-Out: 900" "the header carries the summed output tokens" +contains "$UH" "X-Junction-Review-Cost-Usd: 0.005400" "the header carries the summed cost" +contains "$UH" "X-Junction-Ms: " "the request time covers the whole review" + +# Streaming: derselbe Block steckt im finalen SSE-Chunk, nicht nur im JSON-Pfad. +USSE=$(curl -s -N -D /dev/null -m 20 -X POST -H 'Content-Type: application/json' \ + -d '{"model":"vm-usage","stream":true,"messages":[{"role":"user","content":"hi"}],"max_tokens":8}' \ + "http://127.0.0.1:$RUJ/v1/chat/completions") +contains "$USSE" '"usage":{"prompt_tokens":3600,"completion_tokens":900,"cached_tokens":0,"total_tokens":4500}' \ + "the final stream chunk sums the usage of all three calls" +contains "$USSE" '"cost_usd":0.005400' "the final stream chunk sums the cost" +contains "$USSE" '"review_rounds":2' "the final stream chunk names the rounds" + # Konfigurationsfehler müssen laut sein. printf 'endpoint e {\n base http://127.0.0.1:9995/v1\n}\nreq for "vm" review 5 pass e\n' \ > "$TMP/review_bad_count.conf" diff --git a/tests/run.sh b/tests/run.sh index 00fc3e2..b6055ae 100755 --- a/tests/run.sh +++ b/tests/run.sh @@ -71,7 +71,7 @@ log_has() { # answer requests with somebody else's config), so fail loudly and early. # 8157 gehört auf dieser Maschine dem Hermes-Gateway — der Port wird von keinem # Test benutzt, also darf er die Suite nicht aufhalten. -for port in 8361 8362 8363 8364 8357 8358 8359 8360 8355 8356 8347 8348 8349 8350 8351 8352 8353 8354 8345 8346 8335 8336 8337 8338 8339 8340 8341 8342 8375 8376 8377 8378 8385 8386 8387 8388 8389 8395 8396 8397 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8150 8151 8152 8153 8154 8155 8156 8158 8159 8160 8161 8162 8163 8164 8165 8166 8365 8366 8405 8406 8407 8408 8409 8410 8411 8412 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8167 8168 8170 8171 8172 8173 8175 8180 8181 8194 8176 8177 8185 8186 8187 8188 8189 8190 8208 9443 9990 9991 9992 9993 9994 9995 9996; do +for port in 8361 8362 8363 8364 8357 8358 8359 8360 8355 8356 8347 8348 8349 8350 8351 8352 8353 8354 8345 8346 8335 8336 8337 8338 8339 8340 8341 8342 8375 8376 8377 8378 8385 8386 8387 8388 8389 8395 8396 8397 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8150 8151 8152 8153 8154 8155 8156 8158 8159 8160 8161 8162 8163 8164 8165 8166 8365 8366 8405 8406 8407 8408 8409 8410 8411 8412 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8167 8168 8170 8171 8172 8173 8175 8180 8181 8194 8176 8177 8185 8186 8187 8188 8189 8190 8208 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/^/ /' diff --git a/tests/stub.c b/tests/stub.c index 1dc60fc..d15cf43 100644 --- a/tests/stub.c +++ b/tests/stub.c @@ -469,7 +469,14 @@ int main(int argc, char **argv) } bo += (size_t)wrote; } - if (bo < sizeof b - 2) snprintf(b + bo, sizeof b - bo, "]}"); + const char *usage_env = getenv("STUB_USAGE"); + const char *usage = (usage_env && *usage_env) + ? ",\"usage\":{\"prompt_tokens\":1200," + "\"completion_tokens\":300," + "\"prompt_tokens_details\":{\"cached_tokens\":0}}" + : ""; + if (bo < sizeof b - 2) + snprintf(b + bo, sizeof b - bo, "]%s}", usage); } snprintf(body, sizeof body, "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n"