batch

package
v0.11.8 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: Apache-2.0 Imports: 23 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 batch is the batch subsystem: it accepts bulk inference submissions, runs each item as a background job (via the jobq module), and exposes submit/poll/cancel/results over the customer-facing /v1 surface.

Layering: batch is a CONSUMER of jobq. jobq owns durable execution (claim, retry, crash recovery) and the per-item payload bytes; this package owns the batch concept — the batch record, the batch→job mapping, the inference handler that turns one item into an upstream call (reusing the realtime pipeline), and the HTTP API. The relay hot path is untouched; admission only validates and enqueues, execution happens off to the side.

Index

Constants

View Source
const DefaultMaxItems = 50000

DefaultMaxItems is the per-submission item cap when none is configured. Every item costs a payload file and two rows at submit, on one queue shared by all callers, so a single request must not be able to enqueue without bound.

View Source
const Queue = "inference"

Queue is the jobq queue name batch items run on. The Service registers its handler under this name; the worker pool drains it.

Variables

View Source
var ErrCredentialInvalid = errors.New("batch: credential no longer valid")

ErrCredentialInvalid is returned when the credential that submitted an item has since been revoked, expired, disabled, or rotated out.

View Source
var ErrCrossShape = errors.New("batch: cross-shape dispatch not yet supported")

ErrCrossShape is returned when a batch item's inbound shape differs from the resolved upstream adapter. v1 batch supports same-shape / byte-pass / native only; cross-shape translation is a follow-up. Surfaced explicitly rather than silently mis-dispatched (canonical rule 11).

View Source
var ErrForbidden = errors.New("batch: not owner")

ErrForbidden is returned when a caller asks about a batch they don't own.

View Source
var ErrNotFound = errors.New("batch: not found")

ErrNotFound is returned when a batch id is unknown.

View Source
var ErrPolicyUnavailable = errors.New("batch: policy_unavailable")

ErrPolicyUnavailable is returned when the policy the submission resolved to is no longer in the snapshot. The item fails rather than running policy-less.

View Source
var ErrTooManyItems = errors.New("batch: too many items")

ErrTooManyItems is returned when a submission carries more items than the Service accepts in one batch.

Functions

This section is empty.

Types

type Attribution added in v0.10.0

type Attribution struct {
	ProjectID      string
	TeamID         string
	PrincipalKind  string
	PrincipalID    string
	CredentialKind string
	CredentialID   string
}

Attribution is the principal and tenancy that authorised a submission — fixed at submit, not whatever the credential resolves to when an item finally runs. Ids only; slugs come from the snapshot at emit, as the policy name already does. It rides each item's job metadata so execution needs no extra read.

type Batch

type Batch struct {
	ID           string
	RelayKeyHash string // owner — used for authz on read/cancel
	PolicyID     string
	InboundShape string // the wire shape items are expressed in (adapter spec name)
	Status       Status
	TotalItems   int
	CreatedAt    time.Time
	CompletedAt  *time.Time
	Attribution
}

Batch is the durable record of one bulk submission.

type BatchView

type BatchView struct {
	*Batch
	Counts map[jobq.State]int `json:"counts"`
	Items  []ItemView         `json:"items"`
}

BatchView is a batch plus its items' live states and a per-state roll-up.

type Caller added in v0.10.0

type Caller struct {
	Attribution
	// KeyHash is the presented key's hash; empty for a token.
	KeyHash string
	// PolicyID is the already-resolved policy, not the key's raw field.
	PolicyID string
	// TokenVer and TokenExp are the token's version and expiry claims; zero
	// for a key.
	TokenVer int
	TokenExp int64
}

Caller is the identity a batch request arrives with, resolved by the transport. app/batch never reads an HTTP context itself: the inference layer owns bearer classification and the Key → ServiceAccount → PolicyBinding resolution order, and hands the result down.

func (*Caller) Owner added in v0.10.0

func (c *Caller) Owner() string

Owner is the opaque string a batch is authorized by on read and cancel: the bearer's key hash when it has one, else the principal, so a token-authenticated caller reaches its own batches and no one else's.

func (*Caller) TokenJTI added in v0.10.0

func (c *Caller) TokenJTI() string

TokenJTI returns the jti of the token the submission arrived with, or "" for a key. It rides each item so a token revoked after submit stops its queued work at the pipeline's reservation, as it would a live request.

type CallerFunc added in v0.10.0

type CallerFunc func(ctx context.Context) *Caller

CallerFunc resolves the caller from a request context.

type Item

type Item struct {
	BatchID string
	Idx     int
	JobID   string
}

Item maps one ordinal within a batch to the jobq job that runs it.

type ItemResult

type ItemResult struct {
	Idx      int             `json:"idx"`
	State    jobq.State      `json:"state"`
	Response json.RawMessage `json:"response,omitempty"`
	Error    string          `json:"error,omitempty"`
}

ItemResult is one item's terminal outcome for the results endpoint.

type ItemView

type ItemView struct {
	Idx   int        `json:"idx"`
	State jobq.State `json:"state"`
}

ItemView is one item's live state, read from jobq.

type Runner

type Runner struct {
	Resolver *routing.Resolver
	Pipeline *pipeline.Pipeline
	Specs    *adapter.Registry
	Catalog  *appcatalog.Catalog
}

