Repository navigation
gateway: count usage from multiline and final SSE events - #94
Conversation
|
Thanks for this. I pulled the branch and ran it: the new test passes and the gateway suite is green. But the change breaks a case that works on main, so I can't merge it yet. Regression: the sniffer now parses only when it sees a blank line (or EOF). A stream that separates events with a single func TestSniffSingleNewlineEvents(t *testing.T) {
payload := "data: {\"type\":\"message_start\",\"message\":{\"usage\":{\"input_tokens\":7}}}\ndata: {\"type\":\"message_delta\",\"usage\":{\"output_tokens\":3}}\n"
s := newSniffer(provider.Anthropic, "text/event-stream")
s.write([]byte(payload))
if got := s.usage(); got.Input != 7 || got.Output != 3 {
t.Errorf("usage %+v", got)
}
}Suggested approach: keep the per-line parse. On each |
|
Thanks for the quick v2. I checked it again, and it's merged. What I verified:
|
Problem
The gateway forwards provider SSE streams unchanged, but its usage sniffer parses each
data:line separately and only parses lines terminated by\n. A valid event split across multipledata:lines, or a final event with no trailing newline, therefore loses its token usage in Magpie's route and usage records. The request still succeeds, making the accounting error easy to miss.Fix
Accumulate
data:lines until an SSE event boundary, join them with newlines, and flush the last event at EOF. Keep a 1 MiB cap on buffered data. The response itself remains an untouched pass-through.Tests
TestSniffResponsesMultilineAndUnterminatedSSEfails on main for both cases and passes with this patch.go test -race ./internal/gateway -count=1,go vet ./internal/gateway, andgit diff --checkpass.go test ./...is not green in this workspace: the GUI needs GTK4/WebKit packages, and the unrelated existinginternal/provider/TestClaudeLoginsfails even when rerun alone. The gateway suite is green.AI assistance: an AI coding assistant helped investigate, write the patch and tests, and run the checks. I reviewed the changes.