Skip to content

Latest commit

 

History

History
659 lines (553 loc) · 38.1 KB

README.md

File metadata and controls

659 lines (553 loc) · 38.1 KB

bsp — bulk synchronous processing engine

bsp runs cyclic, iterative computations over a set of communicating vertices, on top of the task engine. An embedding application declares a group — a set of vertex definitions and a step budget — and the engine drives it in supersteps: every scheduled vertex runs in parallel, each emits messages addressed to the next superstep, and a barrier ends the round. It is a library-form adaptation of Google's Pregel — "think like a vertex" — scoped to program-scale graphs, tens of vertices rather than millions. The motivating use case is LLM agent execution (a ReAct loop is a two-vertex cycle), but nothing in the design is agent-specific.

It is a sibling of the workflow engine, not a replacement:

Workflow (DAG) BSP
Structure Acyclic, static Cycles are the point
Node execution Once Many times, until convergence
Termination All sinks complete None — the run rests, and external input wakes it

That last row reframes everything below. There is no success terminal: a group has no COMPLETE state and the engine never declares a run over. It comes to rest when nothing is scheduled, wakes when input arrives, and an application declares a run finished by cancelling it. Like the rest of tasking, this is a library embedded by other applications: it orchestrates, but it does not own multi-tenancy, access control, or scheduler leader election — those belong to the embedding application (see DESIGN.md).

For the design record — the superstep/barrier model, the branch and vertex state machines, message delivery and correlation, the fork mechanics, and everything deferred — see DESIGN.md. This README covers what the package provides and how to use it.

The core idea in one paragraph

A group declares a set of vertex definitions and never itself executes. A branch is the line of execution that actually runs, and it carries the run state — the group has none. A superstep is one round on a branch, numbered from 0: the engine resolves the frontier (the vertices with messages delivered at this superstep, plus those that ran the previous one and did not vote to halt), runs each one's Compute, and then the barrier — the only point at which the computation has a well-defined global state — accepts what each vertex produced, delivers messages to the next superstep, and writes the checkpoint. Every vertex superstep runs as a single task under the reserved task name __EXECUTE_BSP_VERTEX__, so the engine gets the task engine's retry, timeout and crash-safety for free. The three components never call each other directly: they exchange messages over Redis and share a database. The database is the source of truth; commands to the scheduler are best-effort pokes that let it act sooner than its periodic maintenance sweep would. Lose a poke and work is delayed, never lost.

Components

Component What it does Lifecycle
Client The BSP API — define, control, inject, fork, query, drain the outbox construct, then call
Scheduler The state machine — sole writer of branch and vertex state; opens supersteps, runs barriers, forks Start / Stop; single-active
Vertex Runner The one task processor that runs a vertex's superstep by dispatching to your Compute register with the task engine

Two registration acts, which must not be conflated:

  1. Runner ↔ task engine — the Runner is registered under the reserved task name. Engine-internal and done once; the queue helper below is the whole of what you do about it.
  2. Compute ↔ Runner — you supply one processor per ProcessorType your definitions name. Construct-time and immutable: there is no runtime Register, and so no ordering hole where a task arrives before its processor exists.

You wire these together in your application, injecting the Redis-backed factory callbacks (common.NewRedisIPCMessage*, notify.NewConsumer) — or let the root tasking package's constructors fill them in. Tests inject mocks instead.

Defining a group (Client)

Like the workflow engine, the Client offers the define / submit / define-and-run split. DefineBSPGroup writes the group, its vertex definitions, the root branch and that branch's singleton vertices without starting anything; SubmitBSPGroup starts an already-defined group; DefineAndRunBSPGroup does both. The split matters more here than it does for a workflow: an application owns its vertices' state, and a group that starts before that state exists starts too early.

client, err := bsp.NewClient(ctx, bsp.NewClientParams{
    Name:                "my-app",                 // also the identity stamped on scheduler pokes
    DefaultCreator:      "my-app",                 // opaque; the notify routing key and read scope
    Persistence:         dbClient,                 // db.Client
    Config:              clientConfig,             // models.BSPClientConfig
    Redis:               redisClient,              // goutilsRedis.Client
    IPCSenderFactory:    common.NewRedisIPCMessageSend,
    KnownProcessorTypes: knownProcessorTypes,      // map[string]bool — types with a Compute
})