Runner executes one batch item through the realtime inference pipeline, buffering the response. It deliberately reuses app/pipeline.Pipeline.Run so a batch item inherits keypool selection, circuit breakers, failover, and usage emission for free — the only difference from a live request is that the lifecycle source is "batch" and the response is buffered rather than streamed.

func (*Runner) Run

func (rn *Runner) Run(ctx context.Context, requestID, relayKeyHash, policyID string, tok TokenClaims, attr Attribution, inbound adapters.Name, body []byte) (int, []byte, error)

Run executes one item. requestID ties the usage event to the item (the jobq job id); policyID is the policy the submission already resolved to (the resolution order lives in the auth layer, not here), tok carries the submitting token's claims (zero for a key) so a revoked one is refused, and attr is the submission's attribution as recorded at submit. It returns the upstream status and the buffered response body. Usage emits automatically with source="batch" when the pipeline body closes.

type Service

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

Service is the batch subsystem's application layer: it accepts submissions, enqueues each item as a jobq job, and answers status/results/cancel. It is a pure consumer of jobq (execution) + Store (the batch record).

func NewService

func NewService(store *Store, queue *jobq.Queue, runner *Runner, resolveCaller CallerFunc, maxItems int) *Service

NewService wires the store, queue, and runner together. resolveCaller is how the HTTP surface learns who is asking; maxItems caps one submission (<= 0 means DefaultMaxItems).

func (*Service) Cancel

func (s *Service) Cancel(ctx context.Context, id, owner string) error

Cancel cancels every not-yet-terminal item and marks the batch cancelled. owner must match the batch owner token.

func (*Service) Handler

func (s *Service) Handler() jobq.Handler

Handler is the jobq Handler that runs one batch item. Registered on the queue at boot. Pure input→output: it runs the item through the realtime pipeline (reusing keypool/breakers/usage) and returns the response bytes, which jobq persists as the item's result. A non-2xx upstream status is a failure so jobq records it (the body is not retained in v1 — follow-up).

func (*Service) Results

func (s *Service) Results(ctx context.Context, id, owner string) ([]ItemResult, error)

Results returns each item's outcome: the response body for completed items, the error for failed ones. relayKeyHash must match the batch owner.

func (*Service) Routes

func (s *Service) Routes() http.Handler

Routes returns the /v1/batches HTTP surface. Mount it on the inference router behind the readiness → classify → auth chain so the Service's CallerFunc resolves an authenticated caller (key or token) from the request context.

POST   /v1/batches            submit (JSON: {shape, requests:[...]})
GET    /v1/batches/{id}       status + per-item states
GET    /v1/batches/{id}/results   per-item outcomes
POST   /v1/batches/{id}/cancel    cancel pending items

func (*Service) Status

func (s *Service) Status(ctx context.Context, id, owner string) (*BatchView, error)

Status returns the batch with live per-item states aggregated from jobq. owner must match the batch owner token.

func (*Service) Submit

func (s *Service) Submit(ctx context.Context, c *Caller, inbound string, items [][]byte) (string, error)

Submit creates a batch and enqueues one job per item. items are raw request bodies in the given inbound shape. Returns the new batch id.

c is the submitting caller, recorded on the batch so every item's usage event carries the attribution and the policy the submission resolved to, rather than whatever the credential resolves to when the item finally runs.

type Status

type Status string

Status is the coarse, cached lifecycle of a batch. The authoritative per-item state lives in jobq; this is a cheap roll-up plus the terminal cancellation marker.

const (
	StatusQueued    Status = "queued"    // accepted, items enqueued
	StatusRunning   Status = "running"   // at least one item has started
	StatusCompleted Status = "completed" // all items finished successfully
	StatusFailed    Status = "failed"    // all items finished, some failed
	StatusCancelled Status = "cancelled" // caller cancelled
)

type Store

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

Store persists batch records and the batch→job mapping via sqlc-generated queries. Per-item execution state is NOT stored here — it is read from jobq by job id.

func NewStore

func NewStore(pool *pgxpool.Pool) *Store

NewStore constructs a Store over pool.

func (*Store) AddItem

func (s *Store) AddItem(ctx context.Context, batchID string, idx int, jobID string) error

AddItem records the (batch, ordinal) → jobq job mapping.

func (*Store) Create

func (s *Store) Create(ctx context.Context, b *Batch) error

Create inserts a new batch record (status, counts; items added separately).

func (*Store) Get

func (s *Store) Get(ctx context.Context, id string) (*Batch, error)

Get returns a batch by id, or ErrNotFound.

func (*Store) Items

func (s *Store) Items(ctx context.Context, batchID string) ([]Item, error)

Items returns a batch's items in ordinal order.

func (*Store) ListByRelayKey

func (s *Store) ListByRelayKey(ctx context.Context, relayKeyHash string) ([]*Batch, error)

ListByRelayKey returns a caller's batches, newest first.

func (*Store) SetCompleted

func (s *Store) SetCompleted(ctx context.Context, id string, st Status) error

SetCompleted stamps the terminal status and completed_at.

func (*Store) SetStatus

func (s *Store) SetStatus(ctx context.Context, id string, st Status) error

SetStatus updates the cached status.

type TokenClaims added in v0.10.0

type TokenClaims struct {
	JTI     string
	Version int
	Expires int64
}

TokenClaims are the submitting token's revocation-relevant claims, carried on each item so execution re-checks them. Zero for a key.

Jump to

Keyboard shortcuts

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