Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
487 changes: 473 additions & 14 deletions config/litellm/cost_callback.py

Large diffs are not rendered by default.

53 changes: 51 additions & 2 deletions docs/guides/per-agent-models.md
Original file line number Diff line number Diff line change
Expand Up @@ -788,8 +788,57 @@ data:
> first, so a `<N chars omitted>` on a *small* field means the block was
> over budget rather than that field being oversized on its own.
>
> Prompt-bearing fields (`messages`, `tools`, `tool_choice`) are excluded by
> allowlist: the cost stream is not a transcript sink.
> Prompt-bearing fields (`messages`, and the `tools` schemas themselves) are
> excluded by allowlist: the cost stream is not a transcript sink. The line
> the allowlist draws is payload vs selector, not "anything tool-shaped", so
> two small tool-related values *are* recorded (#3692): `tools_count`, the
> arity of the `tools` array without any of its schemas — tool presence is
> the strongest observed lever on whether these models reason, so `0` vs `14`
> is the whole signal — and `tool_choice`, the scalar mode selector
> (`"auto"` / `"none"` / `"required"`, or a small object naming one tool),
> which separates "no tools were offered" from "tools were offered but
> forbidden this turn". An **absent** `tools` key emits no `tools_count` at
> all rather than `0`: "we could not tell" is not "none offered".

> **Which build served the turn, and did the prompt stop growing?** Two more
> fields land next to `request_params` on every `cost_callback` line (#3692).
>
> - **`endpoint`** — `{provider, name, quantization, context_length}`.
> `provider` is per-call, read off the response body ("Poolside",
> "Alibaba"); the other three come from OpenRouter's per-model
> `/models/{slug}/endpoints` metadata, fetched off the request path (a
> daemon thread, cached for an hour) because this code runs in the proxy's
> logging hook and a blocking lookup there would stall the event loop for
> every call. The metadata row is selected by **matching the call's
> provider**, never by position: the `extra_body.provider` pin routes the
> *completion* and has no effect on that public metadata route, whose index
> 0 is frequently a provider you never talked to (`z-ai/glm-4.6` lists
> Venice first at `fp4`/198000 while Z.AI serves `fp8`/202752). A provider
> with no published row reads `null` rather than borrowing a neighbour's
> build id. On the streaming path — all agent traffic — the response's
> provider usually does not survive litellm's chunk reassembly, so
> `provider` reads `null` and the build fields resolve only for a model
> publishing exactly one endpoint, where there is nothing to disambiguate.
> Knobs: `LITELLM_OPENROUTER_ENDPOINT_FETCH=0` disables the lookup,
> `LITELLM_OPENROUTER_ENDPOINT_TTL` (default 3600s) and
> `LITELLM_OPENROUTER_ENDPOINT_TIMEOUT` (default 5s). A failed lookup is
> cached briefly and **logged** (`cost_callback build attribution [slug]:
> ...`, first occurrence at warning), so persistently-null fields are
> diagnosable rather than indistinguishable from "the first fetch hasn't
> landed yet".
> - **`call.prompt_tokens_delta`** — how much the prompt grew since this
> session's previous call *on the same model*. A repetition-trapped agent
> re-sends its whole context plus one near-identical turn, so this lands on
> a small, near-constant value call after call: the livelock signature,
> readable on one line instead of by differencing a whole session's lines
> against each other (which is impossible anyway once the ~48h log
> retention has rolled). `null` on the first call seen for a
> `(session, model)` pair — no predecessor to difference against is not a
> delta of `0` — and negative across a compaction, which is what
> distinguishes a reseed from a flat stall. Keyed per model because the
> paired `<name>[1m]` alias below puts short startup probes on the same
> session id, and differencing prompt length across models is not a
> meaningful quantity the way summing cost across them is.

The `request_params` field on a stock (nothing pinned) OpenRouter route:

Expand Down
54 changes: 53 additions & 1 deletion orchestrator/routes/session_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,33 @@ def _make_error(message: str, status_code: int = 400) -> tuple[Response, int]:
return jsonify({"success": False, "message": message}), status_code


# Cap for the advisory provenance strings. The only one today is an ISO-8601
# timestamp (~24 chars); this is generous room for that, and a bound on a
# client-supplied value that otherwise reaches the structured log stream
# unmeasured.
_MAX_PROVENANCE_STR = 64


def _advisory_str(block: dict, key: str) -> str | None:
"""A bounded string off the advisory block, or ``None``.

The provenance block never gates the push, so a wrong-typed member is
dropped rather than rejected — but "dropped" has to mean it does not reach
the log line either, which is what a bare ``block.get(key)`` would let it
do."""
value = block.get(key)
return value[:_MAX_PROVENANCE_STR] if isinstance(value, str) else None


def _advisory_int(block: dict, key: str) -> int | None:
"""An integer off the advisory block, or ``None``.

``bool`` is excluded for the same reason it is everywhere else in egg:
``isinstance(True, int)`` is True, and ``entries: true`` is not a count."""
value = block.get(key)
return value if isinstance(value, int) and not isinstance(value, bool) else None


@session_state_bp.route("/<pipeline_id>/session-state", methods=["POST"])
def push_session_state(pipeline_id: str) -> tuple[Response, int]:
"""Persist (overwrite) a role's warm-resume record.
Expand All @@ -68,7 +95,13 @@ def push_session_state(pipeline_id: str) -> tuple[Response, int]:
"slice_id": "slice-3", # optional; null/absent → pipeline-level
"session_id": "uuid",
"window_occupancy": 123456, # optional
"transcript": "<jsonl text>" # optional (pointer-only when absent)
"transcript": "<jsonl text>", # optional (pointer-only when absent)
"transcript_provenance": { # optional; logged, not stored
"tail_timestamp": "2026-07-29T04:21:34.335Z",
"entries": 3472,
"assistant_turns": 1837,
"bytes": 4788605
}
}
"""
body = request.get_json(silent=True)
Expand All @@ -95,6 +128,21 @@ def push_session_state(pipeline_id: str) -> tuple[Response, int]:
if transcript is not None and not isinstance(transcript, str):
return _make_error("transcript must be a string or null")

# Which transcript this push carried (#3692). The push is a single
# on-exit snapshot, so a record can be a faithful capture of an early
# moment while the session goes on working for another hour — the blob is
# well-formed JSONL either way, which is what makes a stale record and a
# current one indistinguishable by inspection. Logging the tail timestamp
# against the push time turns that gap into a readable number. Advisory
# and client-supplied: it describes the payload, it does not gate it, so a
# malformed block — or a malformed member of a well-formed block — is
# dropped rather than failing the push. Each member is type-checked on the
# way out, matching the handling of every other field on this route: these
# are the only client-supplied values here that reach a log line, and
# "advisory" is a reason not to reject the push, not a reason to forward
# arbitrary JSON into the structured log stream.
prov = body.get("transcript_provenance")
prov = prov if isinstance(prov, dict) else {}
stored = get_session_state_store().put(
pipeline_id,
slice_id,
Expand All @@ -112,6 +160,10 @@ def push_session_state(pipeline_id: str) -> tuple[Response, int]:
role=role,
stored=stored,
has_transcript=transcript is not None,
transcript_tail_timestamp=_advisory_str(prov, "tail_timestamp"),
transcript_entries=_advisory_int(prov, "entries"),
transcript_assistant_turns=_advisory_int(prov, "assistant_turns"),
transcript_bytes=_advisory_int(prov, "bytes"),
)
# ``stored=False`` is not an error: an empty session_id or oversized transcript
# simply degrades to a cold reseed next event. Report it so the caller can log.
Expand Down
65 changes: 65 additions & 0 deletions orchestrator/tests/test_session_state_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,71 @@ def test_pull_requires_role(self, client):
assert r.status_code == 400


class TestTranscriptProvenance:
"""The advisory block describing which transcript a push carried (#3692).

Advisory means it never gates the push. It does NOT mean the values reach
the structured log line unchecked — every other field on this route is
type-checked, and these are the only client-supplied ones that end up in a
log stream."""

def test_a_well_formed_block_is_accepted(self, client):
r = client.post(
_URL,
json={
"role": "coder",
"session_id": "a",
"transcript": '{"l": 1}\n',
"transcript_provenance": {
"tail_timestamp": "2026-07-29T04:21:34.335Z",
"entries": 3472,
"assistant_turns": 1837,
"bytes": 4788605,
},
},
)
assert r.status_code == 200
assert r.get_json()["stored"] is True

def test_a_malformed_block_does_not_fail_the_push(self, client):
# The transcript is the thing worth keeping; a bad description of it
# must not be able to cost us the record.
r = client.post(
_URL,
json={
"role": "coder",
"session_id": "a",
"transcript": '{"l": 1}\n',
"transcript_provenance": "not an object",
},
)
assert r.status_code == 200
assert r.get_json()["stored"] is True

def test_wrong_typed_members_are_dropped_not_forwarded(self):
from routes.session_state import _advisory_int, _advisory_str

block = {
"tail_timestamp": {"nested": "object"},
"entries": "3472",
"assistant_turns": True,
"bytes": 12,
}
assert _advisory_str(block, "tail_timestamp") is None
assert _advisory_int(block, "entries") is None
# `isinstance(True, int)` is True, and `assistant_turns: true` is not
# a count.
assert _advisory_int(block, "assistant_turns") is None
assert _advisory_int(block, "bytes") == 12
assert _advisory_str({}, "tail_timestamp") is None

def test_an_unbounded_string_is_capped(self):
from routes.session_state import _MAX_PROVENANCE_STR, _advisory_str

value = _advisory_str({"tail_timestamp": "x" * 10_000}, "tail_timestamp")
assert value is not None and len(value) == _MAX_PROVENANCE_STR


class TestEvict:
"""#3537 DELETE - operator-facing eviction of a poisoned warm-resume record."""

Expand Down
6 changes: 5 additions & 1 deletion sandbox/egg_lib/cli_session_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,9 +140,13 @@ def cmd_session_state_push(args: argparse.Namespace) -> int:
file=sys.stderr,
)
return 0
prov = body.get("transcript_provenance") or {}
print(
f"session-state push: persisted {role} slice={slice_id or 'none'} "
f"(transcript={'yes' if body.get('transcript') else 'no'})",
f"(transcript={'yes' if body.get('transcript') else 'no'} "
f"tail={prov.get('tail_timestamp') or 'none'} "
f"entries={prov.get('entries', 0)} turns={prov.get('assistant_turns', 0)} "
f"bytes={prov.get('bytes', 0)})",
file=sys.stderr,
)
return 0
Expand Down
46 changes: 46 additions & 0 deletions sandbox/egg_lib/session_state_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"resolve_config_dir",
"resolve_repo_path",
"transcript_path",
"transcript_provenance",
"write_pulled_state",
]