retry := models.TaskRetryParameters{MaxRetries: 3, InitialDelaySec: 5, Factor: 2}

group, definitions, rootBranch, err := client.DefineAndRunBSPGroup(ctx, bsp.DefineBSPGroupParams{
    Spec: models.NewBSPGroupParameter{
        Name:                    "assistant-session-42",
        MaxSuperstep:            60,   // mandatory: the sole guard against livelock
        MaxSuperstepDurationSec: 300,  // becomes each vertex task's deadline
        Definitions: []models.NewBSPVertexDefinitionParameter{
            {
                Name: "reasoner", Kind: models.BSPVertexKindSingleton,
                Execution: models.BSPVertexExecutionEngine,
                ProcessorType: &reasonerType, RetryParams: &retry,
            },
            {
                Name: "tool:search", Kind: models.BSPVertexKindTemplate,
                Execution: models.BSPVertexExecutionEngine,
                ProcessorType: &searchType, RetryParams: &retry, MaxInstances: &maxCalls,
            },
            {
                // The engine never runs this one. It is addressed and sent messages like any other
                // vertex; the engine publishes them and the application delivers them.
                Name: "human", Kind: models.BSPVertexKindSingleton,
                Execution: models.BSPVertexExecutionExternal,
            },
        },
    },
    // Creator:        &perCallCreator,   // optional; overrides DefaultCreator
    BranchMetadata: map[string]string{"session": "42"},
}, nil /* or an active db.Database txn to join */)

// Or split the two halves — commit your own vertex state in between:
group, definitions, rootBranch, err = client.DefineBSPGroup(ctx, params, nil)
// ... write the application-side state the vertices will read ...
err = client.SubmitBSPGroup(ctx, rootBranch.ID)

The two axes. Kind gives cardinality and therefore lifetime: a SINGLETON has exactly one instance whose address is the definition name, is created with the branch, and never retires; a TEMPLATE has zero or more instances, each addressed by name plus a discriminator, materialized at a barrier when first addressed and ending on a RETIRE vote. Execution says who runs the vertex — ENGINE or EXTERNAL. They are not independent: EXTERNAL implies SINGLETON, and an external definition carries no ProcessorType, retry or timeout at all, having no task to apply them to.

MaxSuperstep is mandatory and cannot be turned off. It is the sole guard against livelock, since a vertex that never votes to halt stays scheduled forever. A long-lived group raises it as it goes through ExtendBSPGroup, and there is deliberately no way to lower it — the operation that stops a run is cancel. MaxSuperstepDurationSec bounds one superstep, and becomes each vertex task's deadline.

Up-front ProcessorType validation. KnownProcessorTypes is the set of types with a registered Compute — the same registration the Vertex Runner holds. DefineBSPGroup rejects, before writing any rows, a group declaring an ENGINE vertex whose ProcessorType is not in it, turning a superstep-12 failure into a fail-fast at definition. A duplicate definition name is rejected at the same point.

Error contract. Every failure the Client returns is a models.BSPClientError carrying the cause underneath, so what happened is read out of the chain with errors.As:

  • goutils.ValidationError / goutils.BadInputError / goutils.ConsistencyError — the spec was rejected before any database work; nothing was written.
  • goutils.PersistenceError — the rows were not created; nothing happened.
  • models.IPCMessageQueueError — the rows were created, but the scheduler poke failed. The group is not lost: the root branch is PENDING, which is the first position the maintenance sweep re-pokes, so a failed submit costs one sweep interval.
  • goutils.NotFoundError — on every later operation, what a group outside this client's creator scope looks like.

The same three classes apply to every other Client operation, so a caller reads a control request, an injection or a fork the same way it reads a define.

Every submission operation is "write rows, then poke the scheduler". The Client writes rows at their initial values and never performs a state transition — that is the scheduler's exclusive job, so there is a single writer of state.

Running a superstep (Vertex Runner + your Compute)

