Running workers locally
The local WorkManager runs workers in-process, in a test or a notebook. Workers subscribe to topics on a local bus, their outputs are routed like pubsub, and every event goes through the same per-event rules as on the cluster. A local run is a rehearsal of a deployment: the same worker, the same configuration, the same routing, without a cluster.
It ships in two packages with the same semantics:
- C#:
LocalWorkManagerandWorkerObservables.RuninVirtufin.Behavior.DevKit; - Python:
virtufin.worker_devkit.localinvirtufin-worker-devkit, which needs the[local]extra (reactivex); - TypeScript:
LocalWorkManagerandrunin@virtufin/worker-devkit(async:await wm.publish(...)drains the cascade; see TypeScript workers).
API
C
LocalWorkManager implements IWorkManagerClient (Virtufin.WorkManager.Client),
the contract GatewayWorkManagerClient implements for the cluster: the same
WorkerSpec, the same state model (Loading, Stopped, Running, LoadFailed), the
same operations. A run function written against the interface runs on both.
using System.Reactive.Linq;
using Virtufin.Behavior.DevKit;
using Virtufin.WorkManager.Client;
await using var wm = new LocalWorkManager(new LocalWorkManagerOptions
{
Loaders = EngineWorkerLoaders.Default(), // Virtufin.WorkManager.Engines.Local: worker packages and C# text, in-process
});
// Consumers first, as on the cluster: the bus keeps no history.
wm.Deploy(executor, [submittedTopic], config: executorConfig); // an instance: Create + Start at once
await wm.DeployAsync(new WorkerSpec(CodeSource.Content.Text(strategySource), // the same spec the cluster takes
WorkerMimeTypes.CSharpSource, [candleTopic], strategyConfig, Tags: new() { ["name"] = "breakout" }));
var orders = new List<CloudEvent>();
using var o = wm.Observe(submittedTopic).Subscribe(orders.Add);
using var d = wm.ObserveDeadLetters(candleTopic).Subscribe(dl => Console.WriteLine(dl["dlqerrormessage"]));
await wm.PublishAsync(candleTopic, candles.ToObservable()); // each candle drained before the next
var (positions, etag) = await wm.Api.GetStateAsync("positions", "BTCUSDT"); // what the workers saved
| Member | What it does |
|---|---|
new LocalWorkManager(options?) |
LocalWorkManagerOptions: Loaders (default instances only), MaxCascade (default 10 000), ActorType (the dlqactortype), Logger (also the workers' context.Logger), TimeProvider (dead letters, CreatedAt, triggers, output topics), PlatformVariables (the local cfg.env, see Platform variables), MaxRecordedOutputTopics (default 1000, the Runtime's Runtime:MaxRecordedOutputTopics). |
CreateWorkerAsync(spec) |
Registers the worker and returns its id: spec.Id, or a generated UUID of version 7; a given id that exists fails with ALREADY_EXISTS (ID_EXISTS), and every group of spec.Groups must exist (see Groups, ids and tags). An Instance is Stopped at once; a URL or content source loads through the first accepting loader in the background (Loading → Stopped, or LoadFailed with LocalWorker.LoadError). No accepting loader: NotSupportedException. |
StartWorkerAsync(id) / StopWorkerAsync(id) |
Start calls the worker's StartAsync with its context (Start-before-Process); only a Running worker receives events. A start while Loading takes effect when the load completes; starting a LoadFailed worker throws WorkerLoadFailedException. Stop cancels the worker's stop token and waits for its StopAsync (StopTimeout, 5 s); the instance and its in-memory state stay. |
DeleteWorkerAsync(id) |
Stops the worker, disposes a loader-created instance (never one you passed in), removes it from its groups, deletes its own state (context.State) and handles the triggers it owns: one in no group is deleted, one in a group keeps firing with its owner cleared. A disposal that throws leaves the worker listed (stopped); a repeated delete finishes it. |
LoadCodeAsync(id, code) |
Reload through the loader; completes when loaded. A Running worker is stopped, reloaded and started again on the new code, never reloaded in place. |
InvokeCommandAsync(id, command, payload?, …) |
One command straight through the worker's ProcessAsync (a com.virtufin.workmanager.worker.command event, the command in its command extension), its outputs returned and not published; WorkerNotRunningException unless Running. |
ListWorkersAsync(tagFilters?, group?), GetWorkerAsync(id) |
WorkerDescriptors in creation order (with Groups, OutputTopics, OutputTopicsTruncated); filters are ANDed, group keeps its members; GetWorkerAsync is null for an unknown id. UpdateWorkerTagsAsync(id, set?, remove?) sets and removes in one atomic step; the groups stay. |
DeployAsync(spec), WaitUntilRunningAsync |
The contract's extension methods: Create + Start + wait, with Stop + Delete on failure. |
CreateGroupAsync, GetGroupAsync, ListGroupsAsync, UpdateGroupTagsAsync, SetGroupOwnersAsync, SetGroupScopesAsync, AddToGroupAsync, RemoveFromGroupAsync, DeleteGroupAsync, ResolveGroupOwnersAsync, GroupsCoveringAsync |
The group calls, with the shapes of GatewayWorkManagerClient's: see Groups, ids and tags. |
Deploy(worker, topics, config?, secrets?, name?), Deploy(worker, topics, LocalDeployOptions) |
Create(Instance) + Start, synchronously (the worker's StartAsync runs before it returns); returns the LocalWorker (Id, Name, State, Topics, Config, Tags, SecretNames, VariableReferences, Processed, DeadLettered, ReportedStatus, ReportedDetail). LocalDeployOptions (Config, Secrets, Variables, Name) also takes platform variables by reference; an unknown one throws WorkerVariableNotFoundException (Worker.Host) and nothing is deployed. Remove(localWorker) stops and deletes it. |
Workers |
The workers, in creation order. |
Api |
The LocalVirtufinApi behind the workers' context.Api: read the state they saved (their context.State lives under sys.workmanager.worker.<id>.state.<key>, service workmanager, as on the cluster), observe or publish, list triggers. A worker's context.PublishAsync and its Api publishes go to the bus like its returned outputs, only while the worker is running. |
Observe(topic) / ObserveDeadLetters(topic) |
Every event published to the topic (or its dlq.<topic>) from now on (hot, no history). |
PublishAsync(topic, CloudEvent) / PublishAsync(topic, IObservable<CloudEvent>) |
Publishes one event, or a sequence each drained before the next; completes when the cascade is drained. |
Complete() |
Completes every observer; later publishes fail. DisposeAsync() stops every started worker, disposes loader-created workers, the API and the bus. |
Without topics, worker.Run(inputs, config?, secrets?, api?) or
worker.Run(inputs, LocalRunOptions) (WorkerObservables)
runs one worker over an IObservable<CloudEvent>. It starts the worker once
with a context whose Api is api or a fresh LocalVirtufinApi (and the
config/secrets given), processes one event at a time, in order, under the
same rules, emits every output (and every event the worker publishes through
its context) in wire form with its publishtopic kept, and stops the worker
when the inputs complete or the subscription is disposed. Nothing is routed,
nothing loops back, and a throw ends the sequence with OnError.
LocalRunOptions (Config, Secrets, Variables, PlatformVariables, Api)
also takes platform variables by reference, resolved
from its own PlatformVariables; BehaviorTestHost(worker, LocalRunOptions)
takes the same options.
The workers' API
LocalVirtufinApi is the IVirtufinApi of a local run, with the gateway's
observable semantics:
- State. Etags are versions from
1; etag"0"isInvalidArgument; a save with a stale etag failsAbortedand leaves the value; a missing key isNotFound;GetBulkStatereturns the keys it holds. Every save and delete publishes the Tier 0 event, as the gateway does since api 0.35.0 (sys.api.state.saved/deleted, ce-typecom.virtufin.api.state.*, sourceurn:com.virtufin:api, payloadStateChange {service, store, key, action, etag}, the service as the store, one event per key, not coalesced);publishChangeandincludeValueare ignored. A caller'sChangeNotificationis published next to it, verbatim.QueryStatethrowsNotSupportedException: read keys explicitly. - Pubsub.
PublishEventgoes to the bus. From inside a worker call it is queued at once and delivered before that call's outputs, as on the cluster (the gateway publishes immediately; the Runtime publishes outputs after the call returns).Subscribe(topics)observes from now on (an empty list: the two Tier 0 topics).PublishWithResultcorrelates the reply bycorrelationid; it cannot be awaited from inside a worker call (the reply would arrive only after the call) and throwsInvalidOperationExceptionthere. - Triggers. The api's trigger calls (
ITriggerApi):ScheduleTriggerAsync(request)answers the id (a given canonical UUID, or a generated UUID of version 7), withtags,groupsandowner_worker_id;GetTriggerAsync,ListTriggersAsync(owner, tag filters, group; creation order),UpdateTriggerTagsAsync(atomic, never moves the next firing),AddTriggerToGroupAsync,RemoveTriggerFromGroupAsync,ClearTriggerOwnerAsync,DeleteTriggerAsync.@every <duration>schedules (Go durations:500ms,1s,2m) and due times (a duration or an RFC 3339 time) firecom.virtufin.api.trigger.firedon the target topic from the manager'sTimeProvider;repeatscaps the firings, and after its last firing a trigger is gone. Cron schedules throwNotSupportedException. A standaloneLocalVirtufinApihas no WorkManager, so no group exists for its triggers. - Failures are
RpcExceptions with anErrorInfo(ApiErrors.ErrorInfoOf):INVALID_FIELD,NOT_FOUND,CONFLICTon a stale etag,ID_EXISTS,GROUP_NOT_FOUND,NOT_MEMBER,DELETING. A returned response means success; no response carries a status of its own. - Gateway.
ListServicesis["workmanager"]; the typedInvokethrowsNotSupportedException(the local WorkManager is an object, not a service).
Python
from virtufin.worker_devkit.local import LocalWorkManager
with LocalWorkManager() as wm:
wm.deploy(executor, [submitted_topic], config=executor_config)
wm.deploy(positions, [submitted_topic, filled_topic], config=positions_config)
wm.deploy(strategy_module, [candle_topic], config=strategy_config)
orders = []
wm.observe(submitted_topic).subscribe(orders.append)
wm.observe_dead_letters(candle_topic).subscribe(print)
wm.publish(candle_topic, candles) # synchronous; a list, an Observable or one dict
The Python API mirrors the C# one in snake case: deploy, remove,
workers, observe, observe_dead_letters, publish, complete, close,
and a context manager. deploy accepts a WorkerBase, a Process(event)
function or a module that defines Process, which is the same entry point the
cluster's Python engine calls. publish is synchronous: it returns once the
cascade is drained. Events are the dicts a Python worker sees on the cluster.
run(worker, inputs, config, secrets, *, variables=None, platform_variables=None) returns an Observable of output dicts.
Install it with pip install 'virtufin-worker-devkit[local]'. Deployed
workers do not need reactivex.
start(worker) and stop(worker) mirror StartWorkerAsync/StopWorkerAsync
(deploy starts, remove stops and deletes the worker's state). A worker
module may define Start(ctx) and Stop() next to Process, which the
cluster's Python engine calls the same way:
import threading
def Start(ctx): # before the first event
ctx.report_status("connected", ctx.config.get("venue"))
def loop():
while not ctx.stopping.is_set(): # set by stop/remove, before Stop()
ctx.publish({"type": "com.example.tick", "source": "urn:ticker", "data": "{}"})
ctx.stopping.wait(1.0)
threading.Thread(target=loop, daemon=True).start()
def Stop(): # after the last event; ctx.publish now raises HostRefused
pass
ctx (virtufin.worker_devkit.context) has worker_id, config, secrets,
variables, stopping, publish(event_or_list) (routed like a returned output, from any
thread; an event with neither publishtopic nor type is dropped),
report_status(state, detail=None) (kept in LocalWorker.statuses), state
(get, save with an optional etag, delete, keys; in memory here, the
worker's own State on the cluster) and get_secrets(). A refused call raises
HostRefused, a stale etag StateConflict (both RuntimeError), a state
value containing a secret ValueError. A stopped worker receives nothing.
The package also exposes the pieces underneath: wire, the protobuf codec of
the Python engine, and event_rules, the per-event rules as a Python worker
sees them.
Platform variables
A worker on the cluster gets settings shared by the whole context (a region,
a venue's base URL) by reference from the context's platform variables,
the state key cfg.env (WorkManager 0.55.0,
Worker variables).
The local WorkManager resolves the same references from a dictionary you give
it, the local cfg.env:
| C# | Python | TypeScript | |
|---|---|---|---|
| The platform variables (name -> value) | LocalWorkManagerOptions.PlatformVariables |
LocalWorkManager(platform_variables=...) |
new LocalWorkManager({ platformVariables }) |
| A worker's references (attribute -> variable name) | WorkerSpec.Variables, LocalDeployOptions.Variables |
deploy(..., variables=...) |
deploy(w, topics, { variables }) |
| The references, never the values | LocalWorker.VariableReferences, WorkerDescriptor.Variables |
LocalWorker.variable_references |
LocalWorker.variableReferences |
| What the worker sees | context.Variables |
ctx.variables |
ctx.variables |
| An unknown variable | the load fails: LoadFailed, LoadError platform variable 'NAME' not found |
deploy raises PlatformVariableNotFound |
deploy rejects with PlatformVariableNotFound |
As on the cluster, the references are resolved when the worker loads (C#) or is deployed (Python, TypeScript), where an unknown name fails with an error naming it, and again on every start: a value changed in the dictionary reaches the worker at its next start, never mid-activation, and a variable removed since makes the start fail. The values are stamped over every input as CloudEvent attributes, over the event's own, and stripped from every output and host publish, like secrets. Unlike secrets, a state value may contain a variable's value.
The shortcuts that run a worker without a manager take both the references and the platform variables, resolved by the same code:
| C# | Python | TypeScript | |
|---|---|---|---|
| One worker over its inputs | worker.Run(inputs, new LocalRunOptions { Variables, PlatformVariables }) |
run(worker, inputs, variables=..., platform_variables=...) |
run(worker, inputs, { variables, platformVariables }) |
| A test host | new BehaviorTestHost(worker, new LocalRunOptions { Variables, PlatformVariables }) |
||
| An unknown variable | Run throws WorkerVariableNotFoundException, a later subscription ends with OnError; the host's start throws |
run raises PlatformVariableNotFound |
the run throws PlatformVariableNotFound before the first event |
Run and BehaviorTestHost start the worker, so it reads context.Variables;
Python's and TypeScript's run do not start it, so the worker reads the
attributes on its inputs.
Semantics
These are the Runtime's rules, applied by the same code (C#) or pinned by the same conformance vectors (Python):
- Codec bytes on the bus. Every event crosses the bus as CloudEvents protobuf bytes and is decoded for each receiver. A worker sees what the codec carries, and one receiver's changes never reach another.
- Config validation (0.42.2, WorkManager 0.38.3). A config key that can
never reach the worker is refused when the worker is created or deployed
(
ArgumentExceptionin C#,ValueErrorin Python,TypeErrorin TypeScript, naming the key), asCreateWorkerrefuses it: config travels as CloudEvent attributes, so a key is lower-case letters and digits (strategyid, notstrategy_id), notdata,timeordataschema, and not an attribute every input carries (id,source,specversion,type,datacontenttype). - Reference validation (0.53.0, WorkManager 0.56.0). Secret and variable
names are checked next, in
CreateWorker's order and with its messages (C#WorkerReferenceRulesin Worker.Host, Pythonreference_rules, TypeScriptreferenceRules): first every secret, then every variable. A name is 1-20 lower-case letters or digits, not reserved (id,source,type,correlationid,replytopic,publishtopic,traceparentand the other core attributes), and not also a config key; a variable name is not also a secret name, and its reference is a platform variable name ([A-Za-z_][A-Za-z0-9_]*). A local secret is its value, not a key of the worker secret, so only its name is checked. The managers' create and deploy and every shortcut (Run,BehaviorTestHost, Python's and TypeScript'srun) refuse a broken name (ArgumentException,ValueError,TypeError) with the exact message, for examplevariable name 'region' is also a config key. - Input rules. A missing
datacontenttypebecomesapplication/json. The worker's config fills the attributes the event leaves out, and the event's own attributes win. The worker's secrets and platform variables are set over everything. - Output rules. An output without an id gets a fresh one. In C#, an output without a source gets the input's. Secret and platform variable attributes are stripped.
- Routing. An output goes to its
publishtopic(removed from the published event), else to itsce-type. In C#, an output with neither is logged and skipped. A Python output without a type goes to the topicunknown, and one without a source getsurn:unknown, as on the cluster's Python engine. - Failures. A throw dead-letters the original event, as it was on the
bus, once to
dlq.<topic>. The dead letter carriesdlqworkerid,dlqactortype,dlqerrortype,dlqerrormessage(at most 1024 characters) anddlqfailedtime. The worker carries on with the next event. A Python worker's exception is reported asSystem.InvalidOperationExceptionwithstr(exception), as the Python engine reports it. - Workers. C# workers are called through
IWorker.ProcessAsync(input, context)with the manager's API in the context, and every output is published in order. Python workers returnNone, a dict, or a list of dicts.
The vectors are conformance/worker-event-rules.v1.json. workmanager owns
them and ships them in the Virtufin.Worker.Host package. worker-devkit keeps
a byte-identical copy, and a test fails when the copy drifts from the pinned
package. The C#, Python and TypeScript test suites run every vector, the
platform variable vectors (an unknown variable fails the load with exactly
platform variable 'NAME' not found) and the reference validation cases
included, and the lifecycle vectors (start before the first event, host publishes
routed like outputs, the stop signal before Stop, nothing after it; a local
host never loses ownership, so a lost lease is a stop).
A per-event vector whose names CreateWorker refuses (secret-wins-over-config,
a secret named like a config key) is refused by the local managers the same way,
and its per-event rule is checked on the rules alone.
Ordering
The local bus is deterministic. There is one global FIFO. Each external
publish is drained completely, breadth-first, before the next one starts. On
each event, the observers of its topic see it first, then the subscribed
workers in deploy order. A publish from inside the cascade (from a worker or
an observer) is queued, never run recursively. MaxCascade (max_cascade)
caps the events one publish may cause. Beyond the cap the publish fails,
which catches a worker whose output reaches its own input topic.
sequenceDiagram
autonumber
participant NB as Notebook
participant Bus as Local bus (FIFO)
participant S as Strategy
participant E as SimulatedExecutor
participant P as FillPositions
NB->>Bus: candle 1
Bus->>S: candle 1
S-->>Bus: order submitted
Bus->>E: order submitted
Bus->>P: order submitted
E-->>Bus: order filled
Bus->>P: order filled
P-->>Bus: position
Bus->>S: position
Note over NB,P: candle 1's cascade is drained before candle 2
NB->>Bus: candle 2
Bus->>S: candle 2 (the strategy already knows its position)
Note over NB,P: On the cluster nothing waits: a replay pauses after<br/>each candle that ordered until its position arrives
On the cluster, workers run concurrently and pubsub does not wait for a cascade. A replay that is compared with a local run has to pace itself: after each candle on which the local run ordered, wait for that candle's position event before publishing the next candle.
Claim shards
A worker created with a claim shard (WorkerSpec.Shard with ShardMode
WorkerShardMode.Claim or ClaimRetry and ClaimTtlSeconds in C#;
deploy(..., shard=, shard_mode=ShardMode.SHARD_MODE_CLAIM_RETRY,
claim_ttl_seconds=) in Python) competes with the other members for every event,
with the cluster's rules (claim mode):
- Settings. The combinations the WorkManager refuses are refused here, with its
messages (
ArgumentException/ValueError); a member whose mode or claim TTL differs from a running member's is refused at create and start (InvalidOperationException/RuntimeError). - Claims. A member claims an event when it is delivered; only the winner
processes it. Locally the members are served in creation order, so the first
running member wins every free event. The claims are kept in memory and expire on
the manager's clock (
LocalWorkManagerOptions.TimeProvider, Python'sclock). - Losers. In claim mode they drop the event. In claim retry mode they park it
and retry it once the claim has expired: a done event is dropped, a live claim
parks it again, an expired one is claimed and processed. The C# manager retries
on a timer of its
TimeProvider; the Python manager retries when apublishstarts and onretry_parked(), so a run on a simulated clock calls it after moving the clock. - Done and dying winners. The winner marks its event done after every finished turn, a failed one too. A turn whose worker is stopped while it runs is unfinished (nothing is published, no done marker), so in claim retry mode another member takes the event over after the claim TTL.
- Overflow. At
claim_max_parked(default 10,000) the oldest parked event is dropped and recorded inLocalWorker.Gaps(Pythonworker.gaps), where the cluster publishes agaplifecycle event. - Commands are never claimed:
InvokeCommandAsyncin C#, and in Python a worker's own command topic (deploy it onwrk.<type>.command.{worker_id}). ListWorkersAsync(C#) and the worker'sshard_mode,claim_ttl_secondsandclaim_max_parked(Python) report the mode asListWorkersdoes.
The shared vectors conformance/shard-claims.v1.json (from Virtufin.Worker.Host)
pin these rules for the C# and the Python managers and the Runtime.
Groups, ids and tags
The local WorkManagers keep groups, membership, ids and tags by the released
WorkManager's and api's rules (openspec item-identity, resource-groups,
write-results), so a script that builds and tears down groups behaves the same
locally and on a cluster:
- Ids. Workers, triggers and groups get a generated UUID of version 7
(
Ids.NewId,new_id,newId) unless the caller gives one; a given id must be a canonical UUID (lower case, hyphenated;INVALID_ARGUMENT,INVALID_FIELD, fieldid) and one that exists fails withALREADY_EXISTS(ID_EXISTS). Ids found again by rule are version 5 (DerivedId,derived_id,derivedId). - Tags.
UpdateWorkerTags,UpdateTriggerTagsandUpdateGroupTagsset and remove keys in one step; a key both set and removed is refused (INVALID_FIELD, fieldremove). Lists filter by exact tags, all of which must match. - Groups. Several parents per group, each existing, never a cycle
(
FAILED_PRECONDITION,CYCLE); owners resolved over every ancestor (ResolveGroupOwners); scopes (name prefixes ending with.), not inherited, resolved byGroupsCovering. Workers and triggers belong to any number of groups;AddToGroupandRemoveFromGroupchange membership atomically per item and never delete anything. - Deleting a group. The group is marked deleting; every member loses this
membership, and the removal that takes a member's last group decides: that
member is deleted (a worker stopped and deleted, a trigger deleted), a member
still in another group is kept. A child group needs
recursive(elseFAILED_PRECONDITIONnaming the first child); a child with another parent is kept, members and all. The answer lists every member asDELETED,KEPT(with its remaining groups) orFAILED. When a member fails, the call fails withABORTED(PARTIAL_FAILURE), the group stays deleting (it takes no new members:DELETING) and a repeatedDeleteGroupfinishes the work. - Owned triggers. Deleting a worker deletes the triggers it owns that are in no group; one in a group keeps firing with its owner cleared.
- Recorded output topics. Each worker's distinct output topics (returned outputs and host publishes, not dead letters), with the time of the first publish, at most 1000 by default; past it the record is marked truncated.
| C# | Python | TypeScript | |
|---|---|---|---|
| Workers | CreateWorkerAsync(spec with { Id, Groups }), GetWorkerAsync, ListWorkersAsync(tagFilters, group), UpdateWorkerTagsAsync, DeleteWorkerAsync |
deploy(..., id=, tags=, groups=), get_worker, list_workers(tag_filters, group), update_worker_tags, delete_worker |
deploy(w, topics, { id, tags, groups }), getWorker, listWorkers(tagFilters, group), updateWorkerTags, deleteWorker |
| Groups | CreateGroupAsync(GroupSpec), GetGroupAsync, ListGroupsAsync(parent, tagFilters), UpdateGroupTagsAsync, SetGroupOwnersAsync, SetGroupScopesAsync, AddToGroupAsync/RemoveFromGroupAsync(group, GroupMembers), DeleteGroupAsync(id, recursive), ResolveGroupOwnersAsync, GroupsCoveringAsync |
create_group, get_group, list_groups, update_group_tags, set_group_owners, set_group_scopes, add_to_group/remove_from_group(group, workers, triggers, groups), delete_group(id, recursive), resolve_group_owners, groups_covering |
createGroup, getGroup, listGroups, updateGroupTags, setGroupOwners, setGroupScopes, addToGroup/removeFromGroup(group, members), deleteGroup(id, recursive), resolveGroupOwners, groupsCovering |
| Triggers | wm.Api: ScheduleTriggerAsync(request), GetTriggerAsync, ListTriggersAsync, UpdateTriggerTagsAsync, AddTriggerToGroupAsync, RemoveTriggerFromGroupAsync, ClearTriggerOwnerAsync, DeleteTriggerAsync |
schedule_trigger(target_topic, id=, schedule=, due_time=, repeats=, owner_worker_id=, tags=, groups=), get_trigger, list_triggers, update_trigger_tags, add_trigger_to_group, remove_trigger_from_group, clear_trigger_owner, delete_trigger; due triggers fire when a publish starts and on fire_due_triggers() |
scheduleTrigger(targetTopic, opts), getTrigger, listTriggers, updateTriggerTags, addTriggerToGroup, removeTriggerFromGroup, clearTriggerOwner, deleteTrigger; due triggers fire when a publish starts and on fireDueTriggers() |
| Output topics | WorkerDescriptor.OutputTopics, OutputTopicsTruncated; option MaxRecordedOutputTopics |
output_topics, output_topics_truncated; max_recorded_output_topics= |
outputTopics, outputTopicsTruncated; option maxRecordedOutputTopics |
| A failure | WorkManager calls: GatewayInvokeException (Status, Error.Reason/Field/Resource) as GatewayWorkManagerClient throws it, WorkerNotFoundException for a call on an unknown worker; a failed DeleteGroupAsync carries its DeleteGroupResponse in Data[LocalWorkManager.DeleteGroupOutcomesKey]. Trigger calls: RpcException with ErrorInfoOf() |
virtufin.api.errors.ApiError (code(), reason, field, resource); a failed delete_group carries ApiError.detail(DeleteGroupResponse) |
a ConnectError read by @virtufin/api's errorInfo(err); a failed deleteGroup carries errorDetail(info, DeleteGroupResponseSchema) |
The local managers publish no group, trigger or worker lifecycle events.
Shared vectors. conformance/groups.v1.json (format virtufin.groups)
pins these rules: ids, tags, parents and cycles, owners and scopes, worker and
trigger membership, deletion with shared, nested and owned members, and a
resumable deletion. The C# (GroupConformanceTests), Python
(test_group_conformance.py) and TypeScript (groupConformance.test.ts) local
managers run every case. scripts/run-group-vectors.py runs the cases marked
for deployed hosts against a WorkManager behind a gateway:
set -a; . ~/.env; set +a
export UV_INDEX_VIRTUFIN_REGISTRY_USERNAME="$VIRTUFIN_REGISTRY_USER" UV_INDEX_VIRTUFIN_REGISTRY_PASSWORD="$VIRTUFIN_REGISTRY_TOKEN"
uv run scripts/run-group-vectors.py --host localhost --port 5002 # deploy-local
It creates its items under fresh ids and deletes them again. Against api 0.34.0
one step still fails: DeleteTrigger of a trigger that no longer exists answers
OK instead of NOT_FOUND (daprd's DeleteJob succeeds for a missing job). The
local managers answer NOT_FOUND, as the api's contract says.
What it does not emulate
The local WorkManager is a rehearsal, not a simulation of the infrastructure. These differences are deliberate:
- Redelivery. Locally, every event is delivered exactly once. Pubsub can redeliver after a timeout or a restart.
- Batching. The Runtime publishes a worker's outputs in batches. Locally, each output is queued on its own, in the same order.
- Backpressure. There is no bounded inbox, and a slow worker never falls behind. A cascade runs to the end before the next external event.
- The tail race on deploy. A cluster worker subscribes from the tail, so events published while it is being created can be missed. Locally, a start takes effect at once (an instance) or as soon as its load completes. On the cluster, deploy consumers first and wait for the subscription before publishing.
- Slot shards. A
WorkerShardMode.Slotshard's settings are validated, but every member receives every event: the slot split is the Runtime's. - Reload state resets. The Runtime reloads a worker when a newer library is released, and the worker's in-memory state starts fresh. A local worker keeps its state until it is deleted or its code is reloaded.
- Isolation and secrets. Workers share the notebook's process and
assemblies; secrets are plain attribute values; the API is in-memory, so
state does not survive the manager, and
QueryStateis unavailable. - The dead letter's error type. Locally,
dlqerrortypeis the worker's own exception type. On the cluster, the failure crosses the Dapr actor call first, so the deployed Runtime often reports the transport's exception type instead (see dead letters).dlqactortypeisLocalWorkManagerinstead of the engine's actor type.
See the worker workflow for where a local run fits between unit tests and a deployment.
How a local run compares with the cluster, step by step: Local runs and the cluster.