record

package
v0.18.0 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: Apache-2.0 Imports: 9 Imported by: ? 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 record holds the bounded, concurrency-safe stores a provider-API proxy keeps beside the accountant to price a request's cache entry across turns: the ping store, the sibling store and the tier store. Every host built on accountant keeps these three, and each wrote the same stores on its own before this package existed (accountant#150).

Each store is per key, bounded, and safe for concurrent use. A nil store pointer is a no-op, so a host that prices without one passes nil and reads empty. The stores hold only the library's hash-and-size Body and plain facts, never request content (R2).

  • PingStore remembers the latest keep-alive ping's accountant.PingFacts for a thread until the thread's next real request takes them.
  • SiblingStore remembers each thread's last forwarded body, to give accountant.EntryFacts.SharedWarm: the prefix another thread of the session already kept warm, which a keep-alive rescue must not credit again (R54).
  • TierStore remembers whether a thread's last write was billed at the one-hour tier, which the rule for a downgraded entry TTL reads after the response.

Recorder runs the accountant calls around one request and composes the three stores with the accountant.Trackers and a thinkcount.Table. A host builds one with NewRecorder and calls Begin (open the record with the client body), End (record the operations, the thread and the forwarded body, and set EntryFacts.SharedWarm from the SiblingStore), ComputeSafe (price the request, and fail open on a library panic) and Price (gate on the structural reasons that remain once a record is open, then compute, then spend the thread's ping facts). It knows no host concept: a host maps its own primary-thread name onto "main" before it calls the Recorder.

The stores are key-agnostic: PingStore and TierStore take a plain string key, so the host chooses its own key format. PingKey gives the one format both expect, session and thread joined, so a host that keeps both stores builds the key the same way for each. The thread id is the one the library sees. A host maps its own primary-thread name onto the library's first (the library calls it "main"); that mapping depends on the host's own thread identifiers, so it stays with the host, and the host passes the mapped id to PingKey.

This module is separate from the accountant root module for the reason the whole host module is (a host needs a JSON library the root module's stdlib-only rule, R3, forbids). The stores themselves import only accountant and the standard library. The package knows no host: no sweep, no preset, no host component name, only sessions, threads, pings and the generic cache facts the root module defines.

Index

Constants

View Source
const PingStoreMax = 4096

PingStoreMax bounds PingStore. It is keyed by session and thread, so without a bound a long-running proxy would hold one entry per thread that was ever pinged and never asked again.

View Source
const ReasonComputePanicked = "compute_panicked"

ReasonComputePanicked is the PriceOut.NoResult a request gets when the library panicked while it priced the request. It is a host reason, not a skip.Reason: a panic is the result of the Compute call, not a fact known before it (see skip's doc comment, and ComputeSafe).

Variables

This section is empty.

Functions

func PingKey

func PingKey(session, threadID string) string

PingKey is the key PingStore and TierStore keep one thread's facts under: the session id and the thread id joined by a NUL byte. threadID is the id the library sees ("main" for the first thread). A host that keeps both stores builds the key with this one function, so a ping facts entry and a tier entry for the same thread share a key.

func ThreadOf

func ThreadOf(id string, parent string, hasParent bool) accountant.Thread

ThreadOf is the library thread for a thread id and, when the thread continues another by content, its parent. A continuing thread starts with no state of its own: accountant carries Thread.Parent and does not read it (design §4.1). The ids are the ones the library sees; a host maps its own primary-thread name onto "main" before it calls this (see the package doc).

Types

type EndRecord

type EndRecord struct {
	Client, Forwarded accountant.Body
	Breakpoints       []accountant.Breakpoint
}

EndRecord is what End gave accountant.Request.EndRequest. The library keeps its record in unexported fields, so a test that checks the bodies the library saw reads them here.

type PingStore

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

PingStore remembers, per session and thread, the facts of the latest keep-alive ping until the thread's next real request takes them. A host gives the same instance to its ping emitter (writer) and to its request path (reader). A nil *PingStore is a no-op.

func NewPingStore

func NewPingStore() *PingStore

NewPingStore returns an empty store holding at most PingStoreMax threads.

func (*PingStore) Drop

func (s *PingStore) Drop(key, window string)

Drop deletes the facts for key: they belong to the next priced request only. window is the PingWindow the request read; facts with another window are a newer ping, put after the request read, and stay for the next request. An empty window drops whatever is there.

func (*PingStore) Len

func (s *PingStore) Len() int

Len is how many threads the store holds. Nil-safe.

func (*PingStore) NotePriced

func (s *PingStore) NotePriced()

NotePriced counts one priced ping. Nil-safe. A host calls it from its own pricing path, once a ping's facts (read via Peek, then dropped once the outcome is known) actually priced a request — the count this package keeps is the metric a host exposes for "pings that earned a saving".

func (*PingStore) Peek

func (s *PingStore) Peek(key string) (accountant.PingFacts, bool)

Peek returns the facts for key and keeps them. A request reads them before it is sent; it takes them (Drop) only once it is priced, so a request that books nothing leaves them for the next one.

func (*PingStore) Priced

func (s *PingStore) Priced() int64

Priced is how many pings the host priced. Nil-safe: a host with no store reads 0.

func (*PingStore) Put

func (s *PingStore) Put(key string, f accountant.PingFacts)

Put keeps the latest facts for key; a second ping overwrites the first. When the store is full and key is new, an arbitrary other entry is evicted (map order), which only costs the evicted thread its LastPing gap on its next request.

func (*PingStore) Take

func (s *PingStore) Take(key string) (accountant.PingFacts, bool)

Take reads and removes the facts for key in one critical section. Unlike Peek+Drop, it removes them whatever the caller does next with them, so it is for a caller that will not price the request from them (a test, or a host's own unconditional cleanup) — a request's own read-then- price flow should use Peek, then Drop(key, window) only once it knows the outcome (review of accountant#167: a Peek-then-Drop pair done across two locks let a Put racing between them be deleted by a taker that never saw it, through Drop's own empty-window wildcard rule; this reads and removes under one lock instead, so a race either takes the one entry that was there or takes nothing, never removes an entry a concurrent Put just wrote).

type PriceIn

type PriceIn struct {
	Status, Rounds int
	// NoResult is the reason an earlier step gave for booking no figure (a body rewrite that could not
	// be placed, skip.ReasonDeferralUnplaced). "" if none.
	NoResult string
	Usage    Usage
	// BeforeCompute, when set, runs once, just before the library prices the request and only when it
	// will. A host uses it to set the entry's billed tier on its facts, which Compute reads.
	BeforeCompute func()
	// AfterCompute, when set, runs once with the result, right after the library priced the request and
	// before the rescue counter and the ping-facts drop. It does not run when the request books no
	// figure. A host books the result here (event, metrics), so those side effects keep their order.
	AfterCompute func(accountant.Result)
	// Session and Thread are the ping store's key. KaPings is how many pings went out in the gap this
	// request ended. PingWindow is the window of the ping facts the request read when it opened, "" if
	// it read none.
	Session, Thread string
	KaPings         int
	PingWindow      string
	Pings           *PingStore
}

PriceIn is what Price needs of one finished request.

type PriceOut

type PriceOut struct {
	Result   accountant.Result
	Priced   bool // Result is set
	NoResult string
}

PriceOut is what Price decided. NoResult is PriceIn.NoResult, or the reason the request books no figure.

type Recorder

type Recorder struct {
	// Trackers holds each thread's state. Exported so a host test can break it on purpose.
	Trackers *accountant.Trackers
	// Siblings holds each thread's last forwarded body, for accountant.EntryFacts.SharedWarm.
	Siblings *SiblingStore
	// Tiers is the tier each thread's last write was billed at, for the host's downgraded-TTL rule.
	Tiers *TierStore
	// Thinking holds the token count of each thinking block a response made, by its signature's key,
	// so a block the client sends back is priced at its own count (accountant design D16). Saved with
	// the host's state.
	Thinking *thinkcount.Table
	// Clients holds the hash of each open request's client body, by request, from Begin to End.
	Clients sync.Map // *accountant.Request -> clientHash
	// OnEnd, when set, is called with each record after End. Tests only.
	OnEnd func(*accountant.Request, EndRecord)
	// contains filtered or unexported fields
}

Recorder runs the accountant calls around one request. It holds the one accountant.Trackers of a host, so a thread's state lives there between requests, plus the three bounded stores of this package and the thinking-count table. A host builds one with NewRecorder and calls Begin, End and Price for each request. It keeps no files, logs or metrics of its own; a host wires those around it.

The Recorder knows no host concept. It takes the thread id the library sees ("main" for the first thread); a host maps its own primary-thread name onto it before it calls Begin, End or ThreadOf, because that mapping depends on the host's own thread identifiers (see the package doc and PingKey).

func NewRecorder

func NewRecorder() *Recorder

NewRecorder returns a Recorder with empty state.

func (*Recorder) Begin

func (s *Recorder) Begin(meta accountant.RequestMeta, client []byte) *accountant.Request

Begin opens the request record with the client body, before any component ran. The Trackers bound their own memory (accountant design §6.1, Memory), so there is nothing to sweep here.

func (*Recorder) Compute

func (s *Recorder) Compute(req *accountant.Request, u Usage) accountant.Result

Compute prices the request. It stores the new ThreadState (so a shadow run still advances it).

func (*Recorder) ComputeSafe

func (s *Recorder) ComputeSafe(req *accountant.Request, u Usage) (res accountant.Result, ok bool)

ComputeSafe is Compute for the request path. The library asks the host to wrap Compute, and the rule is to fail open: a panic here would unwind through the host's finish and lose the log line and the dashboard row of a request that was already forwarded. It reports ok=false instead, the request is recorded with no saving (the host falls back with ReasonComputePanicked), and the panic is logged. Tests call Compute, so a panic still fails them.

func (*Recorder) Drop

func (s *Recorder) Drop(req *accountant.Request)

Drop forgets the client hash of a request that will never end: a panic between Begin and End makes the host send the original body, and End is the only other place that removes the entry. Nil-safe.

func (*Recorder) End

func (s *Recorder) End(req *accountant.Request, th accountant.Thread, forwarded []byte, ops []accountant.Operation, facts accountant.EntryFacts) EndRecord

End records the operations, then the thread and the forwarded body. Every op is added, replays included: the library replaces an active change by the reported op with the same ChangeID, so a change is priced once and unique_change never fires. Skipping a replay here would lose the op whenever Compute ends the change on this request.

func (*Recorder) NoteRescueFactsMissing

func (s *Recorder) NoteRescueFactsMissing()

NoteRescueFactsMissing counts one priced request that followed pings and found no ping facts. Nil-safe.

func (*Recorder) Price

func (s *Recorder) Price(req *accountant.Request, in PriceIn) PriceOut

Price prices one finished request, or says why it books no figure. It gates on the structural reasons that remain once a record is open (gate below): a rejected status, a body rewrite that could not be placed, several upstream rounds, and a panic in the library. It also counts a request that followed pings but found no ping facts, and spends the ping facts it read: they belong to the next priced request only.

func (*Recorder) RecordThinking

func (s *Recorder) RecordThinking(r thinkcount.Response)

RecordThinking stores the thinking counts of one billed response. Nil-safe.

func (*Recorder) RescueFactsMissing

func (s *Recorder) RescueFactsMissing() int64

RescueFactsMissing is the count NoteRescueFactsMissing keeps. Nil-safe.

type SiblingStore

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

SiblingStore remembers, per session, the last forwarded body each thread sent and when. It gives EntryFacts.SharedWarm: the prefix of a request's forwarded body that another thread of the session kept warm inside the TTL, which a keep-alive rescue must not credit (accountant R54). It holds the library's Body (hashes and sizes only, R2) and the breakpoints, never content.

The store lock is held only to find or create a session; each session has its own lock, so requests of different sessions do not wait on each other's scans.

func NewSiblingStore

func NewSiblingStore() *SiblingStore

func (*SiblingStore) SharedWarm

func (s *SiblingStore) SharedWarm(session, thread string, at time.Time, ttl time.Duration,
	fwd accountant.Body, bps []accountant.Breakpoint) *accountant.Position

SharedWarm returns the last position of fwd that a sibling of thread kept warm inside ttl before at, then records this request as the thread's last. The host chooses the siblings: another thread of the session, last seen inside the TTL and not after this request. The library decides where the shared prefix ends (accountant.SharedWarmFrom, R54). Nil when no sibling did.

type TierStore

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

TierStore remembers, per thread, whether its last write was billed at the one-hour tier. It is keyed like the ping store (PingKey) and holds one bool per thread: no content.

func NewTierStore

func NewTierStore() *TierStore

func (*TierStore) Get

func (s *TierStore) Get(key string) (oneHour, ok bool)

Get returns the remembered tier and whether the thread has one. Nil-safe.

func (*TierStore) Set

func (s *TierStore) Set(key string, oneHour bool)

Set remembers the tier. Nil-safe.

type Usage

type Usage struct {
	FreshInput, CacheRead, CacheWrite, CacheWrite1h int64
}

Usage is what one response billed, in tokens.

func (Usage) Accountant

func (u Usage) Accountant() accountant.Usage

Accountant is the usage in the library's type. It is the one conversion: every host site that builds an accountant.Usage from a billed usage calls it.

Jump to

Keyboard shortcuts

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