Implement models.BSPVertexComputeProcessor for each ProcessorType, then register them all with one Vertex Runner and hand that runner to the task engine as the processor for the reserved task name models.BSPExecutionTaskName. Every vertex of every group — whatever its ProcessorType — runs as a task of that one name; the Runner loads the (vertex, superstep) coordinate, assembles the inbox, resolves your processor, and commits what came back:

type reasoner struct{ store MyStateStore }

func (r reasoner) ProcessSuperStep(
    ctx context.Context,
    group models.BSPGroup,
    branch models.BSPBranch,
    vertex models.BSPVertex,
    superstep int64,
    inbox []models.BSPMessage,
    taskEntry models.Task,
) (models.BSPComputeResult, error) {
    // Vertex state is yours. Load it from your own store, keyed by the coordinates handed in.
    state, err := r.store.Load(ctx, branch.ID, vertex.ID)
    if err != nil {
        return models.BSPComputeResult{}, err
    }

    // ... read the inbox, do the work, write your own state back ...

    return models.BSPComputeResult{
        Outbox: []models.BSPComputeSend{
            {
                Type:                   models.BSPMessageTypeRequest,
                Ordinal:                0,
                RecipientName:          "tool:search",
                RecipientDiscriminator: &callID, // addresses one template instance
                Payload:                searchArgs, // a Go value; the Runner encodes it
                Instantiate:            &models.BSPInstanceSpec{Parameters: toolParams},
            },
        },
        Disposition: models.BSPVertexDispositionHalt, // waiting on the answer
        Metadata:    map[string]any{"tokens": used},
    }, nil
}

Then declare the Runner as the processor for the reserved task name. The root package does this in one call:

// Builds the Vertex Runner and returns it as an ordinary task queue config.
bspQueue, err := tasking.DefineTaskQueueForBSPVertex(
    "bsp-queue", 4 /* workers */, 16 /* buffered requests */, dbClient,
    map[string]models.BSPVertexComputeProcessor{
        "reason": reasoner{store: myStore},
        "search": searchTool{},
    },
)

// ... which expands to the Runner plus a queue declaring the reserved name:
runner, err := bsp.NewRunBSPVertexTaskProcessor(dbClient, vertexHandlers)
bspQueue = models.TaskQueueConfig{
    Name: "bsp-queue", Workers: 4, BufferRequests: 16,
    SupportedTasks: []models.TaskDefinition{
        {TaskName: models.BSPExecutionTaskName, Retry: someRetry, Processor: runner},
    },
}

The queue's Retry is never consulted: the scheduler names retry parameters on each vertex task as it defines it — the instance's own where it has them, its definition's otherwise — and the task client resolves its own default when neither declares any.

What a Compute may rely on, and what it owes:

  • It is a function of its inbox. The inbox arrives as a value and the outbox leaves as one; the engine's schema is not part of this API. Neither is business data: a vertex reads and writes its own store, keyed by the coordinates handed in. The engine holds no vertex state.
  • The inbox is the whole batch, deterministically ordered by (sender, ordinal). That ordering is load-bearing — a Compute that branches on inbox[0] under an unstable order breaks determinism only under retry, which is the worst way for it to surface.
  • The three dispositions are a returned value, not a method call. CONTINUE schedules the vertex again regardless of traffic; HALT moves it to IDLE and is revocable — a message arriving at a barrier reactivates it with its identity and state intact; RETIRE is terminal and template instances only. CONTINUE must be stated: a processor that says nothing is rejected rather than read as having voted for it. FAILED is not a disposition — it is the absence of any vote, written by the scheduler when a task ends without committing.
  • Everything outside an Effect must be deterministic. The task engine is at-least-once and recovery is re-entry, not resumption: Compute runs from the top and the journal makes already-completed effects return instantly. Pass the taskEntry handed in to your own models.JournalManager to obtain a journal for task.Effect; a processor that wants no journaling can ignore it.
  • Return models.NonRecoverableError for a failure retry cannot fix, so the attempt budget is not burned on an identical failure.

The Runner runs only a vertex that is still RUNNING. An attempt that committed everything and died before reporting leaves its post-state on the row, and that is what a retry reads to know the work is done — which is how at-least-once execution stays safe here without a destructive write.

