ledger

package
v0.207.0 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: Apache-2.0 Imports: 12 Imported by: 0 modules, 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 ledger records per-call telemetry to an append-only JSONL file and reports estimated tokens (and dollars) kept out of Opus — how the harness proves it earns its keep.

JSONL, not a locked key-value store, on purpose: the long-running MCP server and an occasional `local-offload ledger` invocation must both touch the ledger at once. Writers append with O_APPEND (atomic for the small one-line records on both POSIX and Windows); the reader takes no lock and tolerates a not-yet-complete trailing line. This is what lets the savings report run while the MCP server is live (the bbolt version could not — exclusive file lock).

Index

Constants

View Source
const (
	// KindStackFault: the stack itself failed or went silent (a seat, a node, a transport, a configuration that
	// cannot work). An operator, not a different request, is what fixes it.
	KindStackFault = "stack_fault"
	// KindCapacity: the stack was healthy and full: a place in line, a refusal for room, a wait that ran out.
	KindCapacity = "capacity"
	// KindCaller: the request is what cannot be served as given: its contract, its input, its credentials, a door
	// the node's policy keeps shut, or a caller that left.
	KindCaller = "caller"
	// KindCeiling: a configured ceiling (a step budget, a poll budget) stopped work that may have finished behind a
	// larger one.
	KindCeiling = "ceiling"
	// KindWork: the stack ran and the work itself failed: no usable answer, or one that failed its checks.
	KindWork = "work"
	// KindUnclassified: the failure no class names (ReasonOther). It is not filed under any other kind, so the
	// stack-fault share never counts a failure nobody could classify as the stack's.
	KindUnclassified = "unclassified"
)

The kind of a failure class: what the failure says about WHO owns it, written in code beside the closed reason-code set so a count of failures can be read as the question it is usually asked as, "how often does the stack itself fail". Without it a full queue, a caller's bad contract, a ceiling the work outgrew and a dead seat sit in one list on the same footing: reasoncode.go files congestion as "a place in line, not a failure", and core's defer classes (agentwire.go) keep a node's capacity, the caller's contract and a broken stack apart for the same reason (delegate.BrokenStackDefer names only infrastructure and config as the operator's to fix).

The kind is a fact about the CLASS, decided here once, and never about the row: no row's text is read. Where a class straddles two kinds the comment on its line says which way it was filed and why.

View Source
const (
	LabelSourceLiveEscalation       = "live-escalation"
	LabelSourceShadowCounterfactual = "shadow-counterfactual"
)

Label provenance values for Entry.LabelSource. Constants rather than string literals so a reader that filters on one cannot silently miss rows because of a typo at the writer.

View Source
const (
	// ReasonOK: the job completed and passed every acceptance check.
	ReasonOK = "ok"
	// ReasonStarted: the dispatch marker (Phase "started"): no outcome yet.
	ReasonStarted = "started"
	// ReasonFailedVerification: a result arrived and failed the contract's own
	// acceptance checks.
	ReasonFailedVerification = "failed_verification"

	// ReasonQueueFull: every node the delegator asked refused for capacity
	// (queue full, draining, leased, shed by the node, 429).
	ReasonQueueFull = "queue_full"
	// ReasonQueueDeadline: a node accepted the job and never started it before the
	// queue patience ran out, and did NOT confirm taking it back — it may still run.
	ReasonQueueDeadline = "queue_deadline"
	// ReasonQueueWithdrawn: the same, and the node took the job back (ADR 0064): it
	// will never run there. Either it confirmed a withdrawal the delegator asked for
	// at the queue deadline, or its own record said so when the delegator next polled
	// (reaped because nobody polled it within the poll lease, or withdrawn).
	ReasonQueueWithdrawn = "queue_withdrawn"
	// ReasonPollDeadline: a node owned the job and it did not finish inside the
	// poll budget.
	ReasonPollDeadline = "poll_deadline"
	// ReasonCanceled: the caller went away.
	ReasonCanceled = "canceled"
	// ReasonNodeUnreachable: no node answered (dial failure, dropped connection, a
	// poll that never got an answer).
	ReasonNodeUnreachable = "node_unreachable"
	// ReasonJobLost: a node denied ever holding the job it had acked (poll 404).
	ReasonJobLost = "job_lost"
	// ReasonDispatchRefused: a node refused the request itself (400, 401, 403,
	// 409...): a fact about the request or the credentials, not about capacity.
	ReasonDispatchRefused = "dispatch_refused"
	// ReasonRemoteError: a node reported the job errored, or its answer could not
	// be used.
	ReasonRemoteError = "remote_error"
	// ReasonCapacityWait: no node had room within the placement wait — the
	// delegator's OWN outcome, a result no node ran (PlacedResult.Unplaced).
	ReasonCapacityWait = "capacity_wait"
	// ReasonNodeBusy: a node (or this box's own seat) took the job and answered a
	// capacity defer AFTER admission: its seat was at its run cap ("seat busy:"), a
	// GPU lease or fence held its card ("gpu busy:"), or its engine was held busy by
	// other work. Kept apart from ReasonCapacityWait because they are different root
	// causes with different fixes — a seat at its cap is the node's admission, a
	// capacity wait is the fleet having no room — and a reader counting one must not
	// have to read the prose to exclude the other.
	ReasonNodeBusy = "node_busy"
	// ReasonShed: sheddable work found no idle node.
	ReasonShed = "shed"
	// ReasonNoEligibleNode: route=remote, or a failing fleet, with nothing eligible.
	ReasonNoEligibleNode = "no_eligible_node"

	// ReasonSeatDown: the seat the job needed could not serve it: it was unreachable,
	// went down under the run and did not come back inside the node's recovery wait
	// (`seat down:`, ADR 0066), or answered llama-swap's 5xx past the node's busy-seat
	// wait (`seat not serving:`, the same ADR) — the seat itself, not its peers.
	ReasonSeatDown = "seat_down"
	// The stall codes name the phase a run went silent in (ADR 0055, 0061): the
	// node's own liveness verdict, filed as infrastructure.
	ReasonStallAdmission = "stall_admission"
	ReasonStallColdLoad  = "stall_cold_load"
	ReasonStallPrefill   = "stall_prefill"
	ReasonStallDecode    = "stall_decode"
	ReasonStallTool      = "stall_tool"
	ReasonStallRepack    = "stall_repack"
	// ReasonStallEngine: the seat's engine did no work for anyone, or kept
	// stepping without producing a token (a wedged or thrashing seat).
	ReasonStallEngine = "stall_engine"
	// ReasonStallOther: a stall whose phase the reason does not name.
	ReasonStallOther = "stall_other"

	// The node's own defer classes (core.DeferClass*), for a defer no finer code names.
	ReasonBudget         = "budget"
	ReasonAbstention     = "abstention"
	ReasonContract       = "contract"
	ReasonConfig         = "config"
	ReasonWrite          = "write"
	ReasonInfrastructure = "infrastructure"

	// ReasonBadInput: the call's own input cannot be processed as given: an audio file with no audio
	// stream, a picture that does not load, a video that cannot be sampled. Nothing is wrong with the
	// stack or the contract; the file is what has to change.
	ReasonBadInput = "bad_input"

	// ReasonOther: a failure no code above names. The classifier is total, so a
	// row is never without a code — but a growing share here means the set needs a
	// new member.
	ReasonOther = "other"
)

Reason codes (register C-68, ADR 0064; every deferred row since F22): a CLOSED set that says why a delegated job ended the way it did, written beside the free-text Reason on every `agent_delegate` row and on every row of any task that deferred. The free text is for a human and varies with every job ("queue deadline after 5m0s (31 poll(s) answered `accepted`)"); the code is what a reader groups, counts and joins on. Before it, a fresh question about the fleet (how many jobs died queued? how many stalled in prefill?) needed a bespoke regex over prose, and the answers disagreed.

A delegate row that completed cleanly carries ReasonOK, so "reason_code present on every delegate row" is checkable without knowing which rows failed. A row of any other task carries a code only when it DEFERRED (F22, 2026-10-09: 21 of 100 deferred rows on one node, all 23 on another, none had one, because the code was settled for agent_delegate alone and every other door's defer was a free-text reason and, on the media doors, an err_class): a successful cascade or media row stays without one. The set is closed: Record replaces a code that is not in it with the classification of the row, so a typo at a writer cannot mint a new group. Adding a member is an additive change.

View Source
const (
	// ClassTest is test traffic: a go-test row, the fleet-smoke door, a test binary that opened a real ledger.
	ClassTest = "test"
	// ClassBake is a bake or bake-off run.
	ClassBake = "bake"
	// ClassMeasurement is a measurement: a call the caller pinned with pin_reason "measurement", or the
	// fleet-measure door.
	ClassMeasurement = "measurement"
)

The classes the harness itself writes.

View Source
const EnvRunClass = "LOCAL_OFFLOAD_RUN_CLASS"

EnvRunClass names the class of this process's runs: a bake or measurement tool sets it once (for example LOCAL_OFFLOAD_RUN_CLASS=bake) and every row the process writes, and every PAIR card it would open, is that class. Any clean lower-case label works (test, bake, measurement, or a new one such as soak): the set is open so that a typo reads as a non-production class a reader can see in the skipped count, never as production. "production" (or "prod") says the run is real work and sets nothing.

View Source
const PhaseStarted = "started"

PhaseStarted is Entry.Phase on the dispatch marker a delegator writes when it hands a job to a seat (ADR 0064). A marker is a record that a job BEGAN, not a job: it carries the job's id but no outcome, and the finished row with the same id is the job. Every reader above skips it, and ParentJobIDs must too — a marker looks exactly like a parent row (a job id, no parent), so an inner row whose real parent never landed would otherwise be dropped as an inner row of a parent that is only a marker, and the job would vanish from every count.

Variables

View Source
var DefaultPrices = Prices{InputPerMTok: 15.0, OutputPerMTok: 75.0}

DefaultPrices are the shipped Opus list rates ($/1M tokens) and the fallback an absent/zero config key resolves to, so an un-updated config under-reports by a KNOWN factor instead of silently zeroing half the accounting.

Functions

func AppendLabel

func AppendLabel(path string, e Entry) error

AppendLabel appends e as ONE JSON line to a correctness-label sidecar file (NOT the main ledger — kept separate so the router/calibration/savings report stay pristine). Only the confhead reads it. It creates the parent dir and stamps TS if unset; concurrent callers are serialized by labelMu.

func CardsTokensOf added in v0.206.0

func CardsTokensOf(e Entry) int

CardsTokensOf is the row's own card work by the figures it carries, for a writer that must add work Record cannot see (a call's earlier inner rows, whose cards_tokens Record zeroes): the call's row then sets CardsTokens to that carried work plus this figure, and Record keeps it.

func ClassOf added in v0.206.0

func ClassOf(e Entry) string

ClassOf is the run class of one row: "" for production, else the label. The stamped run_class wins; a row without one (written before the label existed, or by a writer that cannot know) is read by what it carries: the go-test origin and class-prefixed origins, a call its caller pinned for measurement, and the two doors that exist to produce test traffic. Everything else is production, and nothing is guessed from a seat name: a seat that is not in the served roster is a real misconfiguration the operator has to see.

func ClassOfDoor added in v0.206.0

func ClassOfDoor(door string) string

ClassOfDoor is the class a door makes on its own: fleet-smoke and fleet-measure exist to produce test and measurement traffic, so everything admitted through them is. A caller that must decide before it has a row (a card opened when a call begins) asks this instead of building one.

func ClassOfSession added in v0.206.0

func ClassOfSession(session string) string

ClassOfSession is the class a session label names on its own: "bake" for "bake:run-7", "test" for the go-test label, "" for an ordinary label. ClassOf reads the same off a row that names no class, so a label that carries a class labels every row written under it.

func CleanClass added in v0.206.0

func CleanClass(s string) string

CleanClass trims and lower-cases s and refuses anything that is not a short [a-z0-9_-] token, so a malformed environment value cannot bloat or break the one-line record. "production" is no class. It is the one rule for a run class wherever one is read: the process environment, and both ends of the fleet wire (the asker sends only a class that passes it, the node keeps only a class that passes it).

func CleanOrigin added in v0.206.0

func CleanOrigin(s string) string

CleanOrigin trims s and refuses anything that is not printable ASCII within maxOriginLen, so a malformed or hostile environment value cannot bloat or break the one-line record. It is the ONE rule for a session label wherever one is read: the process environment, the fleet wire (the asker sends only a label that passes it, the node keeps only a label that passes it), and the queue. A value over the cap is refused whole, never truncated: a truncated session id would attribute the row to a different session.

func CodeForDeferClass added in v0.206.0

func CodeForDeferClass(class string) string

CodeForDeferClass is the reason code of a defer class, or "" when the class is empty or not one the table knows (the row is then classified from its err_class and its reason, DeferCode).

func CountsAsJob added in v0.206.0

func CountsAsJob(e Entry, parents map[string]bool) bool

CountsAsJob reports whether a row is a job for a counter: every row except a dispatch marker, a refusal row and an inner row whose parent is present.

func DeferCode added in v0.206.0

func DeferCode(errClass, reason string) string

DeferCode is the closed-set code of a deferred row no writer classified: its err_class when the table knows it, else the prefix of its reason ("no ... configured" is config), else ReasonOther. Total: every deferred row gets a member of the set.

func FailureKindOf added in v0.206.0

func FailureKindOf(class string) string

FailureKindOf is the kind of a failure class (a reason code), or "" for a code that is not a failure member of the closed set (ok, started, and anything outside it).

func FailureKinds added in v0.206.0

func FailureKinds() []string

FailureKinds is the closed set of failure kinds.

func IsReasonCode added in v0.206.0

func IsReasonCode(s string) bool

IsReasonCode reports whether s is a member of the closed set.

func ParentJobIDs added in v0.206.0

func ParentJobIDs(entries []Entry) map[string]bool

ParentJobIDs returns the job ids of the rows that can be an inner row's parent: every row that carries a job id and is not itself an inner row.

func ReasonCodes added in v0.206.0

func ReasonCodes() []string

ReasonCodes returns the closed set of reason codes (a copy).

func RunClassFromEnv added in v0.206.0

func RunClassFromEnv(getenv func(string) string) string

RunClassFromEnv is the process class of an environment (Origin.Class) without the pid walk OriginFromEnv does: os.Getppid is a process-table snapshot on Windows, which is too slow for a caller that asks on every request (the PAIR emitters ask whenever a config is turned into one, and a delegation does that per call: two 50 ms-scale waits are enough to reorder the queue-route test). The same rule as ProcessOrigin's, so the two cannot name different classes.

func SessionFromEnv added in v0.206.0

func SessionFromEnv(getenv func(string) string) string

SessionFromEnv is the session label of an environment (Origin.Session) without the pid walk OriginFromEnv does: LOCAL_OFFLOAD_ORIGIN, else CLAUDE_CODE_SESSION_ID, cleaned. The same resolver ProcessOrigin applies, so the two cannot name different sessions.

func ShortReason added in v0.206.0

func ShortReason(s string) string

ShortReason is the display and grouping form of a stored reason: its first maxReasonLen bytes on a rune boundary. Every reader that aggregates by reason (TopDeferReasons, the loupe atlas, the PAIR error text) groups by this, so the full text the ledger now keeps does not fragment a class into one group per job-specific number. Group on the reason CODE where one exists.

Types

type Entry

type Entry struct {
	TS        int64  `json:"ts"`
	Task      string `json:"task"`
	TokensIn  int    `json:"tokens_in"`
	TokensOut int    `json:"tokens_out"`
	// SeatTokensIn is prompt work a seat did (agent rows), NOT tokens saved:
	// the summary never adds it to TokensSaved. Absent on pre-0.115.5 rows.
	SeatTokensIn int     `json:"seat_tokens_in,omitempty"`
	LatencyMs    int64   `json:"latency_ms"`
	TokPerSec    float64 `json:"tok_per_s"`
	CacheHit     bool    `json:"cache_hit"`
	Deferred     bool    `json:"deferred"`
	// --- self-learning signals (Phase 0 enrichment) ---
	Margin float64 `json:"margin,omitempty"`
	// MarginScale / MarginDeclaredMass / MarginAmbiguous describe the margin's
	// denominator (register D-130). Scale is "matched" (matched class tokens
	// only) or "full" (every alternative); EMPTY ON OLD ROWS READS AS MATCHED,
	// which is why every consumer that compares a margin against stored history
	// filters on it rather than pooling the two ~10x-apart scales. The declared
	// mass and ambiguous count are recorded in both modes so a full-scale
	// threshold can be re-derived from real rows before anyone flips the flag.
	MarginScale        string             `json:"margin_scale,omitempty"`
	MarginDeclaredMass float64            `json:"margin_declared_mass,omitempty"`
	MarginAmbiguous    int                `json:"margin_ambiguous,omitempty"`
	ModelTier          string             `json:"model_tier,omitempty"`
	Escalations        int                `json:"escalations,omitempty"`
	Reasoning          bool               `json:"reasoning,omitempty"` // produced by the terminal reasoning tier (a reclaimed deferral)
	Retries            int                `json:"retries,omitempty"`
	Truncated          bool               `json:"truncated,omitempty"`
	Grounded           *bool              `json:"grounded,omitempty"`
	EscalatedAgreed    *bool              `json:"escalated_agreed,omitempty"`
	ErrClass           string             `json:"err_class,omitempty"`
	InputChars         int                `json:"input_chars,omitempty"`
	Feat               map[string]float64 `json:"feat,omitempty"`
	// Reason is the human-readable defer reason (LO-8), set only on deferred
	// entries and stored WHOLE (bounded at maxStoredReasonLen; until ADR 0064 it
	// was cut to 120 bytes on write). A reader that groups or displays by reason
	// uses ShortReason. Old ledger lines without the field parse fine (empty
	// string); rows written before ADR 0064 hold the 120-byte cut.
	Reason string `json:"reason,omitempty"`
	// EscSource names WHICH gate sent the call up a tier, from core's closed
	// EscalationSource set. Unlike Reason it is written on SUCCESSFUL
	// escalations too — that was the gap: a call that escalated and then
	// succeeded recorded nothing, so the split between the one self-declared
	// gate (self_confidence) and the structural ones (margin/confhead/schema/
	// grounding/verifier/retries) could not be recovered from telemetry.
	// Closed set = groupable; the free-text Reason is not.
	EscSource string `json:"esc_source,omitempty"`
	// TierPack records how a climbed-to tier's input was packed (TO-3, see
	// core.Meta.TierPack). Empty on entry-tier rows; old ledger lines without
	// the field parse fine.
	TierPack string `json:"tier_pack,omitempty"`
	// Layer names the device layer a composite box served this call on (ADR
	// 0052: single | pair | triple | display), copied from core.Meta.Placed so
	// the utilization scoreboard can later sum work per layer (council R8 held
	// the by_layer summary; the column is what makes it summable). Empty — and
	// omitted — on a plain box, so its rows stay byte-identical; old lines
	// without the field parse fine.
	Layer string `json:"layer,omitempty"`
	// Oracle names a NON-LOCAL counterfactual oracle that produced this label
	// row's judgment (e.g. "nim" for shadow-label --oracle nim). Empty = the
	// local escalation tier (the default), so historic rows parse unchanged and
	// remote-judged labels stay auditable/filterable in the sidecars.
	Oracle string `json:"oracle,omitempty"`
	// --- call identity (memory-frontier Phase 0.1) ---------------------------
	// Hashes, never content. The ledger recorded THAT a call happened but not
	// WHAT it was about, so duplicate-rate, prefix-reuse and counterfactual-replay
	// questions could not be answered from telemetry at all. Storing full prompts
	// was rejected (privacy + multi-brand isolation); these fingerprints give the
	// grouping power without the liability. All omitempty: historic lines parse
	// unchanged, and the fields simply accrue going forward.
	InputSHA256        string   `json:"input_sha256,omitempty"`
	PromptPrefixSHA256 string   `json:"prompt_prefix_sha256,omitempty"`
	ContextHash        string   `json:"context_hash,omitempty"`
	ExemplarIDs        []string `json:"exemplar_ids,omitempty"`
	// CacheBypass names why the result cache was skipped entirely, so
	// "permanently uncacheable input" is one query away instead of being
	// indistinguishable from a cold miss.
	CacheBypass string `json:"cache_bypass,omitempty"`
	// CacheHitInLoop marks a cache hit served from an entry the agent loop wrote
	// (T2-D). In-loop generations run with a nil ledger and are never costed, so
	// without this the share of the cache-hit rate the harness produced for
	// itself is unrecoverable — and that rate is a gate.
	CacheHitInLoop bool `json:"cache_hit_in_loop,omitempty"`
	// Agent-loop prefill (T2-B). PrefillSteps present (>0) is what marks the row as
	// MEASURED; a row without it made no observation, which is not the same as a row
	// that observed zero prefill.
	PrefillSteps int `json:"prefill_steps,omitempty"`
	// AgentProfile: which agent profile the run resolved to. Absent on non-agent rows.
	AgentProfile string `json:"agent_profile,omitempty"`
	// LabelSource names WHICH WRITER produced a confhead-label row.
	//
	// confhead-labels.jsonl has two writers with OPPOSITE populations, and nothing
	// previously distinguished them:
	//   "live-escalation"       - pipeline.labelAgreement, only ESCALATED calls, judged by
	//                             answersAgree (classify/triage only).
	//   "shadow-counterfactual" - shadow.LabelQueue, only NON-escalated calls (captureShadow
	//                             skips anything with Escalations != 0), and it judges
	//                             summarize by embedding cosine rather than by answersAgree.
	//
	// Pooling those yields a rate that is conditional on escalation and unconditional at the
	// same time, which is no rate at all. Absent on pre-existing rows, which is why readers
	// must treat "" as unknown-provenance rather than as either source.
	LabelSource   string  `json:"label_source,omitempty"`
	PrefillTokens int64   `json:"prefill_tokens,omitempty"`
	CacheTokens   int64   `json:"cache_tokens,omitempty"`
	PrefillMS     float64 `json:"prefill_ms,omitempty"`
	// Arm labels which experimental arm this row was recorded under — the
	// LEDGER twin of the delegation log's field of the same name (see
	// delegate.delegationLogLine.Arm for the full argument: once rows from an
	// experiment and ordinary traffic interleave unlabelled in one file, no
	// timestamp separates them afterwards). Set from OFFLOAD_DELEGATE_ARM at
	// record time, process-wide: every row a tagged process records (agent,
	// agent_delegate, cascade offloads it triggers) belongs to that arm's run.
	// Without this, the prefill columns above are measured under an arm and
	// recorded without it — the exact "computed then discarded" defect class
	// the 0.79.0 instrument-honesty round was about, one file over.
	Arm string `json:"arm,omitempty"`
	// --- row provenance (0.124.0, register D-101) ---------------------------
	// OriginSession / OriginPID / OriginPPID name the PROCESS that recorded
	// the row and the session it served (see Origin). Record stamps them on
	// every row that carries none, so every writer in this binary — cascade,
	// agent, delegate, media — is attributed by one rule. A fleet node's row
	// carries the session of the asker that sent one (the X-Offload-Origin
	// header, ADR 0087) and the node process's own pids; a row for an asker
	// that sent none, or a service's own row, carries pids and no session;
	// pre-0.124.0 rows carry neither, and a reader must treat that as
	// UNATTRIBUTED, never as "some other session".
	OriginSession string `json:"origin_session,omitempty"`
	OriginPID     int    `json:"origin_pid,omitempty"`
	OriginPPID    int    `json:"origin_ppid,omitempty"`
	// Door names the SURFACE that admitted the call (register A-102): an MCP
	// tool name ("offload_summarize"), a CLI command ("cli:summarize"), or
	// "fleet" for a request a fleet node ran for a delegator. Origin* above
	// names the process; nothing named the door, so all 558 cascade rows in the
	// live ledger were indistinguishable between an MCP tool call, a hand-run
	// CLI command and fleet dispatch. Copied from core.Meta.Door; absent on
	// pre-0.129.x rows and on any writer that stamps none, which a reader must
	// treat as UNKNOWN DOOR, never as one of the values above.
	Door string `json:"door,omitempty"`
	// License is the license of the media binding that rendered the row (ADR 0058),
	// copied from core.Meta.License: a named family always declares one, a default
	// binding may. Absent = the binding declared none (every text row, and every
	// pre-0.134 media row) — which a reader must treat as UNKNOWN LICENSE, never as
	// commercial-safe.
	License string `json:"license,omitempty"`
	// CardsTokens is the ONE token figure a share reader wants: the tokens the
	// cards processed for this row — the seat's prompt work (SeatTokensIn on
	// agent rows, TokensIn on cascade rows: the same measurement under two
	// names, kept apart only because TokensIn doubles as the savings column)
	// plus what the seat generated. A cache hit did no card work and records
	// 0. Always written, never omitted: its PRESENCE marks a row that carries
	// this schema, so a reader can stop reconstructing the figure from three
	// columns and an input_chars/4 guess the moment it sees the key.
	CardsTokens int `json:"cards_tokens"`
	// --- the job behind the row (0.124.0, D-101 / F15) ----------------------
	// What the delegate result and the agent wire already knew, so the ledger
	// can answer "which session, which job, how many steps, why it stopped"
	// without opening the delegation-log corpus. All omitempty: a cascade row
	// has no job. Placement is the delegator's placement note, capped like
	// Reason; AcceptanceResult is "pass" | "fail" | "" (nothing evaluated: the
	// run deferred or the wire failed).
	JobID string `json:"job_id,omitempty"`
	// ParentJobID marks an INNER row (register C-62, 0.143.0): the `agent` row
	// the pipeline writes for a run the delegator placed on this box's own
	// seat. That job's authoritative row is the delegator's `agent_delegate`
	// row carrying this id (it alone knows the acceptance verdict). The inner
	// row keeps its savings (TokensIn: the parent records 0 there on purpose)
	// and its seat detail, but Record writes cards_tokens 0 on it and every job
	// counter skips it — until 0.143.0 each route=local job was counted twice
	// (1,002 of 1,002 local rows paired, 2026-09-19..27).
	ParentJobID string `json:"parent_job_id,omitempty"`
	// CallID names the tool call whose PAIR card this row closes (pairworkloads
	// Begin returns it, core.Meta carries it): the card's own job id. Without it
	// the ledger observer could only close the OLDEST open card of the task, so
	// under overlapping calls one call's row closed another's card. Omitted on a
	// row written outside a call that opened a card, which a reader must treat as
	// "no card was opened for this row", never as a call id.
	CallID string `json:"call_id,omitempty"`
	// QueuedMs (0.143.0, ADR 0061) is the wall an agent job's requests spent
	// in the liveness monitor's busy hold — waiting on a seat whose engine was
	// working for others — instead of being killed as a stall. The contention
	// column beside latency_ms.
	QueuedMs int64 `json:"queued_ms,omitempty"`
	// Route is the route the delegator APPLIED to the call. For a call whose local or remote route had no
	// pin_reason (a hint, ADR 0078) it is auto, and RouteAsked is what the caller named.
	Route string `json:"route,omitempty"`
	// RouteAsked is the route the caller named, written only on a call that went through a door offering pin_reason
	// with route local or remote, whether it gave a reason or not; Route is then what the delegator applied.
	// PinReason is the closed reason (privacy, locality, measurement, operator) the caller gave for pinning the
	// call, empty on a hint (RouteAsked set, no reason). Neither is set on any other row, which a reader must treat
	// as "the route was not a pin or a hint", never as a hint.
	RouteAsked string `json:"route_asked,omitempty"`
	PinReason  string `json:"pin_reason,omitempty"`
	Placement  string `json:"placement,omitempty"`
	Steps      int    `json:"steps,omitempty"`
	StopReason string `json:"stop_reason,omitempty"`
	RepackMs   int64  `json:"repack_ms,omitempty"`
	// RepackAttempts is how many seat completions the structured re-pack
	// spent. It rides beside RepackMs because the wall alone cannot tell a
	// slow single attempt from a loop that re-generated three times, and the
	// engine-route change of register D-129 is measured on exactly that
	// distinction: a vLLM seat constrained by `structured_outputs` should
	// finish in one attempt where the discarded `grammar` field cost it two
	// or three.
	RepackAttempts   int    `json:"repack_attempts,omitempty"`
	AcceptanceResult string `json:"acceptance_result,omitempty"`
	// --- telemetry the harness could not see itself with (ADR 0064, C-68) ----
	// FleetJobID is the id the job is known by on the fleet node that ran it: the
	// id the delegator dispatched it under. A delegate row carries it when the job
	// went to a node; the node's own row for the same run carries the same id, so
	// joining the two ledgers is one equality instead of a guess on latency. Empty
	// on a job that never left this box.
	FleetJobID string `json:"fleet_job_id,omitempty"`
	// Node and NodeID say where a REMOTE call ran, on the asker's row for it (PAIR routing fixes,
	// D5/D6): Node is the host of the dispatch URL (the name PAIR's members carry), NodeID the fleet
	// node id its health reported. Empty on every row of a call that ran on this box.
	Node   string `json:"node,omitempty"`
	NodeID string `json:"node_id,omitempty"`
	// Requester is who a fleet node ran the row's work for: the asker name the dispatch carried
	// (X-Offload-Asker, sanitized). Written on the NODE's row; empty on an asker's own row.
	Requester string `json:"requester,omitempty"`
	// CardByCaller marks a row whose PAIR card the writer already decided and emitted (or chose not
	// to emit: a remote call that never reached a node has none): the ledger observer must not card
	// it a second time. Absent on every row the observer cards.
	CardByCaller bool `json:"card_by_caller,omitempty"`
	// ReasonCode is the closed-set code for why the job ended the way it did (see
	// reasoncode.go), written on every agent_delegate row (ReasonOK for a job that
	// completed, so its presence never depends on the job having failed) and on every
	// deferred row of any other task. Absent on a row of another task that did not defer.
	ReasonCode string `json:"reason_code,omitempty"`
	// Phase is empty on every ordinary row — a finished record — and PhaseStarted
	// on the dispatch marker a delegator writes when it hands a job to a seat, so a
	// job that hangs, or a ghost that outlives its delegator, is visible before it
	// ends. A marker is never a job: every job counter skips it (jobrows.go).
	Phase string `json:"phase,omitempty"`
	// RunClass names the kind of run that wrote the row when it was not real work: "test" (a go-test row, the
	// fleet-smoke door, a test binary that opened a real ledger), "bake" (a bake or bake-off run), "measurement"
	// (a call pinned for measurement, the fleet-measure door), or a label the operator's tool chose with
	// LOCAL_OFFLOAD_RUN_CLASS (register F48 / C23). Record settles it on the one path every writer takes. EMPTY
	// IS PRODUCTION: every row written before the label existed, and every ordinary row after it, carries no
	// key at all. Every production view skips a labelled row by default and reports how many it skipped
	// (Summary.ExcludedNonProduction); a reader that must see them all asks (ReadAll, SummarizeFileWith).
	RunClass string `json:"run_class,omitempty"`
	// Refusal marks a row that is a node's capacity refusal AT DISPATCH (a 503 or 429), a place in line and not an
	// outcome: the delegator outwaits it and re-places the subtask, whose outcome is another row (the one that landed,
	// or the terminal row a lost subtask gets under a job id of its own). It is the ledger twin of the delegation
	// log's refusal mark. ABSENT ON EVERY OTHER ROW, and on every row written before the column existed, so a reader
	// that sees none reads the row as it always did: such a row may be an old refusal, and the column cannot say
	// otherwise. A reader that counts jobs or failures sets a marked row aside: the job counters of jobrows.go skip
	// it (CountsAsJob), and the failure register counts it as a refused attempt.
	Refusal bool `json:"refusal,omitempty"`
}

Entry is one offload call. The self-learning fields (margin..feat) are written by the pipeline from core.Meta; old lines without them parse fine (zero values).

func JobRows added in v0.206.0

func JobRows(entries []Entry) []Entry

JobRows returns the rows a job counter should read: inner rows whose parent row is present are dropped; orphan inner rows stay (they are their job's only record). The input is not modified.

func ProductionRows added in v0.206.0

func ProductionRows(entries []Entry) (kept []Entry, excluded map[string]int)

ProductionRows is entries without the non-production rows, and how many JOBS it skipped per class (a dispatch marker, a refusal row and an inner row are not jobs: CountsAsJob). The input is not modified. A ledger with no test traffic comes back whole with a nil map.

func ReadAll

func ReadAll(path string) ([]Entry, error)

ReadAll loads every parseable entry from a JSONL ledger (lock-free; skips malformed/partial lines, and a line that is not a JSON object, a literal null among them). Missing file => empty slice, no error.

func ReadLabelFile

func ReadLabelFile(path string) ([]Entry, error)

ReadLabelFile loads every parseable entry from a correctness-label sidecar (mirrors ReadAll). A missing file returns (nil, nil); blank/malformed lines are skipped.

func ReadProduction added in v0.206.0

func ReadProduction(path string) (kept []Entry, excluded map[string]int, err error)

ReadProduction is ReadAll without the non-production rows (ProductionRows over the file), for a reader that reports or trains on real work. ReadAll stays the raw reader.

type FailureClass added in v0.206.0

type FailureClass struct {
	Class string `json:"class"`
	// Kind is who owns this class of failure (failurekinds.go): stack_fault, capacity, caller, ceiling, work or
	// unclassified. A fact about the class, not the rows.
	Kind  string `json:"kind"`
	Count int    `json:"count"`
	// Share is Count over the register's FailureRows, rounded to four places.
	Share float64 `json:"share"`
	// ExampleReason is the most frequent short reason among the class's rows (ties broken by the smaller text),
	// "(unrecorded)" when no row of the class stored one.
	ExampleReason string `json:"example_reason"`
	// CardsTokens is the card work the class's rows spent: the sum over the rows that MEASURED it, nil (null in
	// JSON) when none did. It is never 0 for "nobody measured". A row measured it when a stored figure above 0
	// says so, or its older token columns hold work, or its stored 0 is the row's own (see failureRow.tokensOf:
	// the row names no node, the reason code says no node ran the job, or the node wrote the row itself). A
	// delegator's 0 for a job a node owned is not a measurement: the node's work is not on that row. RowsWithTokens
	// says how many rows measured it, so a total over fewer rows than Count is a floor.
	CardsTokens    *int64         `json:"cards_tokens"`
	RowsWithTokens int            `json:"rows_with_tokens"`
	Doors          []FailureCount `json:"doors"`
	Seats          []FailureCount `json:"seats"`
	Models         []FailureCount `json:"models"`
	Groups         []FailureGroup `json:"groups"`
}

FailureClass is one failure class: every failed job row of one reason code.

type FailureCount added in v0.206.0

type FailureCount struct {
	Name  string `json:"name"`
	Count int    `json:"count"`
}

FailureCount is a name and how many failed rows carry it.

type FailureGroup added in v0.206.0

type FailureGroup struct {
	Door  string `json:"door"`
	Seat  string `json:"seat"`
	Model string `json:"model"`
	Count int    `json:"count"`
	// CardsTokens is the card work of the group's rows that recorded any, nil when none did (see FailureClass).
	CardsTokens *int64 `json:"cards_tokens"`
}

FailureGroup is the rows of one class that came through one (door, seat, model).

type FailureKindCount added in v0.206.0

type FailureKindCount struct {
	Kind  string  `json:"kind"`
	Count int     `json:"count"`
	Share float64 `json:"share"`
}

FailureKindCount is the failure rows of one kind and their part of FailureRows (four places).

type FailureRegister added in v0.206.0

type FailureRegister struct {
	// LedgerFound is false when the ledger file does not exist: the zeros beside it then mean "nothing was read",
	// not "nothing failed". UnparsedLines is the non-blank lines that did not decode as a ledger row (garbage, a
	// line cut off mid-file, a non-object, a literal null, a last line the writer had not finished) and so are in
	// none of the counts below: a ledger that is partly unreadable must not look like a quiet one. A row is a JSON
	// object, so `{}` is a row (a job that did not fail), not an unparsed line.
	LedgerFound   bool `json:"ledger_found"`
	UnparsedLines int  `json:"unparsed_lines"`
	// JobRows is the job rows the register looked at, after the window and the run-class rule: a dispatch marker,
	// an inner row whose parent is present and a refused attempt are not jobs. FailureRows of them failed.
	JobRows     int `json:"job_rows"`
	FailureRows int `json:"failure_rows"`
	// RefusedAttempts is the rows that are a node's capacity refusal at dispatch (Entry.Refusal): a place in line,
	// not an outcome. The subtask they belonged to landed elsewhere or ended on a row of its own, which is the one
	// that counts; counted here instead, with the same window and run-class rule, so queue pressure stays visible
	// without a refused-then-landed subtask reading as two failures. A ledger written before the column existed has
	// none marked, and its refusals count as the failures they were then recorded as.
	RefusedAttempts int `json:"refused_attempts"`
	// Kinds counts the failure rows per kind (failurekinds.go), count descending then kind, a kind with no row absent.
	Kinds []FailureKindCount `json:"kinds"`
	// StackFaultRows is the failure rows whose class says the stack itself failed, and StackFaultShare their part of
	// FailureRows (four places), nil (null) when there is no failure row: a share of nothing is not 0. Capacity, caller,
	// ceiling, work and unclassified failures are not in it, and an unclassified one is never counted as the stack's.
	StackFaultRows  int      `json:"stack_fault_rows"`
	StackFaultShare *float64 `json:"stack_fault_share"`
	// ClassDerivedRows is how many failed rows carried no usable reason code (rows from before it was stamped,
	// a code outside the closed set) and were classed here by DeferCode, the classifier Record itself uses.
	ClassDerivedRows int `json:"class_derived_rows"`
	// CardsTokens and RowsWithTokens total the classes' (same rule, same nil).
	CardsTokens    *int64 `json:"cards_tokens"`
	RowsWithTokens int    `json:"rows_with_tokens"`
	// ExcludedNonProduction counts the test, bake and measurement jobs left out, per class (absent when none, and
	// always absent with includeTraffic), the way every production view of the ledger reports them.
	ExcludedNonProduction map[string]int `json:"excluded_non_production,omitempty"`
	// Classes are ordered by Count descending, then Class: the same ledger gives the same bytes.
	Classes []FailureClass `json:"classes"`
}

FailureRegister is the whole report.

func FailureRegisterFile added in v0.206.0

func FailureRegisterFile(path string, since int64, includeTraffic bool) (FailureRegister, error)

FailureRegisterFile reads the ledger at path and builds the failure-class register. since (unix seconds, 0 = all) keeps only rows from the window; the job and class indexes are the whole ledger's, so an inner row inside the window is still judged by a parent that is older (the way SessionSharesFile does). Unless includeTraffic, test, bake and measurement traffic is left out and counted per class (the run-class rule every production view of the ledger follows). A missing ledger is an empty register with LedgerFound false. Lock-free, like the other file readers: a last line still being written is not a row, and is counted in UnparsedLines with every other line that does not decode.

type Ledger

type Ledger struct {
	// contains filtered or unexported fields
}

Ledger appends entries to a JSONL file. The mutex serializes in-process writes; cross-process safety relies on O_APPEND atomicity for small lines.

func Open

func Open(path string) (*Ledger, error)

Open opens (creating if needed) the JSONL ledger for appending. It does NOT take an exclusive lock, so multiple processes can append concurrently.

func (*Ledger) Close

func (l *Ledger) Close() error

Close releases the append handle.

func (*Ledger) Observe added in v0.206.0

func (l *Ledger) Observe(fn func(Entry))

Observe registers fn to be called with every entry Record writes, after the write and its fsync succeed. One observer; a later call replaces it.

func (*Ledger) Record

func (l *Ledger) Record(e Entry) error

Record appends one entry as a single JSON line.

func (*Ledger) Summarize

func (l *Ledger) Summarize(since int64, prices Prices) (Summary, error)

Summarize aggregates this ledger's file since `since` (unix; 0 = all).

type Origin added in v0.206.0

type Origin struct {
	// Session names the calling session. LOCAL_OFFLOAD_ORIGIN when set (a
	// non-Claude caller naming itself), else CLAUDE_CODE_SESSION_ID — which
	// Claude Code exports to every child process, MCP servers included
	// (verified on three live servers, 2026-09-15). Empty for a service, a
	// fleet node, or a bare shell: unattributed, never "some other session".
	Session string
	PID     int
	PPID    int
	// Class is the run class of this process when it declares one (register F48): LOCAL_OFFLOAD_RUN_CLASS, else a
	// "<class>:<name>" origin label (bake:run-7). Empty is production. Record stamps it on every row the process
	// writes and the PAIR emitters open no card while it is set (runclass.go).
	Class string
}

Origin is the identity of the PROCESS that recorded a row: the session it served, and the writer's pid/ppid for a reader that groups by process.

Why (register D-101, 2026-09-15): the harness-share gate enforces a per-session floor by summing this ledger, and until 0.124.0 every row was anonymous — the hook summed every row in the session's time window, so a session was credited with every concurrent session's delegations, and a session that routed everything it had could still be blocked. One MCP server is one Claude Code session and inherits that session's environment, so the session id is free at record time; no process-tree walk is needed.

func OriginFromEnv added in v0.206.0

func OriginFromEnv(getenv func(string) string) Origin

OriginFromEnv resolves an origin from an arbitrary environment lookup, uncached, for a caller that must read the session label of a process other than its own start-up environment (a test, or a launcher helper that prints the flags for its caller). It is the same resolver ProcessOrigin applies, so the two cannot name different sessions.

func ProcessOrigin added in v0.206.0

func ProcessOrigin() Origin

ProcessOrigin resolves this process's origin ONCE: a long-lived MCP server's environment never changes, so a per-row read would only add a per-row inconsistency risk. Record stamps it on every row that carries none.

type Prices added in v0.206.0

type Prices struct {
	// InputPerMTok values prompt tokens kept out of the cloud (config
	// `opus_input_price_per_mtok`).
	InputPerMTok float64
	// OutputPerMTok values tokens the local seat GENERATED (config
	// `opus_output_price_per_mtok`). A caller with no configured value passes
	// DefaultPrices.OutputPerMTok - never 0, which is the defect this field
	// exists to close.
	OutputPerMTok float64
}

Prices values what a local seat produced, in Opus dollars per 1M tokens.

TWO rates, not one, because the cloud bills two: on Opus an output token costs FIVE TIMES an input token, and this package's whole claim is that a local seat did work the cloud would otherwise have billed. One rate cannot express that, and the single rate this package took priced output at zero.

func PricesFrom added in v0.206.0

func PricesFrom(inputPerMTok, outputPerMTok float64) Prices

PricesFrom resolves a config's two price keys against DefaultPrices. A non-positive key falls back to the shipped rate INDEPENDENTLY of the other, which is the whole point: every config written before `opus_output_price_per_mtok` existed carries an input price and no output price, and the fallback is what keeps those files from re-creating the priced-at-zero defect on upgrade. Floats, not a config struct, so the ledger keeps depending on nothing.

type ReasonCount added in v0.6.1

type ReasonCount struct {
	Reason string `json:"reason"`
	Count  int    `json:"count"`
}

ReasonCount is one aggregated defer reason for the ledger report.

func TopDeferReasons added in v0.6.1

func TopDeferReasons(path string, since int64, topN int) ([]ReasonCount, error)

TopDeferReasons aggregates the defer reasons of entries since `since` (unix; 0 = all) and returns the topN most frequent, ties broken alphabetically for deterministic output. Deferred entries written before the reason field existed count under "(unrecorded)" so the denominator stays honest. Lock-free like SummarizeFile; a missing file returns nil. Test, bake and measurement traffic is left out (register F48: a bake's "seat is not in the served roster" ranked among the real reasons); TopDeferReasonsWith includes it.

func TopDeferReasonsWith added in v0.206.0

func TopDeferReasonsWith(path string, since int64, topN int, includeTraffic bool) ([]ReasonCount, error)

TopDeferReasonsWith is TopDeferReasons with the choice of counting the non-production traffic.

type SessionShare added in v0.206.0

type SessionShare struct {
	// Session is the origin_session of the rows; "" is every row that carries none (unattributed), never merged
	// into a named session.
	Session string `json:"session"`
	// Rows is the number of jobs the session asked for that this ledger holds (a dispatch marker, a refusal row
	// and an inner row are not jobs).
	Rows int `json:"rows"`
	// CardsTokens is the card work of those jobs, RemoteTokens + LocalTokens.
	CardsTokens int `json:"cards_tokens"`
	// RemoteTokens is the part that ran on a fleet node; LocalTokens the part that ran on this box.
	RemoteTokens int `json:"remote_tokens"`
	LocalTokens  int `json:"local_tokens"`
	// RemoteShare is RemoteTokens over CardsTokens, 0 when the session did no card work.
	RemoteShare float64 `json:"remote_share"`
	// ServedRows and ServedTokens are the jobs this box ran FOR the session as a fleet node (door "fleet"),
	// on this box's own ledger. They are never part of the session's own totals above, so a ledger shared by a
	// delegator and a node (one box that is both) does not count a job twice.
	ServedRows   int `json:"served_rows"`
	ServedTokens int `json:"served_tokens"`
}

SessionShare is one session's card tokens split by WHERE they ran (register D-101, ADR 0087).

It is the card-side placement split: of the tokens the session's own jobs put through the cards, how many ran on a fleet node (RemoteTokens) and how many on this box (LocalTokens). It is NOT the share gate's figure, cards over cards plus cloud, which needs the session's transcript for the cloud term and stays in the hook; the two numbers answer different questions and must not be compared.

It is a FLOOR on the remote part. A row counts as remote only when it says so (a fleet job id or a node), and two kinds of remote work are missing from it: a cascade call routed to a node over the chat lane (the node writes no row, and the asker's row names neither the node nor a fleet job) reads as local, and a delegation sent with route "queue" writes no row on the asker's ledger at all (the claiming node's own ledger holds it, as a served row), so it is in neither number. A delegation pushed to a node is not a floor, whatever becomes of its started marker: the finished row's fleet job id comes from the node's ack, which is recorded before the marker.

It reads ONE box's ledger. The asker's own totals come from the rows its delegator process wrote; the served_* part comes from the rows this box wrote as a fleet node, which carry the asker's session only since the origin headers (ADR 0087). A view across the whole fleet is a reader of several ledgers; this is not it.

func SessionShares added in v0.206.0

func SessionShares(entries []Entry) []SessionShare

SessionShares groups entries by session (see SessionShare). Dispatch markers, refusal rows and inner rows are not jobs and are skipped; the caller decides which run classes to keep (SessionSharesFile applies the production rule).

func SessionSharesFile added in v0.206.0

func SessionSharesFile(path string, since int64, includeTraffic bool) ([]SessionShare, map[string]int, error)

SessionSharesFile reads the ledger at path and groups its rows by session (see SessionShares). since (unix seconds, 0 = all) keeps only rows from the window. Unless includeTraffic, test, bake and measurement traffic is left out and counted per class in the returned map (the way every production view of the ledger does, register F48). A missing ledger is an empty answer. Lock-free, like the other file readers.

type Summary

type Summary struct {
	Calls             int `json:"calls"`
	CacheHits         int `json:"cache_hits"`
	Deferred          int `json:"deferred"`
	Completed         int `json:"completed"`
	ReasoningReclaims int `json:"reasoning_reclaims"` // completed via the terminal reasoning tier (deferrals it reclaimed before Opus)
	TokensSaved       int `json:"tokens_saved"`       // input tokens kept out of Opus on completed/cache calls
	TokensOut         int `json:"tokens_out"`
	// EstValueKeptLocal is the estimated Opus value of the work kept local:
	// tokens_saved x opus_input_price_per_mtok + tokens_out x
	// opus_output_price_per_mtok, both per 1M. BOTH halves are priced — the
	// input tokens the cloud never received AND the output tokens a local seat
	// generated in its place (0.117.7; before that output was priced at zero,
	// which is the expensive half on Opus). It is an estimate of avoided cloud
	// pricing, NOT literal billed dollars saved (LO-12: the old
	// name for this field presented it as money in the bank).
	EstValueKeptLocal float64        `json:"est_value_kept_local"`
	ByTask            map[string]int `json:"by_task"`
	// ExcludedNonProduction is how many JOBS the summary skipped per run class because they were test, bake or
	// measurement traffic (register F48): the default views leave them out, and this says how many so nothing is
	// hidden. Absent when nothing was skipped, and always absent when the summary included them
	// (SummarizeFileWith includeTraffic).
	ExcludedNonProduction map[string]int `json:"excluded_non_production,omitempty"`
}

Summary aggregates the ledger.

func SummarizeFile

func SummarizeFile(path string, since int64, prices Prices) (Summary, error)

SummarizeFile reads a JSONL ledger without any lock — safe to call while another process is appending (a partial final line is skipped). A missing file reports an empty summary (nothing offloaded yet), not an error. Test, bake and measurement traffic is left out and counted in Summary.ExcludedNonProduction (register F48); SummarizeFileWith includes it.

func SummarizeFileWith added in v0.206.0

func SummarizeFileWith(path string, since int64, prices Prices, includeTraffic bool) (Summary, error)

SummarizeFileWith is SummarizeFile with the choice of counting the non-production traffic. With includeTraffic every row counts, as before the run class existed, and nothing is reported skipped.

Jump to

Keyboard shortcuts

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