schema

package
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 20, 2026 License: Apache-2.0 Imports: 6 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package schema holds the helpers this project layers over bifrost's message schema: token counting, deep-clone, MessageText/SetMessageText, Rewritable, ToolCalls (which pairs a tool result with the call that produced it), SessionHead, and static message-SHAPE validation.

Message-shape validation

ValidateShapeFor checks a message list against the provider's message-SHAPE rules — the rules that make a request well-formed regardless of its content.

WHY THIS EXISTS. Four separate shape violations shipped in `summarize` and every one of them was found REACTIVELY, by a live provider rejection or a benchmark failure, each masked by the one before it:

2edb9d4  400 messages.1: role 'system' must precede an 'assistant' message or end the array
fb5c460  400 messages.N.content.M: unexpected `tool_use_id` found in `tool_result` blocks
e7d1aa8  400 messages.N: `tool_use` ids were found without `tool_result` blocks immediately after
e9bf3a7  panic: index out of range [-1]   (a short transcript; see NOT CHECKED below)

None was findable by the project's existing methods. No test asserted the shape of what a component emitted, and every offline measurement replayed through the `/compact` endpoint, which runs the pipeline and returns the rewritten body WITHOUT forwarding it upstream — so no provider ever validated it. Replay can tell you what a component removed; it is structurally incapable of telling you whether the result is a sendable request.

The first three are checkable statically, with no provider and no model, because they are properties of the message list alone. That is what this is for: a component that mutates a message list can be asserted well-formed in a unit test, closing the blind spot without paying for live traffic on every change.

WHERE IT RUNS. Unit tests, over the pipeline's NORMALIZED view of a transcript — the shape apply.normalize produces and components mutate, where an Anthropic `tool_use` block has been lifted into bifrost's ToolCalls and each `tool_result` block is its own synthetic role=tool message.

It is deliberately NOT on the request hot path, but NOT because of cost. Measured on the eval box:

BenchmarkValidateShape166-16     25543 ns/op    9495 B/op   121 allocs/op
BenchmarkValidateShape500-16     72796 ns/op   35492 B/op   357 allocs/op
BenchmarkValidateShape5000-16   801821 ns/op  307919 B/op  3508 allocs/op

73 µs on a 500-message transcript is ~0.007% of a one-second provider call, and less than this package's own tokenizer plus apply.normalize already cost per request. Nor is "fail-open" a reason to stay off: fail-open IS a decision — validate the compacted body, revert to the original on violation, forward that. It converts a guaranteed provider 400 into a silently-lost saving, which is the trade this repo makes everywhere else.

The real blocker is the DIALECT GATE, and it is why ValidateShapeFor takes a provider. system-position is an Anthropic rule; OpenAI imposes no positional constraint on system/developer messages, and `/compact` defaults to OpenAI (proxy/proxy.go:566). Wired to the hot path with that rule ungated, every OpenAI request whose client re-injects a system message mid-array would be reverted and its saving silently lost — a savings regression dressed as a safety check. With the gate in place the remaining work is a post-pipeline check in apply.Body that reverts on violation. That is a separate change.

NOT CHECKED, and why — so nobody "fixes" these:

  • CONSECUTIVE SAME-ROLE messages. Must NOT be checked. `summarize`'s own legal output is [msgs[0], summary(user), user-tail...] — consecutive user messages. An alternation rule would reject the very output this validator exists to bless, and Anthropic accepts it.
  • e9bf3a7's PANIC inside boundary arithmetic. No check on the output list can see it: by the time there is a list to inspect the panic has already happened (and pipeline.runOne swallowed it into verdict=reverted). Shape validation is not a substitute for exercising a component on transcripts shorter than its own thresholds.
  • role="tool" reaching the Anthropic wire. Structurally invisible here, because apply.normalize maps a legal wire and one carrying the illegal role onto the IDENTICAL normalized list. It is a raw-BYTES property, so it is checked on the bytes, by apply/toolrole_wire_test.go and by the role predicate in apply/shape_validate_test.go.
  • ORPHANED `<<cg:HASH>>` markers. Deciding one needs the expansion Store, and a Store dependency does not belong in this package.
  • FIRST message not user, and a TRAILING assistant message. Neither is a hard provider rejection, and prefill (a trailing assistant turn) is a supported Anthropic feature.
  • Token limits, model names, sampling parameters, or anything content-dependent. This is a shape validator, not a request validator.

Package schema wraps bifrost's provider-agnostic chat schema with the helpers context-guru components need: token accounting, deep-clone for fail-open snapshots, tool-result iteration, and byte-preservation for lossless round-trips of provider-specific fields.