Routing. A vertex task is an ordinary task, so the queue above must reach both the receiver's models.TaskReceiverConfig (which runs the tasks) and the task scheduler's models.TaskSchedulerConfig (which routes them to that queue). Give it to the receiver alone and vertex tasks are defined but never routed — a branch then holds one position until the maintenance sweep settles it FAILED. And the application must never declare models.BSPExecutionTaskName in a queue of its own, nor submit tasks under models.BSPExecutionTaskCreator: the scheduler reads every task carrying that creator as the outcome of a vertex superstep.

Controlling a run

err = client.PauseBSPGroup(ctx, groupID, nil)
err = client.ResumeBSPGroup(ctx, groupID, nil)
err = client.CancelBSPGroup(ctx, groupID, nil)
err = client.ExtendBSPGroup(ctx, groupID, 30 /* supersteps of headroom */, nil)

All four are addressed to the group, not to a branch — the scheduler resolves HEAD when it reads the request, so a fork landing in between cannot apply a pause to a branch that has just become history. All four are level-triggered: the barrier and the dispatch read the current value when they run, rather than consuming a transition. Every one of them is therefore idempotent for free — cancelling a cancelled group, pausing a paused one, resuming a running one are all successful no-ops — and a lost or duplicated poke costs latency but never a state change.

Pause is graceful and asynchronous. The request is recorded immediately; the branch stops at the next boundary that can honour it. Wait for the BSP_BRANCH_PAUSED event to learn that it did — that event is the middle step which makes pause, wait, then cancel a clean stop on a written checkpoint. Only an explicit resume clears a pause: input injected meanwhile does not wake the branch, and is not lost by waiting.

CANCELLED is absorbing — nothing clears it, and execution continues only on a child branch. It is the ordinary first step of a retry rather than only an abort: forking requires a settled parent, so "I don't like what this superstep did" is cancel, choose a boundary, fork. Since a group has no success terminal, cancelling is also how an application declares a run over, and that declaration sticks — injection into a settled HEAD is refused.

ExtendBSPGroup's offset is relative while the field is absolute. The Client reads HEAD's position and enqueues max(MaxSuperstep, HEAD.CurrentSuperstep + offset), so offset bounds the headroom bought from above rather than naming it exactly. It is monotonic; a zero or negative offset is a goutils.BadInputError.

The engine outbox — what the engine owes you

The outbox is the whole of the engine's outward work channel: three things it asks the application to do rather than merely telling it about. Everything else the engine says travels notify as an observation.

Subject Payload What it asks
EMIT_MESSAGE models.BSPOutboxEmitMessagePayload Deliver this message to an external vertex
WITHDRAW_MESSAGE models.BSPOutboxWithdrawMessagePayload Retract one already delivered — the branch settled, or it was abandoned
PREP_FOR_FORK models.BSPOutboxPrepForForkPayload Copy your half of a fork checkpoint, then acknowledge

The engine publishes; the application delivers. It knows no transport and holds no credentials, so it writes a row in the same transaction as the state change that decided it and waits for you to drain it.

entries, err := client.ListBSPOutboxEntries(ctx, db.BSPOutboxQueryFilter{
    OnlyUnresolved: true,
    // BranchIDs: []string{branchID},   // to fan out one ordered reader per branch
}, nil)

var done []string
for _, entry := range entries {
    payload, err := entry.ParsePayload(myValidator) // models.RegisterWithValidator installs macros
    if err != nil {
        continue // a poison entry: log it and leave it unresolved
    }
    switch act := payload.(type) {
    case models.BSPOutboxEmitMessagePayload:
        postToSlack(act.Message)                      // act.Message.ID is the claim check
    case models.BSPOutboxWithdrawMessagePayload:
        takeDownPrompt(act.MessageID)
    case models.BSPOutboxPrepForForkPayload:
        copyMyState(act.ParentBranchID, entry.BranchID, act.ForkSuperstep)
        _ = client.MarkBSPForkPrepared(ctx, entry.BranchID, nil)
    }
    done = append(done, entry.ID)
}

err = client.MarkBSPOutboxEntriesResolved(ctx, done, nil)

Three contract terms, and they are what an application agrees to when it drains:

  1. One ordered reader per creator — or per branch, for an application that wants to fan out. Sequencing and single-reader are the same decision here.
  2. An entry is owed until it is marked, so acting twice is possible — dedupe on the entry ID. A reader that acts and dies before marking will see the entry again. For an EMIT_MESSAGE the message ID inside it is the claim check you have to hold anyway, and a repeated WITHDRAW_MESSAGE is a no-op against a prompt already down.
  3. Ordering is by ID and nothing else. An entry committed by a long transaction can appear behind one with a lower ID that committed sooner, so re-read from the oldest unresolved entry rather than from a high-water mark. The unresolved set is the cursor; there is no other. Entries decided in one transaction come back adjacent and in the order they were written, which is what puts a fork's PREP_FOR_FORK ahead of the asks it must precede.

Marking is idempotent (an entry keeps its first stamp) and creator-scoped into the write: naming an entry belonging to another creator leaves it unstamped rather than failing the batch.

BSP_OUTBOX_ENTRY on the group's subject channel is a wake-up, not the delivery. Missing it costs the delay until your next drain and nothing more, because the act is durable on the table.

External input: inject and reply

An external vertex is one the engine never executes — a human approval, a peer agent, a sub-agent. It is addressed and sent messages like any other vertex; only what happens at delivery differs. Messages from one come back in through the Client, in two shapes:

// Unsolicited: the caller supplies both ends of the address, and its own dedup key.
err = client.InjectBSPInput(ctx, bsp.InjectBSPInputParams{
    GroupID:     groupID,
    From:        "human",            // must be a declared EXTERNAL definition
    To:          "reasoner",         // must be a SINGLETON the engine executes
    MessageType: models.BSPMessageTypeData,
    RequestID:   "user-turn-7",      // the caller's handle, and its dedup key
    Payload:     encodedBody,
    CodecID:     models.CodecIDCBORCoreDet,
}, nil)

// Correlated: no address at all — the cited request determines both ends.
err = client.ReplyToBSPMessage(ctx, bsp.ReplyToBSPMessageParams{
    GroupID:   groupID,
    InReplyTo: messageID,            // the request the engine emitted to the external vertex
    Payload:   encodedBody,
    CodecID:   models.CodecIDCBORCoreDet,
}, nil)

The two shapes exist because their checks are genuinely different. An injection has an address to be wrong about, so both ends are validated: the recipient must be a declared singleton the engine executes (which is what makes acceptance real — a singleton exists on every branch and cannot retire in flight), and the sender must be a declared definition the engine does not execute. That pair of opposite checks on one field is what makes an injection enter the computation rather than run alongside it. A reply supplies only a citation: the message must exist on the live branch, must still be EMITTED, and must have been addressed to the vertex now answering. That EMITTED check doubles as idempotency — a retried reply finds the request CLOSED and is refused as a duplicate rather than delivered twice, which is the one respect in which the correlated path is safer than the unsolicited one.

Both are staged on arrival and become ordinary message rows when the next dispatch admits them. Two consequences worth stating:

  • Only ingress leaves SUSPENDED. A branch at rest wakes on input and on nothing else — but a paused branch waits for a resume, and input injected meanwhile is not lost: the resume's dispatch admits everything staged in the interval before it resolves the frontier.
  • Acceptance can still be lost. The Client checks against a branch the scheduler may since have moved, and re-resolves HEAD when it processes the entry. A rejection there arrives out of band as BSP_INGRESS_REJECTED on notify:subject:bsp:<group-id> — because the call it belongs to already returned successfully.

Branches and forks

A group is a container; a branch is the thing that runs, so the branch is the only object with an execution state machine:

   (forked) ───▶ PREPARING ──▶ CANCELLED   the application could not prepare, or gave up
                 │    awaiting the application's half of the cut
                 ▼
   (created) ──▶ PENDING ──▶ RUNNING ──┬──▶ FAILED             a vertex failed, or delivery did
                    │        ▲   │     ├──▶ PASSED_STEP_LIMIT  no budget left to dispatch
                    │        │   │     └──▶ CANCELLED          the user asked
                    │        │   ▼
                    │        ├ SUSPENDED ──▶ CANCELLED
                    │        │    nothing scheduled; awaiting ingress
                    │        │
                    │        └ PAUSED ─────▶ CANCELLED
                    │             the user stopped it; awaiting resume
                    └──▶ CANCELLED   never launched; the application chose not to start