Expand Down Expand Up @@ -144,6 +145,50 @@ def write_pulled_state(
return False


def transcript_provenance(transcript: str | None) -> dict[str, Any]:
"""Describe *which* transcript this push is carrying, so a stored record can
be checked for staleness without re-deriving it from the blob.

The push is a single on-exit snapshot: a record whose content stopped at
04:21 while the session went on calling until 05:17 is not corrupt, it is
simply the last snapshot anyone took. Nothing on the record said so, which
is what made that gap invisible — the blob is well-formed JSONL either way,
so "complete" and "stale" are indistinguishable by inspection. Recording the
tail timestamp and the entry counts makes the staleness a readable field.

``tail_timestamp`` is the last entry that carries one (entries such as the
trailing ``mode`` marker do not). All keys are ``None``/absent-safe: a
missing or unparseable transcript yields zeros and a null tail rather than
raising into the push, which is best-effort by contract.
"""
if not transcript:
return {"tail_timestamp": None, "entries": 0, "assistant_turns": 0, "bytes": 0}
tail: str | None = None
entries = 0
assistant_turns = 0
for line in transcript.split("\n"):
if not line.strip():
continue
entries += 1
try:
obj = json.loads(line)
except ValueError:
continue
if not isinstance(obj, dict):
continue
if obj.get("type") == "assistant":
assistant_turns += 1
stamp = obj.get("timestamp")
if isinstance(stamp, str) and stamp:
tail = stamp
return {
"tail_timestamp": tail,
"entries": entries,
"assistant_turns": assistant_turns,
"bytes": len(transcript.encode("utf-8")),
}


def read_state_for_push(
*,
repo_path: str,
Expand Down Expand Up @@ -182,4 +227,5 @@ def read_state_for_push(
)
except OSError:
body["transcript"] = None
body["transcript_provenance"] = transcript_provenance(body["transcript"])
return body
57 changes: 56 additions & 1 deletion sandbox/tests/test_session_state_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,12 @@ def test_reads_pointer_and_transcript(self, tmp_path):
"session_id": "sid-1",
"window_occupancy": 7,
"transcript": '{"l":1}\n',
"transcript_provenance": {
"tail_timestamp": None,
"entries": 1,
"assistant_turns": 0,
"bytes": 8,
},
}

def test_missing_transcript_yields_pointer_only_body(self, tmp_path):
Expand Down Expand Up @@ -188,6 +194,51 @@ def test_pointer_without_session_id_returns_none(self, tmp_path):
)