Components operate directly on *schemas.BifrostChatRequest (see package components); this package is the small toolbox around that type, not a competing model. Wire<->schema conversion lives in the host adapters — the bifrost proxy gets it for free from bifrost's transport, the AuthBridge plugin uses FromOpenAIBytes/FromAnthropicBytes (added in P3).

Index

Constants

View Source
const (
	RuleSystemPosition   = "system-position"
	RuleAnsweredToolUse  = "answered-tool-use"
	RulePairedToolResult = "paired-tool-result"
	RuleNonEmptyContent  = "non-empty-content"
)

Shape rule identifiers, so a test can assert on the specific invariant it exists for rather than on wording.

Variables

This section is empty.

Functions

func BlockText

func BlockText(b schemas.ChatContentBlock) string

BlockText returns the text payload of a content block, or "" if the block carries no text (image/audio/file/refusal).

func CloneMessages

func CloneMessages(in []schemas.ChatMessage) []schemas.ChatMessage

CloneMessages deep-copies a message slice via JSON round-trip. Used to snapshot a request before a component runs so the pipeline can restore it on error/panic or when a component fails the never-worse gate. JSON round-trip is safe because bifrost's content types implement custom (Un)MarshalJSON that preserve cache_control/citations/cachePoint.

func FormatShapeViolations added in v0.1.1

func FormatShapeViolations(vs []ShapeViolation, msgs []schemas.ChatMessage) string

FormatShapeViolations renders violations one per line for a test failure message, with the list's roles appended — the roles are what makes a shape failure diagnosable.

func MessageText

func MessageText(m schemas.ChatMessage) string

MessageText returns the concatenated text of a message, handling both the string-content and block-content representations.

func MessagesTokens

func MessagesTokens(req *schemas.BifrostChatRequest) int

MessagesTokens estimates the token cost of a request's messages by counting the message CONTENT text — what the model actually reads — not the JSON envelope. This is the signal the never-worse gate needs: control metadata like cache_control adds envelope bytes but no model-visible tokens, so a cache-injection Reformat must not look "worse" for adding it.

func Rewritable

func Rewritable(m schemas.ChatMessage) bool

Rewritable reports whether m's content can be safely replaced with a plain text string (via SetMessageText) without losing data. It is false when the message carries any non-text content block — image/audio/file/refusal, or a block type bifrost does not model (e.g. Anthropic tool_result, whose payload lives in fields MessageText never reads). Those bytes would vanish on a text-only rewrite and were never stashed, so components must skip such messages. String content and all-text block content are rewritable.

func SessionHead added in v0.1.1

func SessionHead(msgs []schemas.ChatMessage) (sys, firstUser string)

SessionHead returns the two strings the derived session key is hashed from: the conversation's HEAD system text and its first user message.

"Head" is load-bearing. The obvious reading — concatenate every system-role message — is what this replaced, and it is wrong for the Claude Agent SDK: that host APPENDS a fresh system-role message on every turn carrying its remaining- budget reminder (`<system-reminder><total_tokens>N tokens left</total_tokens>`), so the concatenation changed on every single request and each turn of one conversation derived a DIFFERENT key. Dedup memory, the extract_llm result cache and frozen offload decisions are all scoped to that key, so none of them ever accumulated past one turn.

A conversation only ever grows at the TAIL, so its head is the one part that is immutable by construction. Taking the first system-role message (plus the first user message, already head-only) is therefore stable across turns without asking the host for anything. Later system-role messages are deliberately ignored: they are per-turn host injections, never conversation identity.

func SetMessageText

func SetMessageText(m *schemas.ChatMessage, text string)

SetMessageText replaces a message's content with a single text string, collapsing any block structure. Components that rewrite a whole message's text (e.g. cmdfilter, offload markers) use this.

func TextTokens

func TextTokens(s string) int

TextTokens counts tokens in a raw string via the shared tokenizer.

func ToolCalls added in v0.1.1

func ToolCalls(req *schemas.BifrostChatRequest) map[int]ToolCall

ToolCalls pairs every tool-result message in req with the call that produced it, keyed by the message's index in req.Input. A message whose id matches no call — unmatched, missing, or a tool result with no preceding tool_use at all — simply has no entry, so a caller reads the zero ToolCall and falls back to whatever it did before. Ids are collected as the transcript is walked, so a result can only pair with a call that PRECEDES it, and several results in one message (Anthropic packs them into one user message; normalize splits them) each pair on their own id.

Types

type Provider

type Provider = schemas.ModelProvider

Provider identifies the wire dialect a request arrived in. It drives provider-specific behaviour (e.g. cache_control is Anthropic-family) and how the adapter renders bytes back out.

type ShapeViolation added in v0.1.1

type ShapeViolation struct {
	Index int    // message index, or -1 when the violation is about the list as a whole
	Rule  string // short, stable identifier for the invariant
	Msg   string // human-readable, mirroring the provider's own wording where possible
}