Three of those are settled — FAILED, PASSED_STEP_LIMIT, CANCELLED — meaning the branch will never run again. SUSPENDED and PAUSED are not settled: between them they are where a healthy group spends most of its life. At most one branch of a group is non-settled, and it is HEAD.

Recovery from a settled branch is a fork, and there are exactly two. Both require a settled parent and a settled HEAD, both create a child, copy a checkpoint into it and repoint HEAD, and they differ in one thing — what the child inherits at its first superstep:

// Re-attempt the superstep that stopped the parent. Takes no boundary: there is nothing to name,
// the fork point being the parent's CurrentSuperstep either way. The child carries what the parent
// was still waiting on an answer to, and re-executes every effect for real on a fresh journal.
err = client.RetryBSPBranch(ctx, parentBranchID, "fork-req-1", metadata, nil)

// Return to a quiet rest point carrying no messages, so the child comes to rest there awaiting new
// input. That whole line of work was wrong.
err = client.RewindBSPBranch(ctx, parentBranchID, boundary, "fork-req-2", metadata, nil)

A rewind boundary must be a quiet rest point — a superstep the branch rested at with nothing outstanding. Resting alone is not enough: a branch blocked on a human's approval reaches an empty frontier by the same check as one that answered its user and is waiting for the next question, and a child inheriting the first without its question would hold an idle vertex nothing could ever schedule again. A refusal names what it found outstanding, and ListBSPSupersteps + ListOutstandingBSPMessages are how a UI builds the list of boundaries it may offer in the first place.

The PREPARING handshake is the part an application must implement. A fork copies the engine's half of a checkpoint and cannot copy yours, so the child is born PREPARING, dispatches nothing, and holds on a PREP_FOR_FORK outbox entry. MarkBSPForkPrepared is what lifts that gate. This applies to a rewind as much as to a retry, even though the child carries no messages — the application's half of the checkpoint is missing either way. The forkRequestID you supply is the handle echoed back in that entry.

A fork request the scheduler refuses (two in flight at once will do it, the first having repointed HEAD at a non-settled child) announces itself as BSP_FORK_REJECTED, for the same reason a rejected injection does: the Client validated and enqueued, so what you would otherwise observe is an absence.

Querying a run (Client)

The same client reads the whole lifecycle, so an application never has to reach into the db package for ordinary work:

// Groups — the filter is db.BSPGroupQueryFilter, reused as-is
groups, err := client.ListBSPGroups(ctx, db.BSPGroupQueryFilter{
    CommonListEntryQueryFilter: db.CommonListEntryQueryFilter{Limit: &limit},
}, nil)
group, err := client.GetBSPGroupByName(ctx, "assistant-session-42", nil)

// Where the run is now: nil when the group has no HEAD yet, which is not an error
head, err := client.GetActiveBSPGroupBranch(ctx, groupID, nil)

// What the run DID: the ledger, in order. `IsRestPoint` + `IsQuiet` is the set REWIND may fork from
isRest, isQuiet := true, true
ledger, err := client.ListBSPSupersteps(ctx, head.ID, db.BSPSuperstepQueryFilter{
    IsRestPoint: &isRest, IsQuiet: &isQuiet,
}, nil)

// One turn, across every vertex — what a UI shows beside the ledger row for that coordinate
states, err := client.ListBSPVertexStatesAtSuperStep(
    ctx, head.ID, 7, db.BSPVertexStateQueryFilter{}, nil,
)

// What the branch is currently holding open to the outside world
open, err := client.ListOpenBSPMessages(ctx, head.ID, nil)

// Delete — only once HEAD has settled
err = client.DeleteBSPGroup(ctx, groupID, nil)

