eventloop

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 6, 2026 License: Apache-2.0 Imports: 11 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 eventloop serializes asynchronous external events into one canonical trajectory and decides when cognition may act on them.

The loop rests on one invariant, and every policy that defers work depends on it:

Commit is unconditional; acting is conditional; every deferral has a
wake-up. An event that has been committed but not yet acted upon must
eventually cause a run. Nothing committed is ever silently dropped.

Event sources may run concurrently. They submit typed observations, complete tool-result batches, or media commitment transitions, and every one of them enters the trajectory the moment it arrives, whatever the conversational state. Whether a continuation then runs is a policy decision made by a Gate, and a gate that says no leaves the events pending rather than consuming them. Wake starts the run that a deferral owes.

The coordinator never derives control from event text: priority is supplied by a trusted source, and triage follows from priority alone.

Index

Constants

View Source
const KindSignal trajectory.Kind = ""

KindSignal marks an event that opens a safe point without appending anything. It is the empty kind because it is the absence of a payload, not a new kind of trajectory item.

Variables

View Source
var (
	// ErrIdle means there is nothing committed or pending to act upon.
	ErrIdle = errors.New("event coordinator has no pending events")
	// ErrBusy means a run is already in flight and this one cannot join it.
	ErrBusy = errors.New("event coordinator is already processing a batch")
	// ErrInterrupted is the cancellation cause for an interrupting event.
	ErrInterrupted = errors.New("event processing interrupted by an urgent event")
	// ErrQueueFull means ingress capacity is exhausted.
	ErrQueueFull = errors.New("event coordinator pending queue is full")
	// ErrDeferred means the batch was committed but a gate declined to act on
	// it now. It is an ordinary outcome, not a failure: the events remain
	// committed and a later wake-up runs them.
	ErrDeferred = errors.New("event batch committed and deferred by policy")
)

Functions

This section is empty.

Types

type Batch

type Batch struct {
	Events       []Event
	Items        []trajectory.Item
	StartVersion uint64
	EndVersion   uint64
	// Triage is the strongest triage among the events in the batch. A parallel
	// batch is one the processor may handle without disturbing work in flight.
	Triage Triage
	// Deferred reports that some events in this batch were committed during an
	// earlier safe point and waited for a wake-up before being acted upon.
	Deferred bool
}

Batch is the exact event group handed to one processor invocation.

A batch may span more than one commit: events that were committed while a policy deferred acting on them are carried forward and handed to the run that the deferral owed. Each commit keeps its own batch marker inside the trajectory, so a model that receives two carried-forward groups can still see that they arrived as two groups.

func (Batch) Contains

func (batch Batch) Contains(kind trajectory.Kind) bool

Contains reports whether the batch committed at least one item of kind.

func (Batch) Signalled

func (batch Batch) Signalled(eventType string) bool

Signalled reports whether the batch carries a signal of the given type. A signal appends no item, so it is the one thing a batch is asked about by name rather than by trajectory kind.

func (Batch) SourceRevision

func (batch Batch) SourceRevision() uint64

SourceRevision is the newest perception revision represented in the batch.

type Config

type Config struct {
	Store     *trajectory.Store
	Processor Processor
	// Gate is optional. Without one, every committed batch runs immediately,
	// which is the correct behaviour for a runtime that has no reason to wait.
	Gate Gate
	// MaxPendingEvents is a required hard ingress bound.
	MaxPendingEvents int
	// ReservedInterruptEvents protects capacity from routine-event bursts. It
	// may be zero, but must be smaller than MaxPendingEvents.
	ReservedInterruptEvents int
	Now                     func() uint64
	NextID                  func(prefix string) string
}

type Coordinator

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

Coordinator owns ingress ordering, safe-point commits, deferral bookkeeping, and interruption of the current processor invocation. Model output still commits through the continuation runner's own version-checked transaction.

func New

func New(config Config) (*Coordinator, error)

func (*Coordinator) Active

func (coordinator *Coordinator) Active() bool

func (*Coordinator) Commit

func (coordinator *Coordinator) Commit() (Batch, error)

Commit drains the pending ingress queue and appends it atomically. It never consults the gate: an external event enters the trajectory the moment it arrives, whatever the conversational state.

func (*Coordinator) Deferral

func (coordinator *Coordinator) Deferral() (Deferral, bool)

Deferral describes the committed work currently waiting for a wake-up.

func (*Coordinator) Interrupt

func (coordinator *Coordinator) Interrupt(cause error)

Interrupt cooperatively cancels the processor currently running at a safe point without fabricating a model-visible trajectory item. It is used for operational signals such as the acoustic start of user speech: the final transcript is submitted later as the authoritative observation event.

func (*Coordinator) Metrics

func (coordinator *Coordinator) Metrics() Metrics

func (*Coordinator) Pending

func (coordinator *Coordinator) Pending() int

func (*Coordinator) RunNext

func (coordinator *Coordinator) RunNext(parent context.Context) (Batch, error)

RunNext commits everything pending and, if policy admits it, acts on that batch together with anything a previous gate deferred.

The two halves are deliberately not separable from the caller's side: commit happens on every call, whatever the gate decides, which is what makes commit unconditional in practice rather than only in principle. When the gate declines, the committed batch is returned alongside ErrDeferred so a caller can observe what it committed without being able to lose it.

func (*Coordinator) Runnable

func (coordinator *Coordinator) Runnable() bool

Runnable reports whether a call to RunNext would do anything.

func (*Coordinator) SetGate

func (coordinator *Coordinator) SetGate(gate Gate)