ShapeViolation is one broken invariant, phrased to point at the message that broke it.

func ValidateShape added in v0.1.1

func ValidateShape(msgs []schemas.ChatMessage) []ShapeViolation

ValidateShape reports every message-shape invariant the list breaks, judged as an ANTHROPIC request. It is the Anthropic-dialect shorthand for ValidateShapeFor; see there for the invariants and for why the dialect matters.

func ValidateShapeFor added in v0.1.1

func ValidateShapeFor(provider schemas.ModelProvider, msgs []schemas.ChatMessage) []ShapeViolation

ValidateShapeFor reports every message-shape invariant the list breaks when sent to `provider`. An empty result means the list is well-formed in the ways that provider enforces structurally.

THE PROVIDER ARGUMENT IS NOT DECORATION. Two of the four invariants are properties of the Anthropic-style tool protocol and hold for every provider that speaks it; the other two are Anthropic's own rules and are simply FALSE elsewhere. OpenAI imposes no positional constraint on system/developer messages, so checking system-position against an OpenAI transcript reports a violation on every turn where the client re-injects a system message — ordinary traffic, and `/compact` defaults to OpenAI (proxy/proxy.go:566). An ungated rule would therefore be a savings regression the moment this is used on the request path, which is why the gate is a prerequisite for that wiring rather than a nicety.

The invariants, and why each one exists:

  1. system-position — ANTHROPIC ONLY. A system-role message away from index 0 must be immediately followed by an assistant message, or end the array. This is the provider's own wording, and it is the defect that made `summarize` unusable on every call: it emitted [msgs[0], summary(system), tail...], so with the usual system prompt at index 0 a second system role landed at index 1 in front of the kept tail.
  2. answered-tool-use — ALL PROVIDERS. Every `tool_use` must be answered by a `tool_result` in the messages immediately following it. Removing a span can delete the answer while keeping the call: preserving msgs[0] when it is an assistant tool-call message does exactly that.
  3. paired-tool-result — ALL PROVIDERS. Every `tool_result` must answer a `tool_use` that appeared earlier. Removing a span can delete the call while keeping the answer. The mirror of (2), and the reason both are checked: e7d1aa8 showed they are one mistake seen from either side, and fixing one alone leaves the other live — which is what happened.
  4. non-empty-content — ANTHROPIC ONLY, on the evidence available. A message that CARRIES content whose text is blank is a hard 400 ("text content blocks must be non-empty"), and this pipeline has ~20 places that can produce one: every component that rewrites a message does it through SetMessageText, and any of them reducing a message to the empty string writes `""` straight onto the wire. `summarize` itself is NOT one of them — it refuses a blank summary (components/offload/summarize.go:201), confirmed by mutation: making its model return "" makes it decline rather than emit empty content. So this rule guards the OTHER rewriters (cmdfilter, dedup, skeleton, textclean and the rest), which have no such guard. Gated to Anthropic because an Anthropic rejection is what is on record; widen it when another provider's 400 is.

The rule is deliberately narrow in three ways, to preserve the property that makes this validator usable at all — content-shape false positives being impossible rather than merely absent. It fires only when Content is non-nil (a pure tool-call assistant message has nil content and is legal), only when the message carries no non-text block (Rewritable, so an image-only, thinking-only or tool_result-payload message is never judged by its text), and never on a role=tool message or an assistant message carrying ToolCalls, whose meaning lives in fields other than their text.

func (ShapeViolation) String added in v0.1.1

func (v ShapeViolation) String() string

type ToolCall added in v0.1.1

type ToolCall struct {
	Name string // "Bash", "Read", "Grep", …
	Args string // raw JSON arguments, e.g. `{"command":"rg -n foo"}`; "" when absent
}

ToolCall is the call that PRODUCED a tool result: the tool's name and its raw input arguments (a JSON object, as the wire carried it).

It exists because the premise "a proxy never sees the command that produced an output" is false. Both dialects put the call and its result in the same request, joined by an id — Anthropic as an assistant `tool_use` block referenced by the `tool_result`'s `tool_use_id`, OpenAI as an assistant `tool_calls[]` entry referenced by the tool message's `tool_call_id` — so a filter can key on the command (`rg -n foo`, `Read /x/y.go`) and not only on the output's shape.

Anthropic's `tool_use` blocks are not modelled by bifrost's chat schema, so the host's normalize step lifts them into ToolCalls (see apply.attachToolUse); this helper then reads one uniform shape for both dialects.

func (ToolCall) Command added in v0.1.1

func (t ToolCall) Command() string

Command renders the call as a single command-ish line: the `command` string for a shell tool, else the tool name followed by its arguments. It is the string a command-keyed filter selector matches against.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL