From 39e0057be80da2db7417534b82fcd7b9d5e4a1bd Mon Sep 17 00:00:00 2001 From: "bunny.fae.mom" Date: Mon, 16 Nov 2026 05:24:58 -0500 Subject: [PATCH] fix(token_count): keep an endpoint that has counted, and log failed counts A subscription's count endpoint is marked absent for a day on any refusal, since the credential may be refused the endpoint outright. That memo is keyed by the endpoint, so one request the provider refused for its own reasons switched counting off for every session on it, and the failure itself was silent: each request was then sized by estimate with nothing saying why. An endpoint that has answered a count is no longer marked absent by a later refusal. A failed count is logged once an hour per endpoint with the provider's words, and a provider encoder that raises while counting is logged by the loop. A unit test against a local endpoint pins both memo cases; no end-to-end route reaches a subscription's endpoint. Behaviour change: after a successful count, a refused count no longer stops counting on that endpoint for a day. --- src/albedo/harness/loop.gleam | 7 ++- src/albedo/harness/sdk/token_count.gleam | 54 ++++++++++++++-- test/harness/token_count_test.gleam | 80 ++++++++++++++++++++++++ 3 files changed, 136 insertions(+), 5 deletions(-) create mode 100644 test/harness/token_count_test.gleam diff --git a/src/albedo/harness/loop.gleam b/src/albedo/harness/loop.gleam index 1bbc3ca8c..ad19c4ef2 100644 --- a/src/albedo/harness/loop.gleam +++ b/src/albedo/harness/loop.gleam @@ -1,6 +1,7 @@ //// Model → tools → model. The session owns cancellation and durable commits. import albedo/harness/kernel/tool as cell_tool +import albedo/harness/sdk/log import albedo/harness/sdk/protect import albedo/harness/sdk/session_info @@ -1327,7 +1328,11 @@ fn sizing( request(state, prompt, match_entries(original_entries, inputs)) case protect.attempt(fn() { count(request) }) { Ok(Ok(tokens)) -> Some(tokens) - _ -> None + Ok(Error(_)) -> None + Error(crash) -> { + log.warning("token count raised: " <> crash) + None + } } } compaction.Sizing( diff --git a/src/albedo/harness/sdk/token_count.gleam b/src/albedo/harness/sdk/token_count.gleam index 49b650921..419a8e846 100644 --- a/src/albedo/harness/sdk/token_count.gleam +++ b/src/albedo/harness/sdk/token_count.gleam @@ -4,9 +4,11 @@ //// encodes its request and names where the answer is; this module sends it //// and reads the number. Nothing here estimates a count. +import albedo/harness/sdk/log import albedo/harness/sdk/memo import albedo/openai_api import albedo/openai_api/catalog +import albedo/openai_api/refusal import albedo/openai_api/stream_http import albedo/openai_api/types import gleam/dynamic/decode @@ -48,7 +50,8 @@ pub type Absence { /// request for its own reasons, and is asked again. NotFound /// Any refusal does, for a credential the endpoint is not documented to - /// take: it may refuse every request it gets and is not asked again. + /// take, until the endpoint has answered a count: one that has refuses a + /// request for its own reasons, as under `NotFound`. AnyRefusal } @@ -73,13 +76,19 @@ fn memo_key(endpoint: Endpoint) -> String { /// It goes out through the streaming transport, which alone may write the /// stored image payloads a request body refers to. pub fn ask(endpoint: Endpoint, body: Json) -> Result(Int, types.Error) { - case memo.get(missing(), memo_key(endpoint)) { + let key = memo_key(endpoint) + case memo.get(missing(), key) { Ok(True) -> Error(types.Unsupported("this route has no count endpoint")) _ -> { let refusal = fn(status, text) { case endpoint.absence, status { - NotFound, 404 | NotFound, 405 | AnyRefusal, _ -> - memo.put_for(missing(), memo_key(endpoint), True, absent) + NotFound, 404 | NotFound, 405 -> + memo.put_for(missing(), key, True, absent) + AnyRefusal, _ -> + case memo.get(served(), key) { + Ok(True) -> Nil + _ -> memo.put_for(missing(), key, True, absent) + } NotFound, _ -> Nil } endpoint.refusal(status, text) @@ -104,9 +113,46 @@ pub fn ask(endpoint: Endpoint, body: Json) -> Result(Int, types.Error) { )) }, ) + |> result.map(fn(count) { + memo.put_for(served(), key, True, absent) + count + }) + |> result.map_error(fn(error) { + report(endpoint, error) + error + }) } } } +/// Logs a failed count once an hour for its endpoint: the request is then +/// sized without it, so nothing else says why. An endpoint that turned out +/// absent is the expected answer of a route without one, and is not logged. +fn report(endpoint: Endpoint, error: types.Error) -> Nil { + case + memo.get(missing(), memo_key(endpoint)), + memo.get(reported(), endpoint.url) + { + Ok(True), _ | _, Ok(True) -> Nil + _, _ -> { + memo.put_for(reported(), endpoint.url, True, 3_600_000) + log.warning( + "token count at " + <> endpoint.url + <> " failed: " + <> refusal.describe(error), + ) + } + } +} + +fn served() -> memo.Memo(Bool) { + memo.new("token_count_served", decode.bool) +} + +fn reported() -> memo.Memo(Bool) { + memo.new("token_count_reported", decode.bool) +} + /// A count answer is a small object. const answer_limit = 65_536 diff --git a/test/harness/token_count_test.gleam b/test/harness/token_count_test.gleam new file mode 100644 index 000000000..13c531efa --- /dev/null +++ b/test/harness/token_count_test.gleam @@ -0,0 +1,80 @@ +//// A count endpoint that answers some requests and refuses others. Counting +//// is skipped for a day once an endpoint looks absent, so which refusal +//// marks it absent decides whether every later request is sized by +//// estimate; an end-to-end run cannot reach a subscription's endpoint. + +import albedo/anthropic_api/refusal +import albedo/harness/sdk/token_count +import albedo/openai_api/types +import gleam/bit_array +import gleam/bytes_tree +import gleam/erlang/process +import gleam/http/request +import gleam/http/response +import gleam/int +import gleam/json +import gleam/result +import gleam/string +import mist + +/// A local endpoint that refuses a body naming "refuse" and counts the rest. +fn serve() -> String { + let bound = process.new_subject() + let assert Ok(_) = + mist.new(fn(request: request.Request(mist.Connection)) { + let assert Ok(request) = mist.read_body(request, 1_000_000) + let body = bit_array.to_string(request.body) |> result.unwrap("") + case string.contains(body, "refuse") { + True -> + response.new(400) + |> response.set_body( + mist.Bytes(bytes_tree.from_string( + "{\"error\":{\"message\":\"bad request\"}}", + )), + ) + False -> + response.new(200) + |> response.set_body( + mist.Bytes(bytes_tree.from_string("{\"input_tokens\":7}")), + ) + } + }) + |> mist.bind("127.0.0.1") + |> mist.port(0) + |> mist.after_start(fn(port, _, _) { process.send(bound, port) }) + |> mist.start + let assert Ok(port) = process.receive(bound, 5000) + "http://127.0.0.1:" <> int.to_string(port) +} + +fn endpoint(base: String, path: String) -> token_count.Endpoint { + token_count.Endpoint( + base <> path, + [#("content-type", "application/json")], + ["input_tokens"], + refusal.http, + token_count.AnyRefusal, + ) +} + +fn ask( + endpoint: token_count.Endpoint, + text: String, +) -> Result(Int, types.Error) { + token_count.ask(endpoint, json.object([#("text", json.string(text))])) +} + +pub fn a_refusal_before_any_count_marks_the_endpoint_absent_test() -> Nil { + let fresh = endpoint(serve(), "/never-counted") + let assert Error(types.Refused(..)) = ask(fresh, "refuse") + let assert Error(types.Unsupported(_)) = ask(fresh, "count this") + Nil +} + +pub fn a_refusal_after_a_count_keeps_the_endpoint_test() -> Nil { + let served = endpoint(serve(), "/counted") + let assert Ok(7) = ask(served, "count this") + let assert Error(types.Refused(..)) = ask(served, "refuse") + let assert Ok(7) = ask(served, "count this too") + Nil +} -- knotmirror 0.0.1