SetGate installs the deferral policy after construction.

The gate needs the coordinator as its waker and the coordinator needs the gate, which is a genuine cycle rather than an accident of ordering. Breaking it with a setter is honest about that; the alternative is a lazily resolved indirection that hides when deferral actually becomes active.

func (*Coordinator) Signal

func (coordinator *Coordinator) Signal() <-chan struct{}

Signal fires whenever there is work to do: an event arrived, or a wake-up released work that a gate had deferred. It is level-triggered with a depth of one, so a driver that always drains to idle after receiving cannot miss an edge.

func (*Coordinator) Submit

func (coordinator *Coordinator) Submit(event Event) (string, error)

Submit validates and queues an event without waiting for cognition.

func (*Coordinator) SubmitBatch

func (coordinator *Coordinator) SubmitBatch(events []Event) ([]string, error)

SubmitBatch validates and queues one inseparable ingress group. Either every event is admitted in the supplied order or none is. Media commitment lifecycles rely on this: their played and repair transitions must never be split by queue backpressure.

func (*Coordinator) Unacted

func (coordinator *Coordinator) Unacted() int

Unacted reports how many committed batches are waiting to be acted upon.

func (*Coordinator) Wake

func (coordinator *Coordinator) Wake(reason string)

Wake declares that a deferral condition has cleared.

Every condition a gate defers on owes exactly one of these: playback completion, the end of a user turn, an admission lease, relief from provider backpressure. If deferred work exists, it signals a run. Calling it when nothing is waiting is a no-op, which is what lets callers wake unconditionally on a state transition rather than checking first.

type Deferral

type Deferral struct {
	Reason       string `json:"reason"`
	Events       int    `json:"events"`
	Items        int    `json:"items"`
	SinceNS      uint64 `json:"since_ns"`
	StartVersion uint64 `json:"start_version"`
	EndVersion   uint64 `json:"end_version"`
}

Deferral records why committed work is waiting and what must happen next. It is operational telemetry: a deferral with no matching wake-up is the bug this type exists to make visible.

type Event

type Event struct {
	EventID            string
	Type               string
	Source             string
	Channel            string
	CorrelationID      string
	Priority           Priority
	Kind               trajectory.Kind
	OccurredNS         uint64
	SourceRevision     uint64
	SupersedesRevision uint64
	InvocationID       string
	Producer           trajectory.Producer
	Content            string
	Observation        *trajectory.ObservationMeta
	ToolResults        []trajectory.ToolResult
	ToolPlaceholder    *trajectory.ToolPlaceholder
	AssistantState     *trajectory.AssistantState
	Repair             *trajectory.RepairState
}

Event is one external occurrence. EventID is assigned on Submit when empty. ToolResults is deliberately a batch: one slow invocation's complete set of outstanding calls crosses the synchronization boundary atomically.

type Gate

type Gate interface {
	AdmitRun(context.Context, Batch) (bool, string)
}

Gate decides whether committed work may be acted upon now.

This is the conditional half of the invariant. A gate that declines does not consume the events: they stay committed and unacted, and whoever declined owes a Wake when its condition clears. The gate sees the batch and nothing else — the duplex state, admission leases, and provider backpressure it consults are its own, because they are interaction policy rather than event loop mechanism.

type GateFunc

type GateFunc func(context.Context, Batch) (bool, string)

func (GateFunc) AdmitRun

func (function GateFunc) AdmitRun(ctx context.Context, batch Batch) (bool, string)

type Metrics

type Metrics struct {
	CommittedBatches uint64 `json:"committed_batches"`
	DeferredBatches  uint64 `json:"deferred_batches"`
	// RefusedEvents counts events the log would not accept. It should be zero;
	// a number that climbs is a defect in whoever produced them, and the
	// events committed alongside them survived.
	RefusedEvents  uint64 `json:"refused_events"`
	Wakeups        uint64 `json:"wakeups"`
	ParallelRuns   uint64 `json:"parallel_runs"`
	PendingEvents  int    `json:"pending_events"`
	UnactedBatches int    `json:"unacted_batches"`
}

Metrics is operational telemetry with no model input in it.

type Priority

type Priority string

Priority is supplied by a trusted event source or a semantic/acoustic classifier. The coordinator never derives it from words in event content.

const (
	// PriorityRoutine waits for the next safe point.
	PriorityRoutine Priority = "routine"
	// PriorityInterrupt cooperatively cancels the work in flight.
	PriorityInterrupt Priority = "interrupt"
	// PriorityParallel is handled alongside the work in flight without
	// disturbing it. It exists for the case the loop could not previously
	// express: answering a quick question while long work continues.
	PriorityParallel Priority = "parallel"
)

type Processor

type Processor interface {
	Process(context.Context, Batch) error
}

Processor advances cognition from a committed event batch. The context is cancelled when an interrupting event arrives; the processor must stop at its next safe boundary.

type ProcessorFunc

type ProcessorFunc func(context.Context, Batch) error

func (ProcessorFunc) Process

func (function ProcessorFunc) Process(ctx context.Context, batch Batch) error

type Triage

type Triage string

Triage is what an arriving event does to work already in flight. It follows from priority alone, which is why deciding it is not a separate policy.

const (
	TriageQueue    Triage = "queue"
	TriageCancel   Triage = "cancel"
	TriageParallel Triage = "parallel"
)

func TriageOf

func TriageOf(priority Priority) Triage

TriageOf maps priority to its effect on in-flight work.

Jump to

Keyboard shortcuts

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