class TestTranscriptProvenance:
"""What a push is carrying, recorded so a stored record's staleness is a
readable field rather than something you have to reconstruct from a
separate ledger (#3692)."""

def test_tail_timestamp_is_the_last_entry_that_has_one(self):
# The real tail is often a trailing marker with no timestamp (a
# ``mode`` line), so "last entry" and "last timestamp" differ.
transcript = (
'{"type":"assistant","timestamp":"2026-07-29T04:20:00.000Z"}\n'
'{"type":"user","timestamp":"2026-07-29T04:21:34.335Z"}\n'
'{"type":"mode","mode":"normal"}\n'
)
prov = sync.transcript_provenance(transcript)
assert prov["tail_timestamp"] == "2026-07-29T04:21:34.335Z"
assert prov["entries"] == 3
assert prov["assistant_turns"] == 1
assert prov["bytes"] == len(transcript.encode("utf-8"))

def test_absent_transcript_is_zeroed_not_raised(self):
for empty in (None, ""):
assert sync.transcript_provenance(empty) == {
"tail_timestamp": None,
"entries": 0,
"assistant_turns": 0,
"bytes": 0,
}

def test_unparseable_lines_are_counted_but_do_not_abort_the_scan(self):
# Best-effort by contract: a torn line must not cost us the tail.
transcript = (
'{"type":"assistant","timestamp":"2026-07-29T01:00:00.000Z"}\n'
"{not json at all\n"
'{"type":"assistant","timestamp":"2026-07-29T02:00:00.000Z"}\n'
)
prov = sync.transcript_provenance(transcript)
assert prov["tail_timestamp"] == "2026-07-29T02:00:00.000Z"
assert prov["entries"] == 3
assert prov["assistant_turns"] == 2

def test_bytes_counts_utf8_not_characters(self):
prov = sync.transcript_provenance('{"t":"éé"}\n')
assert prov["bytes"] == len('{"t":"éé"}\n'.encode())


class TestRoundTrip:
def test_pull_then_push_is_stable(self, tmp_path):
"""A pulled record read back for push reproduces the same body."""
Expand All @@ -197,4 +248,8 @@ def test_pull_then_push_is_stable(self, tmp_path):
record = {"session_id": "sid-1", "window_occupancy": 42, "transcript": '{"l":1}\n'}
sync.write_pulled_state(record, repo_path=repo, config_dir=cfg, session_state_file=str(ssf))
body = sync.read_state_for_push(repo_path=repo, config_dir=cfg, session_state_file=str(ssf))
assert body == record
# ``transcript_provenance`` describes the payload rather than being part
# of it — it is logged at push time, never stored — so the round-tripped
# state is the body minus that descriptor.
assert {k: v for k, v in body.items() if k in record} == record
assert body["transcript_provenance"]["entries"] == 1
Loading
Loading