Alongside these, ListBSPVertexDefinitions, ListBSPBranches, GetBSPBranch, GetBSPSuperstep, ListBSPVertices, GetBSPVertex and ListBSPVertexStates cover the rest, and a family of UpdateBSPGroup* / UpdateBSPBranch* / UpdateBSPVertexDefinition* methods edits what a run was declared to be — names, descriptions, metadata, the superstep duration, a definition's retry parameters, timeout and instance cap. Those take nothing away from the scheduler because no scheduler decision reads them. MaxSuperstep is the field that looks like one of these and is not: it bounds a run in flight, so raising it is ExtendBSPGroup. Renaming a vertex definition is refused once the group holds a HEAD branch, the name being the addressing key on columns that carry no foreign key.

The ledger, not the branch row, is what says what the run did. Branch.CurrentSuperstep is the last checkpoint, not the superstep now running — it stands one behind for exactly as long as a superstep is in flight, and a torn superstep leaves it where it was. Every vertex state row names the task that ran it, so that is also where you start from to ask the task engine how a superstep's work actually fared.

Creator scoping. Every read, edit and delete is scoped to the client's creator: a group belonging to another creator is reported as not-found rather than as a permission failure, so the client never discloses one it does not own. Creator is opaque to the engine and the scope is a default that keeps tenants out of each other's view — not a security boundary. It shows up in three shapes here, and the difference is worth knowing:

  • A listing states the creator as a query condition, so another creator's group lists empty.
  • A single-entry read, and every edit, reports not-found.
  • ListBSPSupersteps, GetBSPSuperstep and ListOutstandingBSPMessages authorize through the branch instead — a ledger row has no creator column — which makes ListBSPSupersteps the one listing here that reports not-found rather than listing empty.

A client constructed without a DefaultCreator has no scope to apply, so a ListBSPGroups that does not carry an explicit Creators is rejected with a goutils.BadInputError rather than silently listing every creator's groups. Use db.Database directly if you genuinely need an unscoped view.

Deleting. Only a group whose HEAD has settled may be deleted — cancel a live one first; the refusal is a goutils.ConsistencyError. The delete cascades away every engine row under the group and reaps the tasks that ran its vertices, and it deliberately leaves your vertex state alone, which is why the DELETE_BSP_GROUP event exists: it is the cue for a process that did not issue the delete to reap its own store.

Running the scheduler

Exactly one scheduler runs against a given database — it is the sole writer of branch and vertex state. It needs a task client to dispatch vertex tasks and a notify consumer to receive their results:

scheduler, err := tasking.NewBSPScheduler(
    ctx,
    models.BSPSchedulerConfig{
        MaintenanceTimerIntSecs: 30,
        BranchStallLimitSecs:    300,
        SchedulerQueue:          "bsp-scheduler",
    },
    "task-scheduler", // the TASK scheduler's queue, where vertex tasks are submitted
    dbClient, redisClient, nil /* OnFatal; nil keeps the default: log and terminate */,
)
if err := scheduler.Start(ctx); err != nil { /* ... */ }
defer scheduler.Stop(ctx)

The root helper builds the scheduler's support task client itself, and that is the reason to prefer it: bsp.NewBSPScheduler requires a client whose DefaultCreator is models.BSPExecutionTaskCreator, because the dispatch stamps that creator on every vertex task and the task client's read paths are creator-scoped — a client scoped to anything else reports the engine's own tasks as not-found, which leaves every cancel silently refused while dispatch goes on working. Use bsp.NewBSPScheduler directly when you need to substitute a factory, as tests do.

Start recovers any messages stranded in the scheduler queue buffer, subscribes for vertex task feedback, and starts the serial event consumer and the maintenance timer.

Required deployment wiring — the notify producer must emit creator channels. The scheduler learns every vertex's outcome by subscribing to notify:creator:<engine-creator>. That channel is only populated when the notify producer running against the same database is configured with EmitCreator: true (models.NotificationProducerConfig). If it is false, the subscription receives nothing: every vertex sits in RUNNING until its deadline expires, and the branch holds one position until BranchStallLimitSecs elapses and the maintenance sweep settles it FAILED with a SCHEDULING cause. Treat EmitCreator: true as a hard requirement, not an optimization.

Reliability model (what you can rely on)

  • Self-healing progress. A branch is advanced by IPC pokes and a periodic maintenance sweep that re-scans the database for anything a lost poke would strand — a PENDING branch to dispatch, a barrier to re-check, a standing control request to honour. A dropped message delays progress; it never loses it.
  • Single writer of state. Only the scheduler mutates branch and vertex state, and it does so single-threaded off one serial queue, so there are no intra-engine state races to reason about.
  • At-least-once execution is safe by post-state, not by locking. A vertex's post-state, the attempt that produced it, and its whole outbox land in one transaction, appending rather than replacing; the barrier accepts whichever attempt the vertex state row names, and the Runner refuses to re-run a vertex that already has a post-state.
  • Vertices inherit the task engine's guarantees — per-attempt retry and timeout, crash-safe reliable queues, poison-message quarantine.
  • A torn superstep writes no checkpoint. If any vertex reached FAILED there is no consistency cut to record, so CurrentSuperstep stays where it was and the branch settles FAILED. Both whole and torn supersteps get a ledger row; only a whole one is a checkpoint.
  • No automatic fork. The engine never re-runs a settled branch on its own. Recovery is always a deliberate RETRY or REWIND, which is what keeps crash recovery and user retry structurally distinguishable.
  • Liveness has a backstop. A branch that is poked and does not move for BranchStallLimitSecs is settled FAILED by the sweep, measured from the sweep's own first observation rather than from anything the engine wrote — so it means poked and did not move, not time has passed.

Configuration

  • models.BSPClientConfig — the BSP scheduler's queue name, the client's only IPC target. No retry settings: vertex retry is a per-definition property carried in the spec. It must match the scheduler's SchedulerQueue.
  • models.BSPSchedulerConfig — maintenance interval (≥ 10s), branch stall limit, and the scheduler queue name. The stall limit must be ≥ 60s and at least twice the maintenance interval, so that reaching it implies at least one re-poke was made and then observed to have changed nothing.

A process running all three engines holds three distinct scheduler queues — the task scheduler's, the workflow scheduler's, and the BSP scheduler's. The BSP scheduler dispatches vertex tasks through the task client, so it has no execution-queue mappings of its own: vertex routing lives in the task engine's TaskSchedulerConfig (route __EXECUTE_BSP_VERTEX__ to a queue there).

Notifications

Every group and branch state change is recorded as a durable, creator-tagged SystemEventAudit row in the same transaction as the change. The notify package turns those rows into a best-effort Redis pub/sub stream; this package produces the events and does not broadcast them. Every BSP event — including branch, outbox, ingress and fork events — is routed to its group's subject channel, notify:subject:bsp:<group-id>, so one subscription follows a whole run.

The handful an application actually waits on:

Event Why you care
BSP_OUTBOX_ENTRY The engine owes you an act — drain the outbox
BSP_BRANCH_SUSPENDED The run came to rest; only ingress wakes it
BSP_BRANCH_PAUSED Your pause landed on a written checkpoint
BSP_INGRESS_REJECTED An injection the Client accepted did not survive to the scheduler
BSP_FORK_REJECTED A fork you requested created no child
DELETE_BSP_GROUP Reap your own vertex state for that group

Delivery is best-effort, so treat every one of these as a prompt to go and read durable state rather than as the state itself — which is exactly what the outbox contract already assumes.

Not yet supported

  • Abandon — a vertex saying it no longer wants the answer to a request it sent. models.BSPComputeResult carries no such field, so a speculative fan-out's losing request stays outstanding until its branch settles.
  • Per-vertex retry — RETRY re-runs the whole superstep, not the one vertex that failed.
  • Declared edges as validation/visualization metadata, speculative execution across parallel branches, and sub-agents as a graph construct (a sub-agent is an external entity a vertex calls like a tool, not a member of the calling group's vertex set).

Out of scope by design, per DESIGN.md "Scope and Non-Goals": combiners, partitioning, compensation/undo handlers, general topology mutation, and data-scale graph processing. Multi-tenancy isolation and scheduler leader election, as elsewhere in tasking, belong to the embedding application.