Architecture Reference
Dense per-symbol fact-sheet for AI assistants and operators who prefer reference style. For narrative and design rationale, see Architecture. Source paths and symbol names identify the implementation; line numbers are navigation hints and may move as code changes.
This file is intentionally dense. If you find a stale fact, fix it inline rather than working around it. The AGENTS.md "Documentation" section requires updates here when architectural shape changes.
Components
-
Native audio result finalization (initiative):
MusicEditAPI._drainandSeparationAPI._drainclose the metadata receiver after the render manifest but wait on the accepted entry'sreturn_settledevent before finalizing the command. Verified WAV custody plus drained reverse ACK (every role for stems) releases successful tasks. Failure/cancellation releases that wait only after cancellation submission has been attempted; the separatecancel_submittedfence preventsTaskFinishedfrom racingTaskCancelled. Metadata ordering alone never deletes a live worker output producer. -
Source-separation native boundary (initiative):
shared/types/audio_separation.pyis the strict standalone source/four-stem and private process protocol; its WAV validator bounds encoded/decoded geometry and rejects malformed/nonfinite input.worker/runner/demucs/process.pyowns one isolated native job, bounded progress/result JSON, complete file verification, process-tree cancellation and partial-output cleanup.packaging/skulk-demucs/contains the offline-loading FP32 HTDemucs adapter. Itscontracts.pylink must become ordinary canonical contract bytes in a native wheel. Four aligned PCM24 stereo WAVs share one gain; process RSS and device allocator peaks stay separate.build_wheel.pyseals clean source revisions, complete platform dependency locks and apython.json-pinned standalone interpreter into reproducible candidates.verify_package.pytests fresh offline installation and expanded-tree integrity against sealed wheel bytes. Three-platform CI exercises installed CPU packages; these tools do not provide production cache reuse or accelerator qualification. No mount/bootstrap, placement, engine inventory or REST route is registered yet. -
Resident native separator (initiative):
worker/runner/demucs/resident.pyowns an isolated--servelifetime with an inherited filesystem fence. Actual pinned weights and complete model placement precede readiness; returned installed payload/weight identities and fixed device/thread policy must match the owner. Serial correlated requests reuse the model; private records are bounded at 16 KiB, progress replaceable, terminal queue separate. Absolute deadlines cover writes, execution and independent complete-file verification. Failure/cancel drains the whole group before incomplete-job cleanup/fence release; incomplete drain retains ownership for retry. Completed files/originals survive. Idle liveness checks withdraw stale readiness. Worker activation, inventory and resource admission remain unwired. Candidate CI proves actual sealed CPU reuse, cancel/reload and parent-death inherited fencing, not music quality or 120-second production memory fit. Warm load time is zero; native RSS is the process lifetime high-water mark rather than a per-job measurement. -
Native separation package integrity (initiative):
provisioning/demucs_package.pyowns shared strict package/interpreter contracts, offline bootstrap with an injected command runner, cooperative verification checkpoints and cached source/Python/venv/import integrity. Standalonepackage_inputs.pylinks that same source; Core never imports private build tools. Mutable receipts are not authorities. Cache orchestration, device probing and ready capacity are not registered by these helpers. -
Native installer supervision (initiative):
provisioning/native_install_process.pyimplements the bootstrap command runner. A standard-library-only_native_install_guard.pystarts each command in its private session, reports completion on a four-byte pipe, retains an optional inherited build lock and kills the group on controller death. Its caught TERM handler survives graceful drain until KILL, preserving the watcher/lock if the controller dies during shutdown; command exec resets it. Non-reaping observation keeps the session leader owned until every descendant is drained. Failed cleanup retains the original process handle fordrain()retry and blocks further commands;quiescentauthorizes cleanup of new incomplete files. Each stream is capped at 128 KiB, each runner at 32 commands, logs are private, and owner cancellation plus per-command deadlines remain active. Frozen Core explicitly supplies a verified guardian Python; freezer hook/spec data retain actual guardian source outside PYZ. Native CI exercises process, lock, parent loss and packaging closure on all three architectures. Production cache orchestration and readiness are still unregistered. The package facade uses lazy exports with unchanged static signatures and backing objects; cold helper imports cannot initialize unrelated provisioners. -
Native separation cache (initiative):
provisioning/demucs_runtime.pydefines exact CPUDemucsWheelpins and the ownedDemucsRuntimeCache. OS/libc/CPU eligibility and whole-object/payload/platform agreement precede any interpreter execution. A cache-wide reservation fence and per-build fence serialize installation; the guardian inherits the reservation. Stable UUID generations, full cached-byte verification, offline bootstrap and a closed CPU/MPS FP32 probe precede fsynced atomic selection. Old generations survive repair; only newly owned unactivated output is cleaned after actual drain. Retained cleanup handles survive failures for explicit retry/close. A persistentpublished/<uuid>deletion-protection marker is synced before selection; it is never an integrity authority. Retry drains before reacquiring the global fence and checks this history even if selection vanished. Close waits at most five seconds for another preparation and retains cleanup on timeout. Raw transport reads each checkpoint cancellation/total deadlines. Bounds include a 10 GiB host free-space reserve, a 16-generation limit, exact streamed download size/hash, a default 30-minute total preparation budget (at most two hours), and a 300-second cold library/device probe bound. This is library preparation, not loaded-model readiness. Worker/task/inventory registration and CUDA/ROCm profiles remain unconnected. -
Protected runtime files:
utils/runtime_files.pyowns private-directory, bounded private-read, fsynced atomic-write and inherited file-lock helpers.extensions/runtime_files.pyreexports the same objects for existing callers; provisioning does not import the plugin subsystem to acquire a file fence. -
Native separation preparation ownership (initiative):
provisioning/demucs_manager.pyretains one cache and fixed package/host inventory, serializes finite-budget preparation and exposes only verified library builds plus private exact-runtime lookup. Revalidation/shutdown withdraw observations; no cache generation with publication history is evicted.worker/demucs_preparation.pybounds requests to four, runs effects off-loop, joins cancellation/shutdown before cache close and retains failed cleanup. Shared-executor queue time consumes the absolute deadline; expired work starts no native preparation effects. No event handler or resource provider is registered by these components. -
Native separation model and source ownership (initiative):
worker/runner/demucs/model.pychecks complete rank-zero placement, stamped build/device/policy and nested loader root before explicit real resident load. Current process liveness governs readiness; every source is remeasured before inference. Private command-derived result paths never enter State.worker/separation_sources.pyreuses raw media assembly for at most four private original copies, including already verified waiting/running input. Full encoded hash and WAV facts precede acknowledgement. Unknown/terminal admission fails; cleanup failure keeps its slot/fence for retry. Drain readers before close. Prior/unknown root entries count against the same four slots after restart; bounded overflow refuses without deleting/following foreign entries. Startup reconciliation requires ownership and prior reader drain. The receiver must correlate authoritative State/owner/placement; no bootstrap, transport receiver or HTTP route is registered here. -
Native separation card reader:
shared/models/separation.pyowns frozenSeparationCardConfig;ModelTask.AudioSeparationrequires[separation]. One SHA-256-identified safetensors object, ordered stems and native geometry must agree with the artifact bundle and transformer depth/width. The model catalog projects this metadata separately from speech/music. Reader metadata does not establish loaded-model readiness. -
Separation execution foundation (initiative): frozen
AudioSeparationcommand/task variants carry only model/source metadata.SeparationChunkcarries one complete four-stem manifest or failure, never WAV bytes.master/main.py::separation_generation_instancesadmits one active job per ready complete single-host rank-zero model. Master-local reservations survive consecutive command iterations until indexed task creation transfers admission to State.shared/models/separation_runtime.pybinds exact tensor/constructor identity, explicit CPU/MPS/CUDA/ROCm spelling, FP32, two threads and a 7.8-second window.BaseShardMetadata.separation_policybinds that policy to admission; absent or changed policy fails the worker guard. Ordinary/exact placement require live verified backend/build resources and the full 120-second workload reservation, not just tensor size. The CPU lane uses system RAM, not unrelated VRAM; complete native assignment construction bypasses the text-layer allocator after workload admission.provisioning/demucs_inventory.pypins separate CPU objects for Mac ARM64, Linux amd64 and Linux ARM64; the Mac package can explicitly probe MPS. GPU dependency and memory profiles remain required. The 3 GiB planning floor is an engine/workload reference, not a model requirement or qualification gate. Installability is not readiness. No preparation/runner/backend activation is registered here. Upgrade every isolated participant before enabling these new replicated variants; older ordered-event readers cannot consume them. -
Native original-input handshake (initiative):
worker/separation_input.pyusesVISION_MEDIAwith the explicit rawseparation_sourcerole; only that role accepts the newrequestedframe. The selected worker resolves its actual complete local rank-zero task before requesting bytes from the owning API. Unknown/terminal/nonlocal/ambiguous or changed assignments cannot admit input. Open/chunk/completion can reorder; independent full WAV verification and current task identity precede ACK and acknowledged readiness. Four input slots, 180-second transfer deadline, two-second request retry until open and bounded sends apply. Cancellation joins file threads, preventing late writers/ACKs. Drain actual resident readers before release/close; failed deletion remains owned. No bytes/paths in State. The Worker lazily creates this owner for admitted tasks and routes the raw role independently of vision/reference input. Planning requires its ready command snapshot. Unowned interrupted jobs fail on state recovery; terminal State cannot authorize source deletion while a reader fence is held. Shutdown detaches service ownership without deleting live originals. The API now serves the addressed original request after actual placement. Upgrade isolated media readers before enabling it. -
Native runner adapter (initiative):
worker/runner/demucs/runner.pysupplies the shared dispatcher with an already validated resident binding. One active/four queued tasks; real load/warmup precedes Ready. Only complete metadata enters output chunks. Cancel drains before serial reload; shutdown cancels reload. Failed reload/liveness withdraws Ready even after final-waiter cancellation, without retroactively failing a verified complete render. Private bootstrap context and background exact-runtime revalidation connect this adapter to Worker supervisors without blocking unrelated planning. First-mount weights resolve only at LoadModel. The exact card permits a contained, installed-card-matched canonical Store-index location when staging is disabled, including bundle-qualified directory names. Tombstoned aliases, mismatched cards and escaping index paths do not gain a candidate. Store-owned paths are read-only in completion/discovery. Download cache deletion independently permits only the default model directory and its descendants or an actual downloader node-cache descendant, even for a stale writable status. Local Store ownership always overrides cache classification; shared/external roots stay protected on non-Store workers. Canonical removal belongs to the indexed Store lifecycle. Default and staged caches remain deletable. Worker Store-direct separator preflight passes the same exact card before runner dispatch. Signed identity checks also guard default/staging fallbacks; staged Worker metadata adoption retains its existing current-catalog proof. Index lookup defaults off; exact loaders explicitly opt in. Both coordinator completion probes and the Worker shortcut allow canonical separator reuse only with staging disabled, including offline cached operation. The coordinator reads the actual downloader's staging policy. Staged/cardless consumers retain their normal transfer and current-catalog adoption paths. Startup-completion candidates must already match a loader-discoverable copy or the Store-direct policy; complete bytes alone do not skip staging. -
Native result producer (initiative):
worker/separation_output.pyverifies fixed private WAVs and emits bounded four-role OUTPUT_MEDIA frames. At most four result sets are retained through sender drain, exact reverse ACKs and cleanup success. Total delivery/ACK deadline is five minutes; sends are capped at five seconds. Original slots remain reserved through result settlement. A role's ACK precedes emission of the next role. API reverse control drains independently of the media consumer: four jobs, at most four role ACKs plus one cancellation drain per job, with admission retained until sender join and completion gated on admitted role ACKs. The API wires separation to_send_separation_output_terminal: raw sender admission propagates channel failures and caller cancellation/deadlines. The legacy best-effort terminal helper remains on video/music paths. Replayed completion terminals require DATA-manifest verification before an ACK can be resent; receipt recording also retries settlement when earlier ACK tasks have drained. Typed subscriber predicates admit separation forward packets only to APIs and reverse control only to Workers before their rendezvous queues, avoiding same-node ACK reentrancy without buffering additional audio. Legacy video/music subscriber admission is unchanged. Foreign content and failed deletion remain owned; no recursive deletion or packet-provided file paths. Nativeresult_custody.pypersists a private directory inode receipt before inference; stale source recovery requires reader drain and exact result ownership before deleting known files. Unknown files, symlinks or changed inodes keep their quota. The child process has umask 0077; Core's global umask and sealed package bytes are unchanged. -
Separation HTTP owner (initiative):
api/separation_api.pyregisters six operations at/v1/audio/separationsusing existing API authentication andapi/types/separation.pypublic projections. Metadata-only commands use normal DATA queue ordering and cancellation. Original WAVs follow directed requests from the authoritative placed worker; results follow four OUTPUT_MEDIA roles. Input is one WAV plus closed request JSON; four uploads/active jobs, 64 MiB original, 180-second upload/transfer budgets. Four verified stems plus render completion are required; complete results have 24-hour retention within 2 GiB and 64 records. Eight descriptor-leased downloads survive concurrent deletion. Restart verifies complete sets, fails interrupted jobs and never replays edits. Local paths/bytes never enter replicated State. Full installed acceptance and normal publication are still release gates. -
Separation job lifecycle component:
api/separation_jobs.pypersists source-bound metadata only, with four active/64 retained jobs and a 1 MiB index ceiling. A lifetime OS fence and in-process lock serialize ownership. Durable transitions precede acknowledgment; uncertain writes fence all access until reopen. Interrupted jobs fail on restart. Completion requires one fixed authoritative worker/source manifest, terminal render success and all four locally verified stem receipts, retaining their earliest expiry.outputis absent before completion; content handlers must enforce the same gate. Cancellation/failure cannot be revived by late frames. Unexpired complete records are never evicted for admission. HTTP/worker/media execution wiring is still absent.shared/types/audio_separation.py::stem_from_wavindependently measures a complete bounded PCM24 stereo WAV's digest, geometry and signed-sample peak. It shares the input container parser without native dependencies; large scans belong off-loop. Native result verification compares every measured stem fact. Silence is a valid estimated stem and is not a musical-quality diagnosis.api/separation_media.pyowns separate private four-role WAV assemblers under a lifetime fence, four active jobs/64 retained sets, 64 MiB per stem and 256 MiB per set. Filesystem headroom deducts every role's outstanding unwritten promises, including reordered chunks, without charging written bytes twice. Closed independent facts, synced bytes, job/role directories and newly created storage-root links precede receipts. Failed first-time setup removes only new empty directories under its fence, so retry repeats the ancestor syncs; committed-but-incomplete sets hold an active-job slot until completion or deletion; only a durable completed manifest exposes content. Restart adopts all four exact files or none, and invalid partial sets delete only owned API copies.OUTPUT_MEDIAaddsseparation_drums/bass/other/vocals; the existing video/music handler refuses these roles without mutating either job family. -
Client-owned continuation (experimental):
api/inference_continuation.pydefines strict public proof/receipt data; no caller keys or provider state.Skulk-Continuation-Proofon/v1/chat/completionsbinds the exact HTTP body to a fresh client proof.inference.chatlinks the continuation descriptor to an exact v2 chat callable in the same actual provider instance. The capability independently verifies current registered-client authority./v1/chat/continuation/receiptuses a distinct signed lookup domain and empty provider input. Semantic receipts require transport completion before HTTP publication. No inference retry, implicit new context or destination migration. Receipt half-close/collection/cleanup transport failures become fixed 503 uncertainty, under a 30-second lookup deadline. Iterator close and provider cancellation each have a three-second cleanup bound; cancellation is attempted even if iterator close fails. Caller task cancellation is not converted to 503. Streaming is bounded per frame; collected JSON alone has an aggregate guard.dashboard-react/src/store/chatContinuation.tsowns nonextractable Ed25519 browser keys in IndexedDB, canonical client proofs and public fingerprints.ChatContinuationControlsexplicitly imports owner public enrollment and recovers receipts.Conversation.continuationcontains public scope/receipts and a durable pending fence;ChatMessage.continuationMessagesretains exact public tool/assistant turns separately from display trimming. Missing receipt, missing history or changed destination never triggers automatic replay/reset.store/chatCoordination.tsowns browser Web Locks, changed-field CAS writes and authoritative versioned IndexedDBskulk-chat-history-v2snapshots. Theskulk-chat-v2localStorage mirror is a bootstrap cache only; first migration reads legacy history. Committed revisions fence stale asynchronous hydration. All ordinary saves use the same merge boundary; a conversation writer spans preparation, generation, tools and terminal storage on HTTPS/localhost. Ordinary insecure HTTP keeps transactional persistence and per-tab ownership; protected continuation requires the secure path. Independent conversations remain concurrent; stale writes refuse without replacing saved history. Storage-event hydration drains local intents before adopting committed state. Continuation and document drafts clear only after preparation acknowledgment; canceled tool rounds do not publish an unused nonce. A Stop before HTTP invocation restores the preceding attempt after successful storage; failed restoration retains the pending fence. Ordinary database-open failures retain ordered local edits. Foreign deletion/reassignment requires explicit selection while retaining the draft. Conversation model identity is immutable after creation, with an additional model precondition on substantive field writes. Recovery verifies refreshed public history under writer ownership before persisting a receipt. Durable metadata adoption preserves transient fields for unchanged messages in the same model. Withdrawal retains reset/recovery UI.store/chatDatabase.tsopens schema version two withsnapshot,documentsandrecoveriesstores. A durable migration cursor copies legacy blobs one at a time before old-store retirement; CAS progress prevents concurrent migration rollback or post-GC resurrection. History publication validates and claims new blob references in the same transaction. Document collection reads canonical and retained references under its deletion transaction, preserves unexpired foreign staging, and aborts on uninterpretable references. Unused staging expires after 24 hours. Older schema-one writers refuse writes.store/chatRetainedEdits.tsowns at most 64 explicit-resolution records.writeChatStoragereceives complete ordinary local intent, durably quarantines conflicting conversations, then admits independent edits. Failed quarantine retains in-process writes.ChatRetainedEditsoffers version review, fresh fork and canonical adoption. Fork publication and recovery removal are atomic; a fork preserves visible messages/documents and explicit model selection but strips continuation, opaque tool history and origin/route affinity. GC also preserves document handles referenced only by retained edits. -
Delegated inference gateway (experimental):
api/inference_gateway.pyadapts provider-neutralchat.completions@0.1.0and@0.2.0catalog/signature/stream contract into/v1/modelsand/v1/chat/completions. Direct owner authority precedes signing; capability-owned policy independently admits the request. Gateway keys stay host-local;GatewaySignerusesutils/runtime_files.pyfor owner-only POSIX/Windows custody, bounded reads and directory sync. Complete-before-publish hard links retain a concurrent winner; malformed or unsafe existing keys are refused without rotation. No account credentials or provider HTTP clients enter Core. Capability models are separate from mounted instances; chat reuses Markdown, function-call handling and mounted TTS. Discovery is local-host only. V2 catalog validation binds the duplex callable and gateway authorization version.GatewaySigner.preparereturns a signed size/digest reference and bounded UTF-8 media body;send_chat_bodysends 1 MiB packets and half-closes input inside the whole-call deadline, owning cleanup on upload failure. The generic request maximum is 16 MiB; providers may advertise a smaller bound. Native text/vision normalization rejectsChatCompletionMessageFileinputs. V2text_file_input/pdf_inputmodel features gate Chat document selection.dashboard-react/src/store/chatDocuments.tsowns browser-local IndexedDB document storage, request hydration, reference deletion and aged orphan cleanup; localStorage retains conversation handles rather than document bytes. Missing or unsupported files fail visibly before request submission. Up to eight cached catalogs are read concurrently under five-second individual and six-second aggregate deadlines, including managed-owner validation overhead and retaining completed results. Overlapping callers share that read, including queue time in its budget; later callers always read afresh. Transient overload or provider errors allow at most three cached-read attempts inside the same budget; successful withdrawal is immediate and generation is never replayed. The macOS manager uses launchdInteractivescheduling in both scopes, so owners, children and isolated schema workers inherit responsive CPU/I/O policy. Only the exact prior generatedBackgroundunit is accepted for scheduling migration; unrelated definition changes remain refused. Cached empty-input unary metadata may opt intoskulk.admission=metadatawith supporting SDK owners. Its separate bounded slot and control connection keep discovery independent of stream media without stale availability caching. Workloads retain fail-fast admission; identity, deadlines and capability-owned authorization remain enforced. Stream cleanup owns cancellation and local receiver retirement before the first assistant-role event is yielded. -
Native model preservation:
store/preservation_export.pyresolves exact installed records and snapshots/verifies a private closure;preservation_closure.pymaps only card-declared companions;preservation.pyatomically recovers a new home;preservation_cli.pyexposesskulk-preservation plan/preserve/inspect/recover(alsoskulk preservation). No network/node launch, GUI, durable host job or second live-store writer. Independent owner trust and packaged registry root; code consent stays separate. The extensible preservation reader retains new descriptive card properties and vocabulary names in the exact identity. Artifact/file and envelope contracts remain strict; preservation never expands runtime admission. Supported companions publish with normal store/index, schema-3 observations, custom admission and offline config. Unsupported processor/vLLM offline paths fail closed. Exact bundles are required for non-text/composite selections. Only single self-contained models with fresh registry proof and complete original SHA-256 binding retain registry verification; multi-member closures require custom admission with base publication retained. Private copy labels do not imply encryption/anonymity. Contract._pyinstaller/registers apyinstaller40hook for the public core's JSON schema and distribution version metadata; no installer/direct-URL metadata enters the binary through this hook. -
Compatibility and memory contract: Model and Engine Compatibility separates model/artifact facts, real engine requirements and scoped test evidence. Compatible untested hardware remains eligible. Placer, reservations, context sizing, assessments and worker guards must share the actual engine and effective weight/cache policy; memory fit is workload-specific.
NodeResources.engine_memory_settingsandShardMetadata.memory_settingsbind effective policy to shared estimates and pre-load drift checks. Known layouts use actual compressed storage; unknown layouts retain explicit 16-bit fallback. -
Inference assessment:
master/inference_assessment.py:assess_inferenceperforms read-only workload planning throughplacement.py:place_instanceandshared/models/memory_estimate.py. Contracts live inshared/models/inference_assessment.py;GET /models/assessment, Steward'sassess_inferencetool and the model-selection capacity panel share them. Estimated feasibility and observed loaded state remain distinct. Cache sizing uses publishedModelCard.attention_head_dimwhere present, otherwise the shared 128-element fallback; GGUF header geometry takes precedence. Concurrency uses observed llama-server slots plus aggregate context, otherwise serial replicas with explicit uncertainty. Candidate hosts never enter membership.TelemetryViewretains separate local memory/resource/GPU receipt timestamps; heartbeats do not freshen capacity. Requested context filters candidates before ranking.memory_estimate.py:shard_admission_context_tokensalso caps lazy-cache worker guards and system-RAM reservations at smaller stamped serving windows. External results are full-model host specifications, not offers or execution authority. No provisioning occurs. -
GGUF cache admission:
shared/models/gguf_memory.pyresolves Qwen3.5 scalar header geometry into fixed FP32 recurrent state and per-token FP16 attention widths.ModelCard.gguf_cache_geometryis artifact metadata; unknown layouts remain unknown.NodeResources.llama_server_settingscarries configured slots and speculation enablement. Placement copies it to served shard metadata;memory_estimate.pycharges rollback rows separately from weights/KV, and the llama-server runner rejects local settings that differ from the stamp.registry_gguf_metadata.pydefines the separate signed header target.TufRegistryClientbinds it to the same catalog snapshot and targets-role version.registry_model_cardsretains the exact-file evidence asModelCard.registry_gguf_metadataand projects supported structural dimensions; canonical cards are unchanged and full-card approvals bind the projection.
Master
- Role: elects + acts as cluster coordinator; indexes events; plans instance placements; publishes snapshots
- Lives in:
src/skulk/master/main.py - Owns: the authoritative event log (via
DiskEventLog); the indexer that assigns monotonic indices to events; the placement planner. Master identity itself lives outside the master process: each node tracks the current master independently via the election protocol (src/skulk/shared/election.py); the_master_node_idcache is held on the API side atsrc/skulk/api/main.py:461. - Communicates via:
LOCAL_EVENTS(consumes),GLOBAL_EVENTS(publishes indexed events),COMMANDS(consumes),STATE_SYNC_MESSAGES(publishes snapshots) - Election:
src/skulk/shared/election.py; bully algorithm; a single master at a time - Formation robustness (#400): a campaign is (re)started by a connection update only when the set of connected peers actually changes (
_apply_connection_updatestracks_connected_peers), and an in-flight campaign is allowed to finish before the next one starts. Peers are multi-homed and libp2p pings/re-dials every few seconds (PING_INTERVALinrust/networking/src/discovery.rs), so raw connection updates can arrive faster thanDEFAULT_ELECTION_TIMEOUT; without this gating each update cancelled and restarted the campaign before it could elect a master, livelocking formation (worst at simultaneous multi-node cold start). Discovery tries advertised addresses, slows failed link-local retries after another path connects, and requires three consecutive five-second ping failures before closing a socket (rust/networking/src/discovery.rs). - Failover: re-election picks a new master, which seeds its session from the node's prior replicated state (#273,
seed_state_for_new_sessioninsrc/skulk/shared/session_carryover.py): instances, downloads, node info maps, tracing, and bounded steward-action proposal truth carry over; in-flight tasks, runner statuses, topology, and liveness timestamps are deliberately dropped (tasks died with the old session's plumbing; runner processes are torn down by the worker re-creation; topology/liveness must come from live gossip, since a carried topology would keep a dead node's out-edges forever). Actionable approved or dispatched steward proposals therefore reach the promoted master's exact-command recovery paths. Workers re-create runners for the carried instances through the ordinary plan loop, so placements survive a master restart with a model-reload-sized gap instead of a silent permanent 404. The election winner tears its own worker down and rebuilds it, which cancels itsRunnerSupervisor.run()tasks; that teardown is shielded from cancellation (runner_supervisor.py) so each runner process is fully reaped (Metal reclaims its wired GPU memory on exit) beforeworker.shutdown()returns. Without the shield the join was cancelled, the old runner lingered holding its memory, and the rebuilt worker's pre-load memory guard saw the not-yet-reclaimed memory, falsely refused the re-creation, and the #290 re-place-wider path deleted the carried instance (the silent 404 this design exists to prevent). It only bit when the winner also hosted a rank of a carried instance and was memory-tight. The plan loop suppresses liveness-based instance pruning forTOPOLOGY_SETTLE_GRACE_SECONDS(60s) after master start so carried instances aren't deleted while topology is still rebuilding; instances whose ranks lived on the dead master are pruned after the grace. A freshly-booted node that wins election has no prior view; with restart recovery on (the default) it seeds from its own on-disk record instead of starting empty (see Restart recovery below). The seed is indexed as event 0 of the new session (a loggedStateSnapshotHydrated,Master._index_seed_event): late bootstrappers receive it inside the snapshot, early bootstrappers (including the promoted node's own worker, whose bootstrap races the promotion) receive it as the live first event: one delivery path, no idx-(-1) hydration skip. - Restart recovery (initiative
initiative/restart-recovery,src/skulk/recovery/): every node keepsSKULK_DATA_HOME/recovery/cluster-intent.json(ClusterIntentRecorder, checked every 5 s, re-stamped every 5 min) holding ordinary placement intents (model, sharding, meta, width, requested context, hosts and exclusions as stablenode_install_ids), the steward proposal audit, and a freshness stamp. It is derived state, never anapply()input, and is written only when the node's view has applied an event andState.restart_recovery_pendingis false. A master that starts cold (no prior replicated view,Master(restart_recovery_enabled=True)fromNode) seeds event 0 withrestart_recovery_pending=Trueand the record's proposals made terminal (restored_steward_proposals: pending becomes expired, approved or dispatched becomes failed), then ordersRestartRecoveryCompletedfrom its plan loop to clear the flag only after restore. Placement restore (_restart_recovery_events/_restore_recorded_placements, helpers insrc/skulk/recovery/restore.py) waits forTOPOLOGY_SETTLE_GRACE_SECONDS, then requests each recorded intent in order against the master's command-ordered card through the same path steward approvals use, threading one instance map so back-to-back placements see each other's capacity; it first prefers the machines the intent ran on (by install ID), then lets the planner choose, honoring only operator exclusions. A missing card or aPlacementErrorrecordsInstanceFailureRecorded(placement_failed, "Could not bring back X after the restart: ...") once; restore never stops anything to make room;PlacementInfoPendingErrorretries for up to 300 s. A cold start that has seen more than one node (latched, including a master promoted mid-recovery) first chooses a record (_choose_restart_recovery_record): after the settling window it waits, for up toHOST_WAIT_AFTER_SETTLE_SECONDS(120 s), for every connected peer'sRestartRecoveryAdvert(TELEMETRY reading:written_at, placement count, API port; published by each node's recorder at start, after every write, and every 60 s, held inTelemetryView.node_restart_recovery), takes the record most recently confirmed current (record_sources; own record on a tie), fetches a peer's overGET /v1/internal/restart-recovery/recordwith the advertised port, checking the answeringnodeId(recovery/fetch.py; a failed fetch moves to the next freshest), and waits within the same window for that record's machines to rejoin.candidate_addressestries the peer's replicated interfaces, then the advert's ownaddresses(up toADVERT_ADDRESS_LIMIT16, fromown_addresses, loopback and link-local IPv6 left out, so a--no-workernode with noNodeNetworkInterfacesreading is still fetchable), skipping link-local IPv6, which needs a local zone. The endpoint authorizes with_require_cluster_peer_read: the operator mutation policy, plustrusted_fabric_peer_read_allowedfor a direct, Origin-less, unforwarded link-local IPv4/IPv6 or IPv6 unique local peer, so Thunderbolt-only clusters (self-assigned 169.254/16) can fetch while no browser page gains access. A chosen peer record also carries its terminal proposal history into the session. Before placing, remaining intents are reconciled against existing ordinary instances (unrestored_intents, same model and width), so a promoted master never places twice; instances the same planning pass's dead-node cleanup will delete (instances_on_dead_nodes, now computed before restore) do not count, so a master promoted after its predecessor died does not lose the predecessor's placements. Each intent has its own node-information deadline. The advert wait also covers peers seen earlier in the recovery that have since left (awaited_peers,_restart_recovery_observed): one is awaited until the deadline unless it is back under a new node ID (matched by install ID), holds no record, or advertised a record no fresher than the best reachable one. Restore retains every original stable machine exclusion inPlaceInstance.excluded_install_idsandBaseInstance.excluded_install_ids(state field, default empty), including connected machines.place_instance(node_install_ids=...)resolves current node IDs for search, every repair builder carries the stable IDs, and a fresh recorder retains them even if it never knew an excluded machine's previous peer ID.State.restart_recovery_placementssays how many models are coming back, which the dashboard shows as "Bringing back N models after the restart" through the whole settling and choosing wait: the cold-start seed sets it from the master's own record, andRestartRecoveryStarted(placements=N, intents=...)(control event,_announce_restart_recovery_plan) updates it when the plan changes, at record choice and at reconciliation with what is running; The same event also carries the settled plan itself (intents, applied toState.restart_recovery_intents): it is ordered at those same two points, only when the plan differs from the one last announced, and failover carries it, so a master promoted mid-restore skips choosing and finishes that plan even when the node whose record was chosen is gone; an empty settled plan likewise stops a successor from choosing a stale record.PlacementIntentlives inshared/types/restart_recovery.pyfor this, re-exported byrecovery/record.py.RestartRecoveryCompletedclears the count, the plan, and the flag. The Settings togglerestart_recovery.enabled(RestartRecoveryConfig, default on, read when a master is created by_restart_recovery_restores_placements, so a change applies to the next restart) turns placement restore off while still restoring the terminal proposal history (nodes keep recording what runs); the seeded count is then 0. Failover carries the flag and the count so a promoted master finishes an unfinished restore. The recorder remembers install IDs for node IDs the current placements still reference, so an offline excluded machine stays excluded. A placement that leaves the view while one of its machines is disconnected stays in the record, in its original position, forDEPARTURE_GRACE(10 min,carry_departed_placements), because machines in a shutdown go down minutes apart and the last one standing must not record a layout without the others' models; it is dropped at once when all its machines are still connected (a stop or a move), when the model is running as many times as before (a repair re-placed it), or when its machines return without it.SKULK_NO_RESTART_RECOVERY=1turns it off.
Worker
-
Worker.run()retires every owned event, connection and media receiver in its outerfinally, including cancellation before task-group startup. Closure is idempotent and precedes joined native cleanup. A retired rendezvous subscriber cannot retain the topic's fan-out or block a live API's audio-source request;shutdown()still waits for native cleanup before replacement. -
run()owns one cancellation scope across startup and supervised tasks.shutdown()records retirement even before the scheduled coroutine enters, cancels that scope when available, and joins_stoppedafter shielded native cleanup. Off-loop startup reads drain before retirement returns; a cancelled startup cannot later advertise capacity or start a replacement task group. -
Role: receives indexed events, applies them locally, downloads model weights, spawns + supervises runner subprocesses, dispatches tasks
-
Lives in:
src/skulk/worker/main.py; planning atsrc/skulk/worker/plan.py -
Owns: local view of
State(derived); per-modelRunnerSupervisorinstances -
Communicates via:
GLOBAL_EVENTS(consumes),LOCAL_EVENTS(publishes viaevent_router.py),DOWNLOAD_COMMANDS(publishes; e.g. shard-download requests atworker/main.py:392)
RunnerSupervisor
- Role: parent-side lifecycle for one runner subprocess; signal handling; flight recorder buffer; SIGTERM/SIGKILL cleanup chain
- Lives in:
src/skulk/worker/runner/runner_supervisor.py - Spawns:
mp.Process(target=entrypoint, daemon=True)with the runner subtype's main loop - Cleanup chain:
join(5s)→terminate()(SIGTERM) →join(5s)→kill()(SIGKILL); plus parent-pid watchdog inside the subprocess for reparenting (SIGKILL of agent)
Video card projection on the models route
GET /v1/models entries carry video (VideoCapabilitySection.from_model_card, api/types/api.py: modes, seconds range, fps, frame grid, canvas rules, audio output, default steps, reference limits, LoRA adapters with trained steps and shifts, style embeddings, and every engine setting a job accepts with its default: sampler and scheduler lists from shared/types/video.py, the card's trained shifts with their bounds, ref2va reference sizing, and codecs) and license (LicenseSection.from_model_card: name, url, spdx_id, notice, display_name) beside the existing capability sections; both null when the card declares none. Consumers plan POST /v1/videos requests and render license attribution from the node's catalog, never from a bundled copy of the card.
ComfyUI engine provisioning
LTX request contracts also carry explicit pipeline/decoder selection, guided
negative conditioning and base-stage CFG/STG/modality scales, internal
keyframe spacing, and bounded automatic duration. Dev two-stage graphs bind
an exact distilled-refinement LoRA and freeze base audio during refinement.
Companion mode limits are enforced in request validation and file selection,
and projected as pipeline/decoder mode maps and duration-head mode lists.
Alternative decoders and duration heads are separately pinned video_decoder
and duration_head companions; primary component resolution excludes these
auxiliary files. Generated keyframe tokens are stripped before upscaling.
For an exact bundle, local upscaler/duration-head/alternative-decoder paths,
declared sizes and explicit revisions must agree with the primary manifest and
revision; external pinned packs remain separate. Source-audio conditioning and
editing cannot declare an aggregate reference-file limit of zero. These checks
preserve valid card identities and do not depend on hardware qualification.
Duration prediction feeds the same bounded frame count into video and audio
allocation; video_probe.py verifies actual dynamic container facts before
publishing a manifest. Comfy HQ requires a placed instance stamped with an issued
Res2s extension build; the ordinary Comfy core remains insufficient. Its base
stage uses 15 intervals by default, a 0.25 distilled LoRA, per-modality guidance
and rescaling, followed by three joint AV refinement intervals with LoRA 0.5.
The output keeps base-stage audio. Standard HQ decoding removes internal
keyframe slots before upscaling; DFR carries its detailing slots through
refinement. DFR spatial and
optional temporal refinement retain their exact companions and fixed Euler
sampling. Model metadata exposes workflow-specific defaults and issued
source/payload feature identities; consumers match the instance stamp rather
than inferring an old instance's capabilities from newer node inventory. Native HQ job records report its published profile separately: no base-stage LoRA and the selected refinement strength, with video/audio rescaling 0.45/1.0.
Family graph dispatch: worker/runner/comfy/graph.py retains H3 graphs and
dispatches family = "ltx-2.5" to comfy/ltx.py. The distilled graph uses
CLIPLoader(type="ltxv"), separate VAEs, joined audio/video latents,
eight base intervals, spatial x2 latent upsampling, and three refinement
intervals. VideoCompanionKind.LatentUpscaler stages weights under
latent_upscale_models. First images use in-place conditioning; last/timed
images use guide tokens, cropped before upsampling/decoding and reapplied at
full resolution. Progress sums distinct sampler nodes without double-counting
retained snapshots. API metadata exposes effective output grid 64, fixed
sampling_stage_steps = [8, 3], and only applicable sampler controls.
Declared Comfy CUDA/ROCm compatibility remains valid on untested GPUs; absent
benchmark evidence does not remove it. Physical engine/artifact/resource
constraints still apply.
src/skulk/provisioning/comfy.py: select_comfy_variant_chain (Linux, GPU vendor, and a recorded wheel set for the machine), provision_comfy (git clone at COMFY_PIN with a HEAD check, uv venv on COMFY_PYTHON, the COMFY_TORCH_WHEELS set installed by exact URL and hash with no resolution, then ComfyUI's requirements resolved against constraints that keep that wheel set, a frozen environment listing, and a record file written last; staging directory renamed into place), managed_comfy_install, dormant_comfy (read-only twin for doctor), ensure_comfy (startup; never downloads: when the gates hold (opt-out, explicit override wins, SKULK_ENABLE_VIDEO_MODELS, variant chain) it wires a complete install already on disk, exporting SKULK_COMFY_BIN and SKULK_COMFY_ROOT), comfy_on_demand_variants (the install eligibility a node advertises: full participation, the gates above, online, git and uv found via _uv_executable, which falls back to the uv PyPI package's find_uv_bin on Linux, and a variant chain; AMD only for COMFY_ROCM_PCI_DEVICE_IDS, the Strix Halo gfx1151), install_comfy_on_demand (serialized by _INSTALL_LOCK; wires an existing install, else refuses offline, rechecks eligibility, removes staging trees an interrupted install left behind (older than _ABANDONED_STAGING_SECONDS, two install budgets, so another process's live install survives), requires COMFY_INSTALL_FREE_BYTES (15 GiB) free, provisions each variant, runs torch.cuda.is_available() in the new interpreter and removes an install that fails it; raises ComfyInstallError(step, detail) whose step is safe to show an operator), stoppable_runner(stop) (the worker's runner: each command in its own session, polled; setting stop terminates the command's process group, kills it after a grace, and raises ComfyInstallCancelledError, which install_comfy_on_demand propagates without trying another variant, removing an install stopped during its GPU check), installed_managed_comfy (the runner's on-disk lookup by stamped backend). Pins live in provisioning/manifest.py (COMFY_PIN, COMFY_REPOSITORY, COMFY_PYTHON, PinnedWheel with an optional channel root for resolver passes, COMFY_TORCH_WHEELS for cu130 and for AMD's stable ROCm 10.0.0 channel, wheel_set_digest keying the install root). The ROCm lane's launch flags are ROCM_LAUNCH_FLAGS (--bf16-vae) plus --cache-ram N, N being ROCM_CACHE_RAM_HEADROOM_FRACTION (40%) of host RAM in whole GiB so resident models do not thrash host memory on a unified-memory APU, plus --disable-mmap only when a weight file exceeds ROCM_MMAP_CEILING_BYTES (64 GiB), applied by launch_flags when the stamped backend, or the node's own advertised tag for an unstamped or bare comfy stamp, ends in -rocm; every other lane gets CUDA_LAUNCH_FLAGS (--disable-cuda-malloc, because the cudaMallocAsync backend aborts Fun ControlNet renders on the GB10). The runner supplies the selected card family to launch_flags; ltx-2.5 CUDA servers additionally use --fast-disk for disk-backed dynamic weight loading, limiting RAM offload residency beside GPU allocations on unified-memory systems. This preserves GPU execution and ordinary admission across compatible CUDA hardware, without a tested-device allowlist. LTX-2.5 ROCm servers additionally use --use-split-cross-attention to preserve prompt subject adherence: matched renders with the pinned default attention path produced unrelated subjects, while split attention recovered the requested subjects with identical weights, graph and seed. This remains GPU execution, retains ordinary admission and does not restrict compatible untested hardware. Other families retain their existing policy; no lane sets server environment variables, and one server serves consecutive renders on every lane. Facts: NodeFacts.comfy_binary, comfy_root, comfy_root_state, declared_comfy_backends; derivation _derive_comfy (GPU-only, vLLM's declaration chain); inventory reports comfy@<checkout HEAD>/torch@<torch version read from the interpreter> (commit-only when torch cannot be read). Startup hook in src/skulk/main.py beside ensure_llama_server (wire only). Doctor check comfy-engine with --fix (--fix runs install_comfy_on_demand; a node that can install at first placement reads ok).
On-demand install path: NodeFacts.comfy_on_demand_variants (filled by facts._with_install_eligibility on every gather) makes derive_node_backends add comfy plus comfy-<variant> and report them in BackendDerivation.on_demand_backends (installed_backends = the rest; only installed tags count toward gpu_serving_disabled and the engine-build inventory); NodeResources.on_demand_backends carries them in telemetry. Placement ranks cycles by backend preference, download locality, _cycle_engine_ready_score (every node with resources has a compatible installed engine), then free memory. PlacementPreview.engine_install (PlacementEngineInstall: engine, node ids, ON_DEMAND_ENGINE_DOWNLOAD_BYTES (7 GiB for comfy), engine_install_notice sentence) is set when a shard's stamped backend is on demand on its node. CreateInstanceResponse.engine_install (POST /place_instance) carries the same notice from the API node's dry run, keyed by the command's instance id, for launches without a preview. Worker: plan._engine_needs_install emits InstallEngine(instance_id, engine, approximate_download_bytes) for an idle runner whose stamped backend is on demand (once per instance, after the download step) and _load_model skips shards still awaiting their engine (awaited_engine); Worker._start_engine_install joins or starts one _EngineInstallJob per engine, _run_engine_install installs off the event loop (abandon_on_cancel=True: a worker shutdown, including the replacement after a master change, sets the stop event and returns at once, leaving waiting instances for the next worker to plan again), refreshes facts, requires the engine to derive as installed, publishes fresh NodeResources, then completes every waiter's task or fails it and sends FailInstance with error code engine_install_failed. The comfy runner falls back to installed_managed_comfy when its inherited environment has no install and fails with ENGINE_UNAVAILABLE_FAILURE_MARKER (engine-not-installed) when none exists; plan._retried_on_failure treats the marker as terminal and engine_unavailable_live_instances gives the instance up once. Hardware message: _ENGINE_HARDWARE["comfy"] names "a Linux machine with an NVIDIA GPU or an AMD Strix Halo GPU" with classes nvidia and amd:pci-1002-1586. Packaged Linux runtimes get uv from the uv dependency and need git on the host.
audio_cpp: TextToMusic is the sole task on cards using [music] model truth and the music.generate registry capability. NodeFacts.audio_cpp_binary/audio_cpp_probe, audio_cpp_vulkan_binary/audio_cpp_vulkan_probe, and audio_cpp_cuda_binary/audio_cpp_cuda_probe require a pinned v0.8.2 source revision, successful --list-devices, and both SHA-256-pinned model specs; a standalone binary uses SKULK_AUDIO_CPP_SPECS_DIR when the specs are elsewhere. _derive_audio_cpp intersects optional SKULK_AUDIO_CPP_BACKENDS restrictions with actual CPU/Metal/Vulkan/CUDA/ROCm devices and raises a conflict for an invalid override. engine_build_inventory hashes the executable selected for each concrete lane as audio.cpp@sha256:<digest>; CPU, Vulkan, and CUDA can have different simultaneous identities. Verified cache entries are rehydrated before initial node facts at worker-capable startup, without a download. The separate packaging/skulk-audio-cpp-cpu/, Linux amd64 packaging/skulk-audio-cpp-vulkan/, and Linux amd64/arm64 packaging/skulk-audio-cpp-cuda/ build artifacts build only ace_step,minimax_music3; installation availability does not grant a model support claim. CUDA CI targets SM 8.9 on amd64 and SM 12.1 on arm64; only an exact qualified platform wheel may be promoted, pinned, and claimed.
GB10 memory telemetry: nvidia_gpu.read_accelerator_metrics uses CUDA cudaMemGetInfo only when NVML memory fails on an NVIDIA GB10 at compute capability 12.1. CUDA's free figure excludes reclaimable page cache on the shared pool, so free bytes are the larger of CUDA free and host MemAvailable (psutil available, capped at the CUDA total); an unreadable host figure leaves CUDA free in charge. A failed CUDA query leaves VRAM unmeasured. Shared memory_estimate.gb10_unified_memory_pool requires measured CUDA total within 10% of host RAM total and takes the least of CUDA free bytes, host RAM available less UMA_GPU_OS_HEADROOM (16 GB), and gpu_working_set_ceiling (75% of RAM total). The master and worker local fit guard use this same calculation; a missing host reading does not fall through to discrete VRAM. GB10 joins unified_memory_gpu_node_ids so outstanding placements reserve shared system RAM; reserve_instance_vram separately caps its CUDA pool by the uncommitted 75% working set. These bounds prevent an NVML unsupported reading from silently removing a usable GPU or double counting the shared pool.
Managed CUDA wheels target SM 8.9 on amd64 and GB10 SM 12.1 on arm64. Candidate preparation requires a signed claim naming the platform's exact managed executable build and compute class, and one observed NVIDIA device with that known class. hardware_class_inventory retains nvidia:sm-unknown when a device cannot be identified and adds nvidia:multiple-devices for multiple NVIDIA devices. audio_cpp_cuda_hardware_matches rejects mixed, unknown, and multiple devices because the runner cannot yet bind execution and memory admission to a selected physical device. Signed support resolution repeats this check for a managed executable restored from cache; CPU preparation cannot bypass it. An operator-provided primary CUDA binary can use its own exact signed build claim through primary preparation. If a dedicated CUDA wheel is already cached, the operator must also configure SKULK_AUDIO_CPP_CUDA_BIN; startup rehydration otherwise prefers that managed executable over a primary-only override. The host loader must provide CUDA 12 runtime, cuBLAS, NCCL, and the NVIDIA driver libraries. A missing library fails the binary probe with an actionable diagnostic before the lane is advertised.
capture_mlx_memory_snapshot and _release_metal_resources do not import MLX outside macOS. Linux runner diagnostics remain inert for Metal memory and shutdown still performs Python garbage collection without initializing an unused native engine.
Managed CUDA admission rejects an additional AMD/Apple GPU as well as multiple NVIDIA devices; mixed-vendor telemetry can report a different memory pool from the NVIDIA device used by the sidecar. Qualified operator overrides remain governed by their own exact signed claims.
estimate_music_workspace adds 10 GiB for ACE-Step CPU/CUDA/Vulkan, 2 GiB for MiniMax CUDA/Vulkan, and 5 GiB for MiniMax Metal beyond weight/runtime overhead. Native CUDA peaks were 17.93/9.15 GiB, Vulkan device peaks 15.33/8.35 GiB, and MiniMax Metal process RSS 11.83 GiB. API admission, ordinary/exact placement, committed-capacity accounting and the worker load guard share this estimate; hardware compatibility alone cannot admit an undersized GPU pool or Metal system-RAM ceiling. Unqualified model lanes retain their existing estimates.
PrepareAudioCpp targets a worker selected from live NodeResources.architecture, platform class, participation, and memory. A matching signed audio_cpp-cuda claim prioritizes the matching native CUDA package on NVIDIA Linux amd64 (SM 8.9) or arm64 (SM 12.1); a matching signed audio_cpp-vulkan claim prioritizes Vulkan on Linux amd64; a separately signed CPU claim remains an eligible fallback if Vulkan preparation fails. An operator-provided primary binary may instead probe as CUDA or ROCm, and the primary preparation path accepts those lanes only with matching signed support and ready build identity. A standalone primary Vulkan override remains eligible when its pinned revision, specs, and device probe pass; a managed CPU cache path still selects the separate Vulkan wheel. Exact CreateInstance preparation is restricted to its shard's requested concrete backend. The master indexes AudioCppPreparationRequested and AudioCppPreparationCompleted; the request carries the selected variant and a five-minute expiry so replay cannot trigger stale package downloads. The worker prepares the pinned wheel (or a verified offline cache), refreshes facts, and publishes ready resources for that variant. Successful completion carries the verified resource snapshot, which the master applies to its live view before broadcasting the event. The API uses that ordered snapshot for its signed claim check and request-local placement dry-run, then carries it on the ensuing PlaceInstance or CreateInstance command. The master overlays the verified node resources for that command alone, so delayed telemetry cannot undo the preparation barrier before placement. Placement stamps resolved_engine_build on each music shard from the exact live NodeResources.engine_builds lane entry. The runner selects the corresponding executable, rehashes it, and probes the selected device immediately before each sidecar start, refusing a changed build. Linux binds the server to runner death with prctl(PDEATHSIG); macOS launches the server beneath a detached parent-liveness watchdog that ends its process group after runner loss. CUDA, ROCm, and Vulkan audio.cpp lanes admit against the accelerator memory pool in API preflight and placement; Apple Metal and CPU use system RAM. Preparation and exact music placement check the full estimated footprint against the selected pool, including the system-memory working-set ceiling. estimate_music_workspace adds 10 GiB to ACE-Step CPU footprints beyond weight/runtime overhead; API admission, ordinary/exact placement, committed-capacity accounting and the worker load guard share this reserve. CUDA/Vulkan also reserve 10 GiB for ACE-Step or 2 GiB for MiniMax, and MiniMax Metal reserves 5 GiB; unqualified model lanes retain their existing estimates. Exact music placements reject LlamaRpcInstance and multiple runner shards, require a ready build plus matching signed support claim, and skip the generic RAM-only API precheck after backend-specific music admission. MusicGeneration is a distinct single-host task. worker/runner/audio_cpp/ uses up to eight affinity-aware usable CPU inference threads, reserving one usable core when possible; accelerator lanes retain one inference thread. It supervises one loopback server per model instance, serializes generation, restores the sidecar after request failures before queued work proceeds, translates only typed family options, and validates a bounded PCM WAV. A terminal MusicChunk manifest and node-addressed OUTPUT_MEDIA purpose music settle the API job together; late task events cannot record output sources for terminal jobs. Ordered task termination without a terminal MusicChunk starts a 45-second grace deadline checked by the job sweeper. Generic /v1/cancel/{command_id} routes active music jobs through their specific stream and media cleanup. api/music_jobs.py persists lifecycle records; a separate VideoStore root retains verified WAV bytes for up to 24 hours, capped at 64 MiB each. Six /v1/music HTTP operations expose creation, list, status, WAV content, cancellation, and deletion.
The audio.cpp cache retains the original wheel. Reuse rehashes it against the immutable SHA-256 pin and compares every extracted required file with its archive member. The mutable cache record cannot approve changed payload bytes. Upstream's abbreviated --version revision is accepted only for a binary reverified against that wheel; standalone overrides must report the full pinned revision. The API dry-run and master constrain ordinary music placement to the node that completed preparation.
The bare audio_cpp tag reports engine availability, but signed music support and runner placement resolve only concrete CPU, Metal, Vulkan, CUDA, or ROCm tags. AMD sysfs PCI IDs add stable amd:pci-<vendor>-<device> hardware classes (Strix Halo: amd:pci-1002-1586) for exact claim scoping before engine preparation. This keeps the stamped backend, memory pool, and device selection in agreement.
ComfyUI runner
src/skulk/worker/runner/comfy/: graph.py (pure: plan_comfy_render resolves the request plus a named adapter against the card, including the engine tier: sampler and scheduler from the request else the template's res_multistep/simple, sigma shifts from the request else the adapter else the card, ref2va reference fidelity, style embeddings bound as embedding: prompt tokens by style_tokens, and the output codec, all recorded by ComfyRenderPlan.engine_settings into VideoGenerationStats.engine; select_control picks the card's model_patch companion for the mode when the request attaches a control, mask, or source role (the roles in VIDEO_STRUCTURAL_ROLES, kept out of the conditioning builders and the card's reference limits) and build_prompt loads it with ModelPatchLoader and applies MiniMaxH3FunControlNetApply after the sigma shift, so the sampler walks the patched model; shared/types/video.py holds the sampler list and the refusal reasons (video_sampler_refusal), resolve_model_files maps components and the artifact bundle onto ComfyUI loader names, bind_references names verified attachments below the input directory, build_prompt emits the API-format prompt with stable node ids, stage_for_node maps them onto VideoStage, extra_model_paths_yaml), server.py (ComfyServer: spawn with start_new_session and PR_SET_PDEATHSIG, /system_stats health with early-exit detection, port-race retry, process-group teardown; run_prompt: POST /prompt with prompt_id and client_id, /ws?clientId= events, /api/jobs/{id} liveness polling, /api/jobs/{id}/cancel, /history/{id} outputs read once the entry exists (ComfyUI sends execution_success from inside the executor and records history after it returns; the wait is bounded by _HISTORY_WAIT_SECONDS); ComfyRenderError is task failure, RuntimeError is runner failure), runner.py (the test engine's state machine on ServedConcurrentDispatch at width 1 with an admission queue held by the loop (queue_admitted; unbounded in the runner, bounded upstream by the API's per-node job admission, so the loop never blocks on a render and never lets a newcomer past the queue), _generation_kinds = (VideoGeneration,): renders are serial but acknowledged on admission and queued in the loop oldest first, so the worker keeps planning, later renders are still read, and a queued render is cancelled before it reaches the server; the liveness poll is a no-op before load, and a fatal render error tears the server down so the next task, queued render, or poll ends the runner, with the renders still queued failed by the runner rather than dispatched against nothing; LoadModel starts the server, StartWarmup only checks it, renders move SaveVideo/SaveImage output onto output.mp4 and a JPEG thumbnail.jpg), orphan_sweep.py (init-parented main.py with --user-directory under SKULK_CACHE_HOME/comfy/). Selected in bootstrap.entrypoint when the stamped backend's engine is comfy. The shared request-to-plan resolution lives in src/skulk/worker/runner/video_plan.py.
Test video engine
src/skulk/worker/runner/test_video/: render.py (seeded frame and tone synthesis, minimal ISO BMFF muxer with MJPEG and sowt PCM tracks), runner.py (duck-typed Runner with the image runner's state machine; emits progress VideoChunk frames and the terminal manifest), provision.py (stand-in model directory so foxlight/test-video places without a download; the card's TOML ships beside the engine, apart from model cards: it names no artifact, so the signed registry can never supply it; load_test_video_card() reads it). Selected in bootstrap.entrypoint when the shard's stamped backend resolves to the test_video engine; advertised by facts.derive._derive_test_video when SKULK_TEST_VIDEO_ENGINE is set.
Runner subprocess
- Role: owns one model shard or served-engine process; serves typed inference tasks; participates in distributed collectives when its engine and placement support them
- Entrypoint:
src/skulk/worker/runner/bootstrap.py::entrypoint - Subtypes:
src/skulk/worker/runner/llm_inference/runner.py: text generationsrc/skulk/worker/runner/embeddings/runner.py: embeddingssrc/skulk/worker/runner/image_models/runner.py: image generation and editingsrc/skulk/worker/runner/llama_cpp/runner.py: in-process GGUF textsrc/skulk/worker/runner/llama_server/runner.py: served GGUF textsrc/skulk/worker/runner/vllm/runner.py: served GPU textsrc/skulk/worker/runner/speech/runner.py: MLX Audio speechsrc/skulk/worker/runner/comfy/runner.py: served video generationsrc/skulk/worker/runner/test_video/runner.py: deterministic test video
- Communicates via:
mp.Queuefrom worker (incoming tasks);mp.Queueto worker (outgoing events);mlx.distributedcollectives with peer runners
Drafters (speculative decoding)
src/skulk/worker/engines/mlx/drafters/. The loop runs on single-node, tensor-parallel, AND pipeline placements. Multi-node PIPELINE placements use an EXPLICIT decider protocol (#254): exactly one rank (the decider, the last rank) holds the drafter, makes every speculative decision, and fans the outcomes out via fixed-shape per-round collectives: one all_sum lands the draft tokens (_exchange_drafts; the drafter's effective distribution rides along under sampling), and after the verify forward a second tiny all_sum lands the accept length and the next bonus token (mtp_accept_decision). The first sampled token of the request is broadcast the same way. Receiving ranks never draft, sample, or compare logits (they apply broadcast decisions to their own cache slices), so correctness never depends on cross-rank numerical determinism (heterogeneous chips, e.g. M5 vs M4 GEMM kernels and NAX reduced-precision B≥2 matmuls, produce divergent per-rank logits; the previous rank-symmetric design desynced on exactly that and SIGABRT'd in the Metal completion block, #252). A per-request all_sum agreement settles that exactly one rank holds a working drafter (speculation disables symmetrically otherwise); mid-request drafter failures abort loudly on multi-rank placements instead of silently forking the collective schedule. Assistant drafters (gemma4) cross-attend the target's KV, which the decider seat owns by construction (#201 Track 2b); sidecar drafters draft from the all-gathered trunk hidden from the same seat, and only the decider rank loads drafter weights. Multi-node TENSOR placements do NOT use the decider protocol (#263): draft logits go through the TP-sharded lm_head, an all-rank collective idle receivers would never join, so a lone TP decider GPU-times-out mid-draft. Instead every TP rank loads the sidecar (sidecar_load_eligible in src/skulk/worker/engines/mlx/utils_mlx.py, the same envelope assistants use) and drafts rank-symmetrically; the drafter agreement requires ready_count == group.size() on that path and disables speculation symmetrically on partial loads. Cross-attending drafters declare reads_target_cache = True and the loop keeps the target cache fully committed before every draft (no deferred replay); and they must hold the LIVE cache sequence, since reject-restores replace rotating entries in the loop's list. Forces SequentialGenerator. Greedy requests use argmax-prefix acceptance; temperature > 0 uses Leviathan-Chen probability-ratio acceptance over the effective sampler distributions (src/skulk/worker/engines/mlx/generator/speculative_sampling.py, depth forced to 1). Draft depth comes from the card's mtp_max_depth (default 1). Rounds are bonus-driven: the loop carries an emitted-but-unforwarded bonus token, verifies [bonus, drafts] in one K+1-token forward (the round's only target forward), commits the longest matching prefix, samples the next bonus from the first non-matching row, and drafts the very next round from the correction position.
- Protocol:
protocol.py::Drafter:begin_request(prompt_cache)/observe(hiddens, next_tokens)/draft(hidden, next_token, depth=1) -> (K, vocab) logits. The generation loop owns verify/accept/reject and cache reconciliation: attention-only caches roll back positionally in the loop (supports_positional_rollback/rollback_speculative_positionsincache.py: the rejected tail is trimmed, no snapshot, no replay), else the model's nativerollback_speculative_cache, else SSM snapshot/restore with deferred replay (restored-but-committed tokens ride at the front of the next verify forward; capped, flushed at stream end). On the positional path the loop runs on mlx-vlm'sBufferedRotatingKVCachefor plain sliding-window entries (buffer_rotating_caches_for_speculation, converted on entry by the_stream_generate_with_mtpwrapper and restored to their plain class on exit, early close or cancellation;KVPrefixCachestores any converted entry plain): a plainRotatingKVCacheappends every multi-position verify write by concatenating, allocating a buffer one round larger than the last until the window fills, and MLX kept the freed ones (9.5 GB of freed-buffer cache over a 400-token gemma-4-12B response on a 24 GB M4; 0.5 GiB with the buffered cache, decode about 2 to 5 percent faster). Drafters own only their private state. The loop feeds every committed position's(hidden, next token)pair exactly once, in order (the pair-stream contract); the hidden convention is per-family (pre-final-norm for qwen-shaped trunks, post-norm for gemma4). - Builder:
builder.py::build_drafter(model, mtp_weights, runtime): detects sidecar key layout, resolves family facts (norm convention, fc concat order) from layout-keyed defaults with model-cardruntimeoverrides, and quantizes the sidecar block + fc to the target's(group_size, bits)on load (bf16 targets keep bf16 sidecars). - Implementations:
qwen_sidecar.py::QwenSidecarDrafter: Phase 2: +1.0 zero-centered norm shift,embed_firstconcat, sidecarmtp.layers.0block instantiated from the target family's own decoder-layer class (strict-loaded), privateKVCache. Validated 79–85% acceptance / 1.38–1.90x on Qwen3.5 9B–27B (issue #192, bonus-driven cadence).deepseek_sidecar.py::DeepseekSidecarDrafter: legacy projection-only head; conventions unverified against real weights.gemma4_assistant.py::Gemma4AssistantDrafter: wraps mlx-vlm's chain-trained assistant model: cross-attends over the target's KV (shared-KV extraction incl. RotatingKVCache temporal restore), consumes post-norm hiddens, loads viaassistant_model_repo(bf16-enforced). Validated 84% acceptance / 35.1 tok/s on gemma-4-26B-A4B-4bit (depth 1) and 1.86x on E4B-8bit (depth 3).
- Observability: the loop logs
MTP acceptance so far: A/Nevery 32 drafts; the publicGenerationResponsedoes not carry per-token draft provenance.
Router (libp2p)
Worker info ingress forwards heartbeats and resource telemetry independently of ordered-control admission. A separate owned publisher drains one latest queued value per typed connectivity/info kind; a full reliable outbox cannot stall that telemetry consumer or create an unbounded FIFO of changed connectivity readings. Snapshot replacement and self-timeout invalidate queued, pending and confirmed control readings. Normal input closure drains offered values; worker shutdown cancels its blocked publisher.
Self-master control admission bypasses the serialized topic loop before queueing, including after promotion while an earlier follower publication is blocked. The master also reports newly consumed prefixes directly to its local EventRouter after the whole ordered batch has applied/persisted. That in-process retirement performs no peer send, so blocked remote receipt replies cannot strand local skipped events. Remote receipts retain their authenticated retry path. Local producers reject encoded frames above the conservative 8-MiB transport budget (4 KiB reserved for framing and envelope growth) before enqueueing or allocating a source sequence. The producer receives an explicit size error; cloned handles retain the guard. Retention never waits for an untransmittable frame to obtain an acknowledgement.
LOCAL_EVENT_RECEIPTS is an ephemeral control topic for retry-time cumulative
consumption probes. Only authenticated session-master responses can release the
requesting node's retained source prefix. The master advances that prefix after
applying/persisting the whole ordered batch, including skipped stale task events;
receipts themselves never enter State or the event log. Each authenticated reply
also retains a monotonic global replay target, even after its local source was
retired. An independent bounded-backoff task retries from the current global
cursor until that target is reached, surviving lost requests and missing final
replay frames without depending on local outbox activity, while those events
remain in the master's retained log. Local self-master probes short-circuit peer
egress. Origin-aware receipt subscriptions coalesce by transport origin,
requester, source, session and request/response kind. Responses preserve the
highest acknowledged prefix and highest global head independently, so a delayed
older reply cannot erase replay work after outbox retirement. Requests retain
latest metadata. Each subscription holds at most 256 frames of 4 KiB each (at most 1 MiB encoded); oversized metadata is not admitted.
Admission never blocks the shared network receive loop. A full queue evicts its
oldest disposable metadata, which ordinary idempotent retry repairs.
A same-session cursor older than the compacted master tail is a separate recovery limit: existing replay clamps to the retained range and does not acquire another snapshot for a running follower. This bounded local-delivery path does not add live snapshot recovery. Complete the documented same-build fleet deployment before resuming workloads.
-
Reliable local ordering:
routing/event_router.pyretains admitted local events under their original source/index until an authenticated master echo or consumed-prefix receipt; it never expires an ordering dependency after a retry count. Retention is bounded by 256 events and 16 MiB (one individually larger legal message may occupy an otherwise empty outbox); producer queues hold one event. Capped exponential retry delay is 30 seconds with at most 16 sends per wakeup. -
Local-event egress:
LOCAL_EVENTSproducer admission is a rendezvous, followed by one serialized packet and its own publisher. A master's own local events bypass peer publication. Non-control events take no source sequence; strict payload validation, master admission and other topic lanes remain authoritative. The worker coalesces pending connectivity readings and clears that coalescing on membership-context replacement or its own timeout. -
Role: transport for all inter-node communication
-
Lives in:
src/skulk/routing/(Python wrapper);rust/networking/+rust/skulk_pyo3_bindings/(Rust libp2p impl + PyO3 bindings) -
Topics: see "Pubsub topics" below
-
Discovery: mDNS by default;
--bootstrap-peersmultiaddrs for explicit static peers -
Subscription repair: the pinned
rust/vendor/libp2p-gossipsub/backport reannounces existing local subscriptions on each additional connection and on close-with-remaining. This repairs aSubscribeprefetched by the dying handler. First-connection peer scoring, blacklisting, final-disconnect cleanup and local subscriptions remain authoritative; protocol ids, authentication, framing and namespace/key derivation are unchanged.
Election
- Role: picks the cluster master via the bully algorithm
- Lives in:
src/skulk/shared/election.py - Communicates via:
ELECTION_MESSAGEStopic - Late proposals: a better same-round proposal corrects a completed result; comparison uses the completed vote rather than post-win seniority. Duplicate, inferior, and older-round proposals do not reverse the result.
- Lost startup votes: connected nodes republish the original completed winning vote every five seconds. A fixed receive deadline prevents busy incoming traffic from starving repair. A newer in-flight round suppresses the previous result. The timer never creates a round, increases seniority, or substitutes for connection liveness; peerless nodes emit no repair traffic, and input closure stops the receiver.
- Last-resort candidates: a node with management participation (
--no-worker, orSKULK_NODE_PARTICIPATION=management, which Windows always declares) campaigns from a seniority band that starts at -1,000,000 (LAST_RESORT_SENIORITY_FLOOR), so it loses to every ordinary candidate and masters a cluster only when no inference node is present. It gains seniority inside that band when it wins, as an ordinary candidate does from zero, so a management master that has won a round against another node is not displaced by a further management node joining; two nodes that each started alone still tie on seniority and are decided by commands seen and node ID, in either band. The reason is configuration, not load: a newly elected master'sskulk.yamlreplaces every follower's, model-store host included.--force-mastermakes any node an ordinary candidate with top seniority.is_master_candidateinsrc/skulk/main.pydecides. - Triggers: node startup, lost master heartbeat, explicit master abdication
API
- Role: HTTP entry point; FastAPI app; OpenAI / Ollama / Claude / Responses / Skulk-native adapters; serves dashboard
- Lives in:
src/skulk/api/main.py; adapters atsrc/skulk/api/adapters/ - Default port: 52415
- Mounts: dashboard at
/(skipped when the built assets are absent, e.g. a headless/non-Mac worker node with nodashboard-react/dist;DASHBOARD_DIRis thenNoneand the API serves without the UI, #333); OpenAPI at/api/openapi.json - Background tasks:
_apply_state(consumesGLOBAL_EVENTSand persists merged traces),_pause_on_new_election,_cleanup_expired_images(image-store TTL),_prune_old_traces(hourly trace janitor backed byprune_old_trace_files; retention viatracing.retention_days) - Chat-completion response models: non-streaming responses use
ChatCompletionResponse(object: "chat.completion", choices carry a completemessage); streaming frames useChatCompletionChunkResponse(object: "chat.completion.chunk", choices carry adelta), both inapi/types/api.py. These were one model until the harness's external-API compatibility suite caught streaming emitting the non-streaming discriminator; strict OpenAI clients validate it and reject the stream, while lenient ones readchoices[0].deltaand never notice. Keep them separate: the shared model is what allowed the drift. - Third-party surface coverage: the OpenAI, Anthropic and Ollama wire formats are contract-tested by the
external-api-compatsuite in the test harness, and a real client application is driven against them byclient-app-compat. Wire-shape changes to these surfaces belong with a suite update.
Intelligent fabric (internal steward role)
-
Product identity: operator surfaces call this cognition Skulk and the system prompt speaks in the first person as the intelligent distributed AI fabric.
stewardremains only the compatibility role insystem_role, route names, and the reservedskulk/stewardmodel id. Dashboard speech requires and pins theskulkvoice; it never falls back to another voice for fabric answers. -
Config:
intelligent_fabricinskulk.yaml(enabled, default false;steward_modelspreference list, default Qwen3.6-35B-A3B GGUF then MLX, then the parser-pinned vLLM FP8 card (the benched 35B tier), then Qwen3.5-4B MLX, then the 4B GGUF, then the Qwen3.5-0.8B GGUF universal floor so CPU-only fleets still place a steward). The master places the first entry the cluster can serve, so a fleet falls through to the largest brain it can host. -
Thinking: OFF for every steward generation (
STEWARD_THINKING_ENABLED = False, sent asenable_thinkingon both investigation turns and canary probes). Bench measurement, not a card field: the candidate matrix ranked thinking-off, and the thinking-on tiebreaker made both finalists worse on the trust axes. Model cards keep declaring their real reasoning support; this is the harness's request shape. -
Identity:
BaseInstance.system_role = "steward" | None(additive field; None on replayed old logs). Stamped fromPlaceInstance.system_roleat mint; all three repair builders re-stamp it from the instance. -
Canary: the lowest API-advertising node runs
_steward_canary_loop(every 300s, only when mode on + elected + runner idle-Ready + no in-flight task; busy-wedge belongs to the worker wedge detector). Probe = minimal pinned no-tools generation, code-checked non-empty text from a generation that finishes within 120s (an expired deadline fails the probe even after partial text, so a stalled runner cannot reset the failure run); 3 consecutive failures sendFailInstance(runner_unresponsive)so the cause is retained before teardown, and the invariant re-places. Pure target selection =canary_probe_target(steward.py). The failure run lives inStewardCanaryStateon the API (not a loop local), so the status endpoint can reportdegradedfrom the FIRST failure instead of hiding the problem until teardown; single event loop, no lock. The probe dispatches by pinned instance, so a worker host using--no-apiis covered. API presence is explicitNodeResources.api_availabletelemetry; the field defaults true only for mixed-version compatibility, and--no-apiprocesses advertise false. -
Invariant:
Master._maintain_steward_placementruns each planning tick behind the topology-settle grace: places first servable card from the preference list (min_nodes=1, MlxRing meta), tears down duplicate stewards keeping the lowest instance id, paces attempts to one per minute. Master failover re-establishes the steward via the invariant; no dedicated failover code. Both the placement walk and the upgrade walk place candidates only through_place_steward_model, which skips (warning once per candidate) any cardsteward_candidate_is_servablerejects: it requiresTextGeneration, no task or speech declaration that routes the card to a non-text runner, and a resolved profile that supports tool calling. If a higher-preference brain remains placeable for five minutes, its exact shards are prestaged; after the current steward is idle-Ready for 30 seconds the invariant performs a short exactly-one restart. Failed promotion falls through to the prior brain and retries after 30 minutes. -
Pinning:
TextGeneration.target_instance_id(mirrors SpeechSynthesis); miss emits TaskFailedinstance_unavailable. -
Harness:
src/skulk/api/steward.py. Observation tools: cluster state summary (exact node count; per-node identity, RAM, accelerator, backends, and CUDA/ROCm/MLX support; separate operator active-placement, ready/running, and stopping/failed lifecycle buckets; internal system-role services isolated from operator models; retained terminal failures marked historical and non-current), node resources, telemetry diagnostics, data-plane diagnostics, complete per-node diagnostics, cluster versions, performance envelopes, each named node's doctor registry, model catalog, andsearch_docs(steward_docs.py: dependency-free tf-idf section index over the checkout's own docs, anchored on architecture-reference.md; honest absence report on doc-less installs; version-correct by construction, per the no-knowledge-in-weights doctrine). Proposal tools:propose_place_model,propose_stop_model,propose_restart_model, andpropose_cancel_download. They create inert ten-minute proposals only and are supplied to the model only when the HTTP request passes the operator mutation guard; read-only steward chat remains available without that authority. The model has no direct mutating verb. 6000-char tool-result bound, 8 steps/turn. -
Basic-action authority: exact action unions live in
shared/types/steward_actions.py;ProposeStewardActionandDecideStewardActionrideCOMMANDS;StewardActionProposalChangedis the replicated audit event.GET /v1/steward/proposalsreturns a safe projection, andPOST /v1/steward/proposals/{proposal_id}/decisionrequires the ordinary trusted-fabric or operator-gateway mutation guard. The master serializes each decision once, reserves approved placements before the State echo, revalidates current target truth, carries the reviewed attempt identity inCancelDownloadfor final worker-side rejection of a replaced attempt, blocks system roles, and translates approval into existing place/delete/replacement/download command paths. Stop and restart capture complete instance state and share one target reservation, rejecting stale replacement state and conflicting approvals. Stop teardown and restart teardown wait for the replicated decision, and restart revalidates its captured model-card identity before teardown. Restart is two-phase:approveddurably arms teardown; after the deletion event and released-capacity telemetry converge, the planning loop dispatches the captured placement intent or fails it after five minutes. Bounds: 32 pending, 128-record audit target; pending, approved, and dispatched proposals inside the five-minute recovery window are retained even when that temporarily exceeds the target. The master accepts at most a 15-minute proposal lifetime and publishes terminal expiry on deadline. Each planning pass (about ten seconds) rechecks pending proposals with the approval checks (src/skulk/master/steward_staleness.py, pure, shared with approval) and orders terminalstale(decided_by: "fabric_staleness") once the reviewed target changes; the outcome names the change, and approval refusals use the same wording. The pass runs withabsence_is_evidence=False: a cancel-download is marked only for a newer attempt or the reviewed attempt's own completion or failure, since failover clears live download telemetry; approval alone refuses an unseen attempt. Past-deadline proposals are left to expiry. Deciding a non-pending proposal returns 409 with status and outcome.dispatchedmeans command acceptance, not lifecycle completion. A promoted master reconciles dispatched proposals for five minutes from their separate dispatch timestamp and reissues a missing exact command effect once.SKULK_FABRIC_CAPABILITIES_DISABLE=1is a master-side global fail-closed kill switch for both new approvals and recovered dispatches. No autonomous approval or per-action grants yet. -
Every Steward turn obtains a fresh, bounded
get_cluster_statetool result before any model generation, after client history and middleware context. The harness supplies the tool exchange itself; model tool selection cannot skip it. An unavailable or invalid baseline ends the turn with the normal chat error and no generated answer. This also applies to follow-ups, greetings, and both streaming and non-streaming clients. Additional investigation remains model-directed; the baseline guarantees evidence availability, not perfect interpretation. -
Steward omits resident-model/service details from routine cluster summaries; explicit questions about the steward or internal services may include them. Its version tool returns actual per-node Skulk versions and commits, not just comparison status. Standalone version questions receive verified build listings with unknown/partial coverage preserved; matching builds do not establish release currency. The read-only
get_capability_nodestool projects current/state.capabilityNodesadvertisements, owner status and bundle versions separately from hardware and inference backends. Standalone capability-inventory questions use these observations directly; no current advertisements does not prove nothing is installed, and discovery grants no execution authority. These Steward views leave capability lifecycle and authorization unchanged. -
Steward also projects immutable inventory observations before compaction, with API read time, explicit scope, and null counts for missing or malformed source sections. Read time is not telemetry freshness. A bounded set of standalone node-count and download-status questions (for example, “How many nodes do you currently have?” and “Are there any downloads in flight?”) receives a deterministic answer from those observations without model generation. Compound, per-model, action and other diagnostic requests continue through the model investigation. Counts describe topology transport peers and node-staging records, not physical hosts, capability nodes, Pods or model-store fetches. Queued, transferring and retained terminal downloads remain distinct; unavailable per-transfer timestamps prevent a claim that bytes are moving now. Exact counts survive detail compaction, which prioritizes active downloads over terminal history. Backend support is inferred only from advertised backend tags, never hardware vendor. This protects the supported inventory answers; it is not a general semantic validator for model-generated diagnostic prose.
-
Client surface: reserved virtual model id
skulk/stewardonPOST /v1/chat/completions(checked before card resolution; clienttoolsrejected 400; client system messages ignored; trace streams asreasoning_contentdeltas then the answer ascontent; 404 when the mode is disabled). Harness emits the adapters' native chunk vocabulary (run_turn_chunks), so streaming and non-streaming ride the ordinary adapters unchanged. The final answer streams token-live behind a markup hold-back gate (splittable_prefix): prose emits as it arrives, a suspicious tail holds until disambiguated, and tool markup is never emitted as content.GET /v1/modelscarries a flagged entry (system_role: "steward") while enabled.GET /v1/steward= presence plusstate(disabled | downloading | starting | ready | degraded, purederive_steward_state; the booleans stay authoritative). Additivedesired_model,transition, andprogressfields expose best-brain staging and repair. The earlier bespokePOST /v1/steward/chatwas removed before any release. OrdinaryDELETE /instance/{id}of the steward is refused 409 while the mode is enabled.POST /v1/cancel/{command_id}accepts the turn's advertised id:API._steward_turns(weak values, entry removed by_release_steward_turn_afteraround the outermost response iterator) routes it toStewardHarness.cancel_turn, which cancels the generating step throughAPI.cancel_local_commandand latches the loop so no further step or tool call runs; a cancel racing a step's dispatch cancels the fresh inner command. The cancelled turn ends without a terminal chunk, so the adapters report it like any cancelled generation. -
Readiness preflight: the reserved id answers 404 when the mode is off and 503 (status payload +
message+Retry-After) when the mode is on but no steward is ready, checked BEFORE the response begins. The in-stream ErrorChunk path remains only for the placement-vanishes-after-preflight race, so "the fabric is still setting up" is no longer indistinguishable from "the model failed mid-answer". -
Dashboard: instances with
systemRoleset are hidden from all instance surfaces (filter in App.tsx instanceCards). The steward chat polls the safe proposal list and presents separate Approve and Reject controls. Settled proposals stay on screen for ten minutes with their status and reason (components/steward/proposalVisibility.ts), dismissible per view. -
Cards:
unsloth/Qwen3.6-35B-A3B-GGUF(text-only so served lanes stay eligible) andmlx-community/Qwen3.6-35B-A3B-4bit(vision, MLX) are the v1 brain, both revision-pinned;Qwen/Qwen3.6-35B-A3B-FP8adds the parser-pinned vLLM CUDA/ROCm lane;mlx-community/Qwen3.5-4B-MLX-4bit/unsloth/Qwen3.5-4B-GGUFare the small-fleet tier andunsloth/Qwen3.5-0.8B-GGUFthe floor. GGUF steward cards must stay text-only: a[vision]section gates them offllama_server, whose runner cannot load an mmproj projector.
Dashboard
- Role: operator UI for the same Skulk runtime
- Lives in:
dashboard-react/(source); served by API at/ - Stack: React + TypeScript + styled-components + Vite
- State: Redux Toolkit + RTK Query (
dashboard-react/src/store/). Slices atstore/slices/uiSlice.tsandstore/slices/chatSlice.ts; query endpoints injected fromstore/endpoints/cluster.ts,store/endpoints/config.ts,store/endpoints/observability.tsinto a singleapiSlice(store/api.ts). - Routing: activity-style enum (
activeRouteinuiSlice); no react-router. TheNavRouteunion incomponents/layout/HeaderNav.tsxis the source of truth and must stay in sync with four other places: the header links and the mobile rows incomponents/layout/MobileMenuSheet.tsx, the deep-link allowlist and render branch inApp.tsx, and the SPA fallback tuple insrc/skulk/api/main.py(without which a refresh on the route returns{"detail":"Not Found"}). - Integrations page:
components/pages/IntegrationsPage.tsxrenders copy-paste connection recipes for external tools (Claude Code, OpenCode, Codex, Hermes, OpenClaw, Pi, AnythingLLM, Open WebUI, n8n, Firefox). Snippet generation is a pure module,utils/integrationConfigs.ts, fed by the ready instances joined against/modelscapability truth, so each recipe carries real model ids, real context windows, and per-model flags: a vision model declares image input, and a model whosethinking_formatis notnoneis configured to sendreasoning_contentback on later turns. The embedded address comes fromuseRemoteAccess()rather thanwindow.location.origin, because a snippet is pasted into a tool that usually runs on another machine; Docker recipes rewrite it tohost.docker.internal. The page is read-only and issues no cluster mutations. - Capability satellites:
types/capabilityNodes.tstypes thecapabilityNodesprojection and maps status plus freshness to a satellite health level (readyok;starting/degraded/configuration_invalidwarn;failedor owner unavailable error;installed/disabled/stale muted;disablednodes are hidden).hooks/useClusterState.ts#normalizeCapabilityNodesvalidates the wire shape, andensureCapabilityHostsPresentadds a capability host that is missing from the replicated topology (a management-only host emits noNodeGatheredInfo) from its identity and health telemetry, so its satellites have a node to orbit on every dashboard.components/topology/topologyLayout.ts#computeSatellitePositionsplaces up to six satellites on an arc above the host leaning away from the hardware badge, with one overflow glyph;CapabilitySatellitedraws them insideClusterNode,TopologyGraphowns the openCapabilityFlyout(HTML overlay: link surfaces open in a new tab withnoopener noreferrer, descriptor actions callPOST /v1/capabilities/callonly on the local host, loopback surface URLs are reachable only from a browser on the host itself and never rewritten, "Details" opens the panel, remote hosts get a "manage on host" hint),capabilityActions.tsis the shared action registry, andcomponents/capabilities/CapabilityPanel.tsx(overview / surfaces / actions tabs) reuses theRightDrawerchrome extracted fromObservabilityPanel(components/common/RightDrawer.tsx, tab parts indrawerParts.ts). One build flag,VITE_CAPABILITY_SATELLITES=0, turns the layer off. - Persistence: sessionStorage for in-session UI; localStorage for cross-session preferences (theme, panel widths)
- Localization: Tolgee provider in
dashboard-react/src/i18n/tolgee.ts; app wrapper indashboard-react/src/main.tsx; English namespace data indashboard-react/src/i18n/en/skulk.json. All dashboard keys use theskulknamespace and are called throught(key, englishFallback, params?), not<T>. - Translation loading:
BackendFetchreads CDN/static JSON fromVITE_TOLGEE_CDN_PREFIX(default/i18n) with bundled English fallback;VITE_TOLGEE_AVAILABLE_LANGUAGEScontrols the comma-separated language allow/preload list and always includesen.
Operator identity and authority foundation
- Role: owns stable host/cluster identities, deterministic quorum certification, and the encrypted local projection that operator pairing, credentials, revocation, and gateway fencing build upon.
- Lives in:
src/skulk/operator/identity.py,src/skulk/operator/authority.py,src/skulk/operator/replication.py,src/skulk/operator/consensus.py,src/skulk/operator/consensus_store.py,src/skulk/operator/service.py,src/skulk/operator/transport.py,src/skulk/operator/key_provider.py,src/skulk/operator/pairing.py,src/skulk/operator/relay.py, andsrc/skulk/operator/cli.py; pairing and credential-lifecycle routes live insrc/skulk/api/operator_auth.py, the relay-only canonical API guard lives insrc/skulk/api/operator_gateway.py, and focused tests live insrc/skulk/operator/tests/andsrc/skulk/api/tests/. - Stable node identity:
NodeInstallationIdentity.node_install_idis a persisted UUIDv4 under the protected operator configuration directory. It is intentionally independent of the currently ephemeral libp2pNodeId.StaticNodeInformationpublishes only this non-secret ID on the existing last-write-wins telemetry plane, soGET /stateprojects it asnodeIdentities[*].nodeInstallId. The authority journal, keys, credentials, and membership records remain excluded. StablePOST /admin/restarttargeting resolves the ID to exactly one live runtime node before dispatch; missing or ambiguous mappings fail closed. - Cluster identity:
ClusterPublicIdentitycarries the UUIDv4 cluster ID, normalized operator-visible name, raw Ed25519 public key, bound SHA-256 fingerprint, and creation timestamp. The private key may be handed only toEncryptedAuthorityStore.initialize_cluster, which encrypts it before persistence. - Encrypted journal: SQLite WAL with
synchronous=FULL, mode-0700parent and mode-0600database/sidecars on POSIX. AES-256-GCM AAD binds every ciphertext to cluster ID, schema version, authority term, commit index, record type/ID, and external key ID. Appends require the caller's exact expected commit index. Opens repair directory modes; identity replacement fsyncs its parent; public cluster metadata is rebound to the encrypted key; and non-finite JSON fails closed. - Quorum certificate:
AuthorityCommitDescriptorsigns the cluster, term, contiguous index, prior digest, exact payload digest, record target, and one active or two joint membership digests. Ed25519 votes bind the descriptor to a stablenode_install_id. The bootstrap log head derives from stable cluster public-key material, not the editable display name. Every membership needs a strict majority; learners, duplicate members/keys/votes, stale chain heads, non-consecutive joint generations, invalid signatures, and substituted payloads fail closed. - Consensus protocol:
AuthorityBallot(counter, proposer_node_install_id)totally orders concurrent proposals. A voter persists a promise before its phase-one response and an accepted descriptor before its phase-two vote. A replacement proposer recovers the highest accepted value returned by a prepare quorum. Learners catch up but do not vote; joint transitions require both majorities and the resulting committed membership fences removed nodes. Catch-up carries bounded contiguous certificate suffixes only. - Consensus persistence:
SqliteAuthorityConsensusRepositorystores promise/accept state and an append-only certified log separately from the encrypted authority projection. Immutable bootstrap position/membership anchors permit every restart to reverify the complete signature, quorum, digest, index, and membership chain. Writes use revisioned compare-and-set in one SQLite transaction; secret authority payloads and keys are not accepted. - Dormant runtime:
AuthorityConsensusServiceserializes local proposal admission, drives prepare/accept/commit with phase deadlines and bounded retries, recovers a previously accepted value before advancing caller intent, and keeps outbound and response queues bounded. It persists the local commit before success and broadcasts the certificate to voters and learners. Runtime diagnostics expose payload-free queue depths and counters. - Network boundary:
AUTHORITY_MESSAGEScarries Ed25519-signed envelopes binding stable source and target installation IDs, message ID, and one typed public protocol payload. Producer admission and the dedicated Python egress queue are both bounded, and traffic currently rides the default authenticated libp2p gossipsub behavior.AuthorityChannelTransportdiscards broadcasts for other targets before consensus. The topic and consensus service remain dormant. API nodes do construct the independent local pairing service, which never uses this network topic. - Operator pairing:
skulk operator pairexplicitly designates the local host, initializes the encrypted store when needed, and emits one five-minute QR capability. A relay-configured gateway emits the version-two package with app-role carrier and pinned inner-TLS bootstrap material;--exchange-urlremains the direct-development fallback. The relay package is bounded compact JSON compressed with zlib under the QR'szparameter and is rejected before session persistence if it exceeds the terminal-scannable budget. Challenge binds a proposed Ed25519 device key; exchange verifies a domain-separated signature, consumes the session, and returns one access/refresh credential pair. The journal stores encrypted state and one-way token digests, not raw nonces or tokens. Refresh rotates both tokens atomically; bearer validation enforces typed scopes; and device list/revoke routes expose no credential material. A relay-configured exchange also returns the app-role carrier credential, opaque locator, and pinned inner-TLS trust once for durable local storage; the gateway role never leaves Skulk. No QR package contains a canonical access or refresh token. Explicit duration or pairing-limit flags emit a compressed version-three reusable invitation lasting at most 90 days and permitting at most twenty successful pairings. Every scan receives a separate five-minute attempt. Invitations and attempts are distinct encrypted journal records; ten live and one hundred total attempts are admitted. Global compare-and-set fencing prevents concurrent exchanges from oversubscribing the success limit. Host-only list/revoke commands reveal no nonce. Revocation blocks new and unfinished attempts without revoking credentials already issued to devices. Paired-device cap: at most five active devices per cluster (not revoked, refresh credential unexpired), counted from the same journal snapshot whose head fences the credential append, so concurrent exchanges cannot exceed it. Creation refuses at zero free slots, invitation limits shrink to the free slots, scans are refused early, and HTTP refusals are409. Dashboard-onlyGET /v1/auth/pairing-capacityreports active/maximum/free;skulk operator devices list|revokeserves headless hosts. The ordinary direct dashboard listener exposes the same create/list/revoke authority through/v1/auth/pairing-invitations: the socket peer must be loopback or use Tailscale's100.64.0.0/10orfd7a:115c:a1e0::/48space and be verified by the local Tailscale authority; the browser request must be exact same-origin from a loopback, MagicDNS,*.ts.net, or literal Tailscale host and includeX-Skulk-Dashboard: pairing-v1. Forwarding headers, ordinary LAN peers, and unverified CGNAT peers are rejected. Creation returns the bearer package once underno-store, and safe lists omit it. The relay authorization wrapper returns404for this prefix before credential validation, so even a fully scoped paired device cannot mint invitations remotely. Settings renders the secret throughqrcode.reactin component memory for five minutes, independently of the server-side invitation lifetime, and reports actionable gateway/path guidance for authority failures. - Self-service relay registration:
skulk operator pairwithout a route registers one (relay_registration.py): node-generated P-256 key, epoch, and both carrier credentials;POST /v1/registrationscarries only the key ID and SHA-256 credential digests; the answer (locator, region, three URLs) is stored as an on-demand route. Origin:connectivity.relay.registration_urlor the build default (DEFAULT_RELAY_REGISTRATION_ORIGIN,https://relay.foxlight.ai); disabled or offline nodes never register; transient failures (including the relay'sunavailable) retry with the same values; coded refusals (invalid_request,not_found,already_registered,rate_limited,registration_paused,capacity_exhausted) do not.forget-relaywrites a tombstone and removes the TLS identity.OperatorRemoteAccessSupervisorpolls every 5 s and on request: start on a new route, stop on forget, restart on a route-identity change, capped-backoff retry on failure, stay stopped on a permanent refusal (explicit revocation, or 401 for ten minutes). - Dashboard phone pairing: dashboard-only
GET|POST|DELETE /v1/auth/remote-pairing(RemotePairingController, relay-denied). States:not_set_up,registering,connecting(under 20 s without a live session),connected,relay_unreachable,revoked,managed_elsewhere. POST is idempotent and refusesmanaged_elsewhere/device_limitbefore the relay; DELETE forgets the route and revokes its invitations. Errors carry{detail, code, retryAfterSeconds}. Uninitialized nodes list empty invitations and devices. - Pairing gateway telemetry:
NodePairingGateway{active}on the TELEMETRY plane (last-write-wins,TelemetryView.node_pairing_gateways, pruned with the node; never State or the event log), published every poll while the node holds a relay route, then the withdrawal at once and about once a minute after (PairingGatewayAdvertisement), so a peer that missed it still clears the role.skulk operator pairasks the local node's/v1/auth/remote-pairingover loopback and refusesmanaged_elsewhere. Same-version fleets required. - V1 remote carrier:
skulk operator configure-relay --provisioning-filevalidates one generated paired-WebSocket route, encrypts locator and distinct app/gateway carrier credentials in the local journal, and creates a protected pinned TLS identity.OperatorGatewayConnectormaintains 1–32 independent outbound gateway lanes with bounded frames and reconnect delay. Each lane is an opaque byte bridge to a loopback TLS listener serving the same FastAPI app.OperatorGatewayAuthorizationleaves pairing/refresh bootstrap reachable and maps every other canonical route onto existing cluster/model/chat/operation/ device scopes. The ordinary local API/dashboard listener is unchanged and is not relay-accessible; no mobile-only replacement surface exists. - Opt-in V2 on-demand carrier: the same command accepts only a complete
generated version-two document. The existing app URL, route/app credential,
QR bootstrap, pinned inner TLS, and canonical API are unchanged. Skulk keeps
the delegated P-256 key in the encrypted authority journal, durably advances
a
u64connector generation before use, and proves its exact route, region, epoch, term, generation, and five-minute lease over one canonical SKRL control WebSocket. Relay-negotiated heartbeats (currently five seconds) and signed renewal retain that authority. EachOpenConnectionis mapped to a fresh data WebSocket carrying the exact connection ID and immutable initial hello proof, including after lease renewal; its first frame is the canonicalConnectionAccepted, after which only opaque inner-TLS bytes are bridged to the existing loopback listener. The gateway admits at most 64 active data lanes before task or socket allocation; excess requests are left unclaimed for relay-side expiry. No warm data lanes are opened. This path is source-integrated but not enabled by version-one state and is not yet a production scale, mixed-version, persistence, revocation, or rollback claim. - Key boundary:
AuthorityKeyProvidersupplies the active unwrapped 32-byte data key and immutable key-version ID. V1'sLocalFileAuthorityKeyProvidercreates one random local key protected by POSIX mode0600on the designated gateway. Hardware-backed wrapping and replicated key envelopes are later hardening; the authority SQLite database never writes the plaintext data key itself. - Critical boundary: local pairing, scoped canonical relay ingress, and the
outbound designated-gateway lane pool are active when provisioned.
Deterministic network vote collection, certified log
recovery, and caller-selected bounded proposal orchestration are implemented,
but authority leader selection, encrypted payload replication, OS-protected
key wrapping, gateway leases, and Node lifecycle integration are later slices.
V1 explicitly claims no automatic authority or gateway failover: local
pairing and relay state are authoritative only for the designated gateway,
and remote access is unavailable when that host is unavailable. Relay state
loading and the relay listener/connector are isolated from the ordinary local
API, so damaged protected material or carrier startup failure disables only
remote access. None of these records enters
State, telemetry, diagnostics, or the API event log.
Extensions (plugins)
-
Signed dependency roots:
runtime_artifacts.pyaccepts isolated runtime protocols 2 and 3. V2 signed bytes/claims remain unchanged; v3 requires 1–8 unique canonicalapplication_rootspresent in its exact signed wheel inventory. Before pip, v3's graph from declared roots plus launcher-provider wheels must cover every package. Metadata, native tags, hashes, dependency versions, URL/extra refusal and archive bounds remain enforced. Verification imports no provider SDK and resolves nothing online. Deploy this reader before offering v3 capability releases. -
Proposal review:
proposal_review.pyexportsProposalReference, summary, field, page and review models plusNodeProposalReviewProvider.api/plugins.pyexposes read-scoped per-node proposal listing and exact-ID/digest review. Maximum 16 summaries per page, 32 text fields per review and 128 KiB per response. Managed owners advertise per-nodeproposals_available. Canonical input, approval and execution remain provider-local; these methods cannot sign or dispatch. -
Owner proposal actions:
proposal_actions.pysupplies the optionalNodeProposalActionsProviderand exact-reference/review-fencedProposalApproval. Approval and explicit interrupted-approval recovery requireplugins:approve; durableProposalOperationreads requireplugins:read. Direct and relay routes enforce scopes before broad operation fallback and pass authenticated actor IDs. The provider owns durable intent, signatures and reconciliation. The Plugins page renders bounded plain-text terms and persists only an operation lookup ID; reconnect never resubmits. These actions are separate from steward tools. -
Isolated steward callbacks:
managed_host.pybinds one protected local owner to live policy, owned descriptor revisions and exact-target Fabric invocation.managed.pyexposes the optional steward provider facet through fixed owner IPC. Frames are bounded and sequenced; reconnection admits future calls without replay. No signing key crosses this interface. Overall tool deadlines: reads 5 seconds, inert proposal preparation 20 seconds. -
Original direct-owner identity:
api/operator_auth.py:authenticate_capability_ownerreturns the process-localextensions/caller_identity.py:AuthenticatedOwneronly after actual socket/origin/Tailscale/ASGI request admission. Caller and issuer fields never come from headers or payloads. It names one node-local owner realm, not a human or provider account; paired/relay credentials cannot inherit it. It is not an execution grant, native root, bearer credential, discovery field or replicated State. Native dispatch retains separate live-policy/exact-destination admission. -
Node configuration: optional
NodeConfigurationProviderinextensions/configuration.py; stable installed node IDs, schema/ordinary values, enabled state, revision and schema digest.api/plugins.pyexposes/v1/pluginsinventory and per-node GET/POST configuration. Provider-owned storage and validation, independent of child readiness, never replicated State.plugins:read/manage/approveare explicit grants with no pairing defaults;operator/plugin_scopes.pyprecedes broad operation fallback on direct and relay routes. Owner-only/v1/auth/plugin-grantsuses current encrypted pairing records and revision fences. Plugins dashboard renders ordinary schemas and preserves drafts on conflicts. -
Node credentials: optional
NodeCredentialProviderinextensions/credentials.py; separate per-node GET/POST credential routes expose declarations/readiness and accept bounded write-only values with exact operation/revision/schema fences. Explicit plugin scopes precede broad authorization. Managed IPC never loads the private SDK into core. Providers retain cleanup versions and admission checks; the dashboard keeps values outside Redux/browser persistence and requires refresh after conflicts or unconfirmed writes. No values enter ordinary settings, diagnostics or replicated State. -
Role: load separately installed packages and call them at serving-path hooks; deployment-specific behavior without forking Skulk
-
Lives in:
src/skulk/extensions/(types.pycontract,loader.pydiscovery + guarded dispatch,managed.pyisolated-owner adapter); call sites inAPI.chat_completionsandAPI._steward_chat_completions -
Native runtime envelope 3: release envelope 2 retains exact canonical protocol-five manifest bytes.
native_contracts.pyuses the qualified public kernel 0.4.0rc1, full profile/source identities and exact published wheel hash/length. Native signatures/digests useskulk.runtime/3\0; legacy v2 signing bytes stay unchanged. Offline staging retainsnative-manifest.jsonand verifies its full native identity and all four fingerprints in the installed interpreter before completion. Normal selection fences changes between legacy/native semantics or native author/managed fingerprints; a state/schema label is not profile migration authority. -
Native call runtime envelope 4: explicit
control_profile: "skulk.calls/1", public kernel 0.6.0rc1 and all six profile/source identities, with exact public wheel bytes. Signature/digest domain isskulk.runtime/4\0. Staging repeats six-profile and call-codec checks in the installed interpreter. The migration window accepts envelopes 2/3/4/5 while preserving old signed closures; it never swaps a newer binary into an issued generation. Selection distinguishes native transport from native calls and refuses implicit state migration. Startup qualification grants no native invocation/delegation capacity. Frozen builds collect all three cohort receipts and exact selected reader metadata/licenses; any missing receipt refuses the build. -
Runtime artifacts and staging:
runtime_artifacts.pyverifies the complete canonical v2 envelope, owner-provisionedRuntimeTrust, the manifest's Skulk version range (the recordedskulk_build_sha256is provenance, never a fit requirement, so a Skulk update keeps installed releases running; catalog protocol 2 listings carry the same range asskulk_requires, andentry_reviewfits them by host version, while protocol 1 listings keep their exact-build rule;ACCEPTED_CATALOG_PROTOCOLS = (1, 2, 3, 4)), platform/Python compatibility, bundle/wheel hashes, safe archive paths and full wheel dependencies. Provider manifest policy is signed opaque data.runtime_install.py:RuntimeInstallerstages under protected service storage using isolated venv + offline hashed wheels, and journalsRuntimeOperationIDs (staging,staged,recovery_required), release-sequence binding and monotonic trust. Waiter cancellation retains ownership until completion is durably recorded. Cached completion is reverified; interrupted generations are retained without replay.runtime_integrity.pyseals installed files, permissions and interpreter identity; verify before private Python starts and disable bytecode writes with-B. Missing or changed seals require explicit recovery. Exception:verify_or_adopt_installed_runtime(every cached verification, under the installer lock) runsadopt_current_interpreteronly after ordinary verification fails; it re-points the interpreter links andpyvenv.cfgat the running interpreter and reseals when only the base interpreter moved or changed, every other sealed member matches exactly,pyvenv.cfgis the sealed bytes and the Python minor version is unchanged;interpreter-rebase.jsonlets an interrupted adoption resume.runtime_files.pysupplies protected atomic files and fixed local locks. This path does not activate services or alter logical/cleanup state. -
Native inference runtime envelope 5: release3/runtime5 signature domains are
skulk.release/3\0/skulk.runtime/5\0. Explicit calls2 selects exact published kernel0.7.0rc3, kernel0.7.0rc4, kernel0.7.0rc5, kernel0.7.0rc7 or stable kernel0.7.0 with portable2/managed2/handshake2/transport2/composition3; installed staging independently checks all thirteen baseline binary profiles and optional discovery1 on native7 and stable0.7.0, manifest identity and call framing. Old issued wheel closures and signing bytes remain unchanged. Selection refuses implicit interpretation/state migration. All seven cohort receipts are required by frozen packaging, preserving all five published inference closures. -
Native inference caller authority:
inference_callers.pykeeps Core-issued bearer digests, credential lifetimes and per-principal exact grants outside capability backups. Settings → Inference access explicitly enrolls the dashboard or separate API clients; its/v1/inference-access/ownerread supplies the authenticated manager-profile principal without granting authority. One-time client keys remain in component memory only. Direct-owner/v1/inference-accessmanages revision-fenced credentials/policy; enrolling a client grants no effects.inference_enrollment.pyverifies signed runtime/descriptor/effect/domain/mode and persisted child identity without requiring readiness.native_inference_hosts.py/native_inference_calls.pyexpose exact unary read/inference and delegation at/v1/native-inference, using actual authenticated owner/client identity and the role-authenticated owner bridge. The owner repeats current permission under the physical-write fence and cancels revoked active work. Read cannot delegate inference; unrelated offline capacity cannot rewrite permission. Nullable request/credential/owner deadlines intersect; no hidden generation cap or uncertain replay. The explicit rc4 stream cohort adds all three same-host stream modes throughnative_inference_streams.pyand the enrolled-bearer WebSocket.api/server_config.pyshares the production 2 MiB WebSocket transport bound with installed checks. Portable/2 JSON values remain bounded to 64 KiB; larger contexts use multiple bounded media packets. Protocol-six packets retain separate media and per-call byte leases; terminal delivery requires native end, control completion and call-tree cleanup. Fresh write guards and root-scoped cancellation preserve sibling calls. Signed resource bounds remain independent of generation lifetime. Governed effects, remote Fabric, provider account custody and routing remain outside this adapter.api/native_inference_service.pyshares broker custody across API adapters; protected connection replacement is serialized and drains the old generation. A trusted adapter may pin an entire observed listing, independently of fresh caller authorization; changed runtime, incarnation, signed descriptor or resource policy refuses before dispatch. Closing prevents reacquisition. The API task owns injected broker shutdown after every listener stops; relay lifespan shutdown leaves local native requests active. A standalone router closes only its own service. -
Runtime selection:
runtime_selection.py:RuntimeSelectorholds installer and stopped-supervisor ownership, revalidates the signed staged generation and installed seal, journals exact intent, and atomically publishesRuntimeSelection.SelectionOperationretains pending/completed/recovery/superseded state. Explicit disable can withdraw stalled local activation/selection, withwithdraws_operation_idretained through both journals and restart; it never runs the withdrawn release. Live work and pending withdrawal cannot be superseded. Explicit rollback preserves the highest selected sequence; expanded permissions require acceptance; incompatible state or configuration schemas require migration. A changed configuration schema is compatible only when the candidate's manifest speaks plugin protocol 3 or later (CARRYING_PROTOCOL: its owner validates stored settings against the new schema once and rebinds them) andconfiguration_schema_compatiblefinds that the new schema still accepts everything the old one did. That comparison is structural and never evaluates a schema: annotations (title,description,default,examples,$comment,deprecated) may change anywhere; a closed object withoutpatternPropertiesmay gain optional properties; and required properties may become optional. Loosening is followed only through keywords where a schema accepting more makes its parent accept more (properties,items,prefixItems,additionalItems,additionalProperties,allOf,anyOf). Undernot,if/then/else,oneOf,contains,propertyNames,dependentSchemasand existing definitions, which a$refcan reach from anywhere, only annotations may change. Any other change needs migration. Disable/uninstall retains selected files and logical/cleanup state even when trust is invalid. Recovery completes only local selection, never provider acquisition. Selection is desired state, not service health; the launcher must revalidate the live core before execution. -
Runtime service:
runtime_service.py:RuntimeServiceruns separately from inference and executes only the freshly verified selected generation's owner, through the archive's fixed__owner__entrypoint or theownerlauncher a signed wheel declares underskulk.capability_runtimewith isolated Python and bytecode writes disabled. It ownsservice.lock, repeats trust/core/artifact/seal checks, passes a launcher lifetime pipe and persists payload-freeRuntimeServiceStatus. Running means process existence, not readiness. Shutdown checkssupervisor.lockafter bounded owner teardown; surviving children must retain that fence. Unexpected owner exit ends this launcher lifetime without replay. Fixed OS registration remains separate from this primitive. -
Runtime management:
runtime_controller.pyjournals immutableLifecycleRequestandLifecycleOperationfor revision-fenced activate/disable. Preview happens before stopping; accepted work outlives callers; boot recovery finishes only recorded local selection.runtime_manager.pyowns a protected bounded local socket and up to sixteen controllers, automatically provisions the locally established transport binding and retains unavailable installations in inventory. Fixed operations are list/register/get/submit/operation/recover; no caller-supplied commands, paths, credentials or paid approvals. Terminal JSON control uses the same socket. HTTP lifecycle and OS registration are not yet wired to this primitive. The controller supervisesRuntimeServicewith restarts after_RESTART_DELAYS_SECONDS5/15/45/120/300 and then every 300 s while failures continue (a lifetime of_STABLE_LIFETIME_SECONDS600 starts the waits over; a launcher raisingOSError/ValueErrorafter its teardown is a failed lifetime; a stop during a wait starts nothing; each restart is a new lifetime, never a replay; the supervisor fence refuses a new owner while an old one survives).runtime_files.is_desktop_metadata(regular.DS_Storeand._*files) is skipped by the manager's installation scan,measure_host, the core runtime copy, the installed seal and, restated standard-library-only,service_bootstrap.runtime_tree. -
Stable manager runtime:
service_snapshot.pystages a local copy of the exact installed Skulk environment, effective core/bindings and declarative resources. It creates a fresh standard venv, omits editable/installer path shims, refuses unknown startup hooks and external links, compares source bytes and dependency inventory before/after, and qualifies the copied core.ServiceSnapshotbinds a complete protected tree seal; activation needs a stopped manager. Retention: once a manager attaches on the generation selected for the host's build,ManagedServicesremoves superseded generations in the background under the installer fence (prune_superseded_generations). It keeps the selected one, any generation a running manager starts from, and the newestRETAINED_PREVIOUS_GENERATIONS(1) other complete one. A completed pass runs once per selected generation. A busy fence defers it to the next refresh, and a pass that leaves a superseded runtime behind, or fails, is retried after five minutes. The fixed standaloneservice_bootstrap.pyruns with-I -S -B, verifies the manifest, interpreter identity and full tree before enabling Python site initialization, and starts only the generic manager with its explicit state root and a fixed environment. On POSIX it replaces itself with the manager (execve). Windows cannot replace a running process, so there the bootstrap stays as the process the OS service watches: it joins a Job Object that ends its processes when the bootstrap's handle closes, starts the manager as a child, ignores Ctrl-C and Ctrl-Break (the manager acts on them and shuts down in order), waits, and exits with the manager's exit code; however the bootstrap ends, the manager and everything the manager started end with it. The Windows seal differs where the platform does:venvmakes no link there, so every reparse point is refused, each member must be the account's and grant access to nobody but the account and SYSTEM,homeinpyvenv.cfgmust be the base interpreter's folder, and the manifest also records the base's library (base_library_sha256). Staging on Windows builds the environment in a child run on the base interpreter's real path, and refuses, before creating anything, a copy whose deepest file would not fit below the service root on a machine without long paths (copied_path_excess). Two things still do not run on Windows: staging a real copy, because host measurement (measure_host,current_platform) names macOS and Linux only and a Windows artifact family has not been named; and registering the service with the operating system (service_registration.py,service_setup.py). It is not a replacement for Skulk installation or a same-user sandbox. OS setup remains a separate gate. -
Private release staging:
extensions/runtime_download.pyretains signed metadata reviews, downloads only from one owner-configured HTTPS source, verifies exact artifacts, and stages throughRuntimeInstallerwithout activating. Source/trust/credential destinations require direct owner authority; explicit remote plugin grants can inspect/install only the trusted selection. Feed secrets are write-only protected references and validation errors are redacted. Retained install IDs outlive browser disconnect; interrupted work is never automatically replayed. Dashboard review/staging/activation andskulk-plugin-service manageshare manager operations. Dashboard source setup generates identities, requires explicit publisher trust and keeps credential values out of Redux/browser persistence. Omitted source fields retain existing settings; trust updates preserve revocations. Explicitrecover_installuses the original ID/digest with a reviewed current source revision, retains each attempt, and never moves selected/pending generations or reseals completed ones. -
Signed capability catalog (discovery only):
extensions/runtime_catalog.pyreads one host-scoped catalog address with its own discovery trust and write-only credential (one atomically replacedcatalog-state.jsonunder the manager root holding the source, the discovery trust, its floor and the per-address floors (catalog revision floors keyed by address, document and publisher, and discovery trust floors keyedtrust\n<address>\n<document>in the same map so older builds still read the document; a switch records the address being left and never lowers another address's trust floor, configuration compares a trust only with the target address's own floor; trust floors and catalog floors are each bounded to 32 entries separately;revocations, written only when not empty, keeps per private address the revocations its trust held when the host left it, carried into any later trust for that address and never into the store's or another address's;CatalogSourceUpdate.assign_trust_revisionhas the host number a trust one above the target address's floor, andCatalogSourceStatus.assigns_trust_revisionsadvertises it for the dashboard), pluscatalog-credentials/and thecatalog.lockfence), verifies the signed document in the release order (signature over the canonical payload before the claims are read, publisher trusted and not revoked, trust and catalog windows, protocol window with the namedcatalogrefusal) and retains each verified document by digest. Reviews carry consent facts (identity, sequence, digests, size, platforms, Skulk build, permissions, capability ids, surfaces, durable operations, steward risk classes) and whether each release matches this host, never an address or credential. Built-in capability store (extensions/capability_store.py):StoreTrustClientmirrors the model registry'sTufRegistryClientagainsthttps://skulkapps.foxlight.ai/trust/(metadata/,targets/), bootstrapping from the embeddedcapability_store_root.jsonpackage data (shipped since root version 1: two hardware root keys at threshold one, targets key separate from the snapshot/timestamp key; absent, the store is inactive andbuiltin_store_available=false), replayingroot_history, and verifying one targetv1/publisher-trust.json(aRuntimeTrust: revision, expiry, publishers, revoked publishers and artifacts; root and role keys may be ECDSA P-256 or Ed25519); it keeps a hash-boundlast-known-good-trust.jsonunder<manager root>/store-trust/that is also the store trust's revision floor (older or same-revision-different trust refused), uses it alone when offline or when a refresh fails, and refuses an expired trust.HostCatalogtreats a state with no source and no trust as the built-in store (configured=true,builtin_store=true), seedscatalog-state.jsonwith the store's catalog address (https://skulkapps.foxlight.ai/catalog/catalog.json, anonymous) and verified trust on the first read, and on each read while the source is the store applies only a strictly newer trust revision, also after the held trust has expired, exactly as published, with no revocation merge; the store budget is 8 seconds inside the request deadline.configure_catalogreserves the store's address and requires bothbase_urlandtrustto move off the store;use_builtin_catalog(HostCatalog.use_builtin_store, revision-fenced, undercatalog.lock) switches back with the store's trust as published, independent of the private trust's revision and revocations;configure_catalogmerges prior revocations only within a private catalog's own history, never from the store's trust.CatalogRequestandCatalogStoreRequestcarry the node'sofflinemode because the manager runs with a fixed environment. Refusal codescatalog_store_unavailable,catalog_store_trust_unavailable,catalog_source_reserved. Store-bound installations: follower status isReleaseSource.follows_storeinrelease-source.json(omitted when false so older builds still read private records;SourceStatus.follows_storereports it), withReleaseSource.store_trust(StoreTrustRecord: the store revision and digest last taken).RuntimeDownloads.configureandfollow_trustinstall the source record and the trust as one step: atrust-transition.jsonjournal lands first, both files are written, the journal is removed;source()completes a pending journal before anything reads either file, the manager completes it when it loads an installation before the owner can start (RuntimeDownloads.recover_transition), and an unreadable journal refuses release operations and keeps the installation from starting.follow_trustrefuses a store trust older than the one recorded, or a different one at its revision, so a read racing a renewal cannot roll a follower back; a binding keeps a follower's newer recorded trust over the catalog's older view; a refused binding's rollback restores source, trust and record in one step (configure(restore_trust=...)).install_from_catalogfrom the store callsRuntimeDownloads.configure(carry_revocations=False, follows_store=True)and gives the installation the store's trust as published at its next trust revision (_store_release_trust; a key differing from a not-yet-following installation's still refuses); a private-catalog bind or an ownerconfigure_sourcepassesfollows_store=False.RuntimeDownloads.source()migrates a legacystore-binding.jsonmarker into the record, then removes it with a directory fsync (remove_private). Manager requestrefresh_store_trust(StoreTrustRequest, carriesoffline; answersStoreTrustRefreshwithtrust_revision,followed,deferred) takesHostCatalog.builtin_store_trust(independent of the current catalog source; on a refresh timeout it falls back to the store client's retained copy), refuses withcatalog_store_trust_unavailablewhen followers exist and no verified trust is in force, applies the trust to the catalog withHostCatalog.apply_store_trust(only on the store, only a strictly newer revision, through the same per-address floor helper as a read, skipped while a catalog operation holds the catalog), and callsRuntimeDownloads.follow_trustfor each follower under the manager guard with one shared 10-second deadline (_STORE_FOLLOW_SECONDS) for installer fences: follower status is rechecked under the fence, content-equal is a no-op, otherwise the trust is rewritten atrevision + 1with the source revision untouched; busy installations are deferred.read_catalogreturnsCatalogRead(review,store_trust_deferred) and on the store follows the same way with a 2-second deadline;install_from_catalogfrom the store first applies the client's retained trust to the catalog, so consent is checked against the newest verified store trust. A store renewal in a read applies only a strictly newer revision, also after the held trust expired. Any follow that defers sets the manager's retry flag, reported asstore_trust_retryin the inventory.ManagedServicessendsrefresh_store_trustwith the node'soffline_mode()after an inventory refresh once due: hourly, or after five minutes when the manager refused or deferred, a read reported deferred followers, or the inventory flag rose; a renewal in flight when such a notice arrives keeps the five-minute deadline; it warns once per run of failures.skulk-plugin-service catalogalso sendsoffline_mode(), and both terminal catalog commands accept the bareCatalogReviewreply of a manager still running the previous build (CatalogRead.from_reply). Manager requestsread_catalog(outside the manager-wide lock),catalog_status,configure_catalog,use_builtin_catalog,install_from_catalog(HostCatalog.acceptedre-verifies the retained document under the reviewed digest and requires it to be the accepted floor for the source and publisher; the listing must fit the host; the installation is registered or reused under the manager guard, its bundle and high-water sequence checked, its source configured from the listing withrelease.json, the discovery trust and the catalog credential only for the catalog's own origin viaHostCatalog.credential_for; inspection runs outside the guard and the review must match the listing'srelease_digest, publisher, bundle and sequence); routesGET /v1/plugins/managed/catalog,GET/POST /v1/plugins/managed/catalog/source,POST /v1/plugins/managed/catalog/source/builtinandPOST /v1/plugins/managed/catalog/install(POSTs owner-only);skulk-plugin-service catalogandskulk-plugin-service install-plugin --from-catalog BUNDLE_ID [--sequence N] [--platform FAMILY] [MANAGED_ID](TerminalInstaller.run_from_catalog: newest listing that fits the host, plain listings are never candidates since the host installs runtime records only, ambiguity at one sequence refused until the family is named, then the ordinary stage and activate consents). Reading the catalog selects, stages and installs nothing; installs still go through the verified release path. -
Live manager discovery:
extensions/managed_services.pywatches the protected local setup connection and manager inventory; newly registered installations enter configuration and cached capability lookup without API restart. Manager unavailability independently fences admission. Existing extensions retain namespace priority.api/managed_plugins.pyprovides explicit plugin-scoped inventory, registration, selection, submit/status/recover HTTP routes, backed by the same retained local operation IDs as the terminal. Dashboard reconnect reads pending/selected operation references without replay. API shutdown releases observers, not OS service ownership. -
Managed owners: protected local
SKULK_CONFIG_HOME/managed-plugins/*.jsonregistrations containplugin_idand absolutestate_root; no HTTP command/path selection or private SDK import. Owner-only Unix sockets carry bounded discovery, exact-node unary/streaming invocation and revision/schema-fenced ordinary configuration. Owner transport identity must match Skulk. Health polls use a one-second timeout, observations expire after three seconds; failed owners retain their management facet.DynamicCapabilityProvider.dynamic_capabilities()supplies cached snapshots for all four I/O modes for live lookup. Static IDs win and conflicting dynamic contracts are hidden. Explicit manager disable releases cached capability reservations without removing management nodes; unknown manager or selection state retains conflict protection. Loader-owned one-second telemetry reconciliation withdraws dynamic tags at shutdown without stopping external services. The adapter carries fixed steward and owner action messages; provider approval policy stays outside core. -
Managed streaming:
extensions/managed_streams.pyimplements the protocol-4 local media bridge without importing an owner SDK. Admission is a protectedcontrol.sockconnection carrying exact node/descriptor identity and one deadline up to 300 seconds. Packets carry a finite JSON header up to 64 KiB plus raw inline media up to 1 MiB. Owner/child media uses a fresh authenticated connection per call, isolated from primary health; ingress is bounded to eight frames per queue and writes await backpressure. Input completed is a half-close. Output terminal is held until owner cleanup acknowledgment and EOF; wrong identity, sequence, duplicate/missing terminal, disconnect and cancellation fail the call. The owner invalidates/reaps that child under its restart budget; fresh local IDs fence stale output, siblings remain independent, and calls are never replayed. State and event logs contain no call/media bytes. Protocol-3 unary owners remain supported; streaming descriptors require a protocol-4 owner and matching core reader. -
Plugin attachment facts:
extensions/host_network.pyandGET /v1/plugins/host-networkexpose bounded numeric TCP listeners, live peer identity, data transport and a domain-separated namespace fingerprint under existing plugin-read authorization.Router.host_networkqueries the running libp2p swarm and Zenoh session, including OS-assigned ports. Zenohtls/locators project to their numeric TCP socket; TLS is end to end between Skulk peers, so a plugin byte tunnel stays transparent while the attaching peer must hold the same cluster key. Raw routing namespaces remain private; no dial/reconfigure action is exposed. Provider-specific secure tunnels and peer bootstrap remain plugin-owned. -
Discovery:
skulk.extensionsentry-point group, scanned once at node startup (load_extensions()insrc/skulk/main.py, API-spawning nodes only); entry point value = zero-arg factory returning aSkulkExtension -
Contract:
SkulkExtension(name,skulk_requiresPEP 440 specifier,chat_middleware());ChatMiddleware.transform_chat_request(context, task_params)pre-dispatch +ChatMiddleware.observe_chat_response(context, task_params, summary)post-completion (background task, immutableChatResponseSummary) -
Steward turns: the steward's bespoke surface returns before
chat_completions' hook, so it wires both hooks explicitly (API._steward_extension_transform+LoadedExtensions.tap_chat_streamoverStewardHarness.run_turn_chunks). The turn is presented asTextGenerationTaskParams(model=skulk/steward, instructions=STEWARD_SYSTEM_PROMPT, input=user/assistant history); onlyinstructions(becomes the turn's system message viarun_turn_chunks(system_prompt=...)) andinput(user/assistant only) are read back. A transform leaving no trailing user message is discarded in full (history, prompt, and params) with a warning; an accepted transform's returned params are normalized to the reserved model, filtered history, and effective prompt, so observers always describe the turn served. Exactly one observer call per turn:StewardHarness._generate_events(investigation steps) andcanary_probepassextension_tap=FalsetoAPI.text_generation_chunk_stream/_tapped_text_stream, which withholds the extension chat-summary tap while keeping envelope and telemetry taps. Same guarded never-degrade semantics as the ordinary path. -
Context:
ExtensionContext= node_id + skulk_version +embed_texts(in-process equivalent ofPOST /v1/embeddings, backed byAPI.embed_texts; returnsNonewhen no embedding instance is placed) + telemetry-plane access (fabric-citizenship Phase 1, read + advertise):read_cluster()(telemetry-plane READ surface): returns an immutabletuple[ClusterNodeView, ...]snapshottingTelemetryViewper node: node_id, friendly_name, backends, participation, skulk_version, accelerator_vendor, ram_total_bytes, last_telemetry, capabilities; pure/in-memory, no mutation, fieldsNone/empty until each reading arrives;extensions/telemetry.py:snapshot_cluster.advertise_capability(tag)(telemetry-plane ADVERTISE surface,API._advertise_capability): records an opaque capability tag onTelemetryView.local_advertised_capabilities(the node's outbound set on the shared view). The worker'sInfoGatherer._monitor_capabilitiespolls that set and gossips it as aNodeCapabilities(aTaggedModelinTELEMETRY_PLANE_INFO,capabilities: frozenset[str]); every node'sTelemetryView.apply()coalesces it intonode_capabilities[node_id], surfacing in peers'read_cluster().capabilities. Additive + idempotent (blank tags ignored); published only while the set is non-empty (no gossip volume for the common no-capability node), EXCEPT one empty reading on the non-empty -> empty transition so peers clear the LWW entry after a withdrawal (a behavioral change only; theNodeCapabilitieswire shape is unchanged). TheNodeCapabilitiesvariant itself is a wire type, so the same-version-fleet rule applies to it. A--no-workernode publishes tags, including empty withdrawals, alongside its management resource heartbeat every two seconds without advertising inference backends.withdraw_capability(tag)(API._withdraw_capability): liveness counterpart of advertise; discards the tag from the outbound set. Peers see the shrunken set on the next poll (or the single empty reading when the last tag goes). No-op for unknown tags.publish_capability_node(summary)/withdraw_capability_node(plugin_id, node_id)(topology surface,API._publish_capability_node/_withdraw_capability_node): records aCapabilityNodeSummary(shared/types/capability_nodes.py; identity, status literal,owner_available, at most fourlinksurfaces with validated absolute http(s) URLs and no userinfo, at most eightsurface/link/descriptoractions with descriptor payloads capped at 4 KiB,operations_active) onTelemetryView.local_capability_nodeskeyedplugin_id/node_id; at most sixteen per host.InfoGatherer._monitor_capability_nodes(poll 5 s) gossips the snapshot asNodeCapabilityNodes(aTaggedModelinTELEMETRY_PLANE_INFO) on change, republishes a non-empty snapshot every 30 s for late joiners, and sends one empty reading after the last withdrawal;_publish_management_node_resourcesapplies the same discipline on--no-workerhosts (polled with its two-second resource tick, published on change, republished every 30 s while non-empty, one empty reading after withdrawal).TelemetryView.applystoresnode_capability_nodes[node_id]plusnode_capability_nodes_received_at, clearing both on an empty reading or prune.GET /stateprojects live hosts ascapabilityNodes: {hostNodeId: [summary + observedAt]}, dropping a host whose last reading is older thanCAPABILITY_NODES_STALE_AFTER_SECONDS(90 s, three republish intervals) so a missed empty withdrawal cannot pin stale summaries on a peer.SKULK_TEST_CAPABILITY_NODE=<url>publishes one stand-inreadynode (foxlight.test-capability/studio) with a link surface at API startup. Wire type: same-version-fleet rule applies.describe_node(node_id)(heavy discovery half,API._describe_node_capabilities): local node readsLoadedExtensions.capability_descriptors; a peer is proxied viaGET /v1/capabilitiesover_reachable_peer_api_urls()(the same peer-API browse the trace cluster endpoints use; the extension contract is transport-abstract so this can later ride the provider call plane). Returns()on unreachable/invalid payloads, never raises.
-
Provider facet (fabric-citizenship Phase 2a): an extension implementing
capabilities() -> Sequence[CapabilityDescriptor]is a provider (structural@runtime_checkablecheckCapabilityProviderinextensions/types.py; collected guarded inLoadedExtensions.__init__; duplicateid@versionper node rejected loudly).CapabilityDescriptor(extensions/capabilities.py, frozen/strict, MCP-tool-aligned shape without MCP's JSON-RPC):id(lowercase pattern, doubles as the telemetry tag and is auto-advertised at API construction),version(semver;qualified_id=id@version),title,description(LLM-readable),input_schema/output_schema(JSON Schema dicts),io_mode(unary/server_streaming/client_streaming/bidirectional; chunk schemas required for the streaming modes, forbidden for unary),annotations.descriptor_revision(d)= 16-hex sha256 of the canonical JSON dump; calls will carry it so discovery and invocation cannot silently disagree.on_start(context)(SupportsExtensionStartup, dispatched guarded byLoadedExtensions.run_startup_hooksat API construction) is the startup hook: a pure provider has no chat hook through which to reach the context, so registration must not depend on a chat request. Endpoint:GET /v1/capabilities(API.list_node_capabilities) returns{node_id, capabilities, revisions}. Reference provider:examples/extensions/echo-provider/(not installed by default; servesecho@1.0.0calls). -
Capability call (Phase 2b):
ExtensionContext.call_capability(node, id, version, revision, payload, timeout_seconds=None)->CapabilityResult(typed; never raises). Envelope types inextensions/calls.py:CapabilityCall(call_id, capability_id, version, descriptor_revision, caller/target node, timeout_seconds capped at 300, payload),CapabilityResult(ok + result | typedCapabilityError), error codesnot_found / version_mismatch / revision_mismatch / invalid_payload / invalid_result / payload_too_large / overloaded / timeout / provider_error / unreachable. Provider side: a provider implementingCapabilityCallHandler.handle_callis callable; registryLoadedExtensions.call_handler(qualified_id); a descriptor without a handler is discovery-only. Dispatch chokepointAPI._dispatch_capability_callguards in order: target-node addressing check -> handler lookup -> revision pin (descriptor_revision) -> then INSIDE the per-node concurrency bound (_MAX_CONCURRENT_CAPABILITY_CALLS= 8, excess ->overloaded) and the caller deadline (anyio.fail_after->timeout): 1 MiB payload cap, input-schema validation (extensions/validation.py, JSON Schema 2020-12, NO remote $ref fetch), the handler (exception ->provider_error); then result-shape checks + result cap + output-schema validation ->invalid_result. Serialization/validation work counts against the bound and deadline (#513) so a storm of large-but-invalid payloads cannot drive unbounded concurrent validation; cheap guards stay outside so trivially-rejectable calls never consume a slot. EndpointPOST /v1/capabilities/call(always HTTP 200 with a typed result). Caller sideAPI._call_capability: local target = in-process fast path (same guards); peer = direct peer-API POST with ONE budget clock spanning target resolution + the HTTP hop (#513): the lookup (_peer_api_url_for, first-hit, deadline-bounded) consumes from the same budget the provider gets, the envelope carries the REMAINING budget, and the HTTP deadline is remaining + 5s so the provider's typed timeout wins; a lookup that exhausts the budget returns typedtimeout. Master never in the hot path; nothing event-sourced. Transport-abstract: the peer hop can move to a Zenoh queryable (needs queryable support inrust/networking/src/zenoh_session.rs, currently pub/sub-only) without changing the contract (#510 transport note). Handlers are async; blocking/CPU-heavy work must be moved off the event loop by the extension. New dependency:jsonschema. -
Provider streaming (Phase 3):
extensions/streams.pyis the transport-independent contract.CapabilityStreamFramekeys one logical stream by(call_id, direction), uses sharedstarted/chunk/completed/failed/cancelledkinds, and carries structured payload, optional rawInlineMediaAttachment(1 MiB/frame cap), optional stagedBlobMediaAttachment, or typedCapabilityStreamError.CapabilityStreamReceiverenforces bounded ordering, one terminal, duplicate idempotency, late-frame rejection, five-second gap expiry, call/idle deadlines, and synthesized failures independently per direction.CapabilityStreamHandlerservesserver_streaming;CapabilityInputStreamHandler.handle_input_stream(context, call, input_frames)servesclient_streamingandbidirectional. Skulk emits output sequence-zerostarted, validates exact identity/sequence andoutput_chunk_schema(oroutput_schemaon a client-streaming completed result), and requires one terminal followed by iterator exhaustion. The terminal is withheld until the handler returns so itsfinallycleanup completes before dependent work can observe success; malformed or trailing output closes a closable iterator before the synthetic failure terminal is published.ExtensionContext.stream_capability(...)returnsCapabilityStreamSession(open_result, frames, input);inputisNonefor server streaming, otherwise aCapabilityStreamInputsink whosesend_chunkowns caller sequencing and whosecompleteis input half-close, not cancellation. Local/remote opening usesPOST /v1/capabilities/streamas a control-sized admission request; both media directions use the distinctPROVIDER_DATAtopic (not theDataChunkunion), encoded byrouting/provider_streams.pyas a four-byte JSON-header length + canonical header + optional raw bytes. The receiving node is the owner key: caller for output, provider for input. The Zenoh DATA scheduler uses independent bounded queues keyed by(owner, call_id, direction), with same-node short circuit, owner/process admission caps, publish deadline, typed saturation rejection, and a renewed-on-frame 30-minute idle resource lease. Lease expiry tombstones the stream, releases admission, and best-effort publishes a next-sequence transport failure. Early output-iterator close callsPOST /v1/capabilities/stream/cancel; caller inputcancelrides DATA and terminates the same logical call. No final acknowledgement in v1; master/State/event log are absent from the path. Narrative treatment: Architecture "Provider streaming". -
Dynamic stream admission:
CapabilityStreamAdmissionHandler.admit_stream(context, call)runs after static input-schema validation, inside the stream concurrency/deadline budget, and before lifecycle creation. It returnsCapabilityError | None; a typed rejection emits nostartedframe. Use it for live model/backend availability, not static schema rules. -
Built-in TTS provider (Phase 4 first consumer): production
APIconstruction prependsBuiltinSpeechProvider(extensions/speech.py) to the guarded registry, reservingtts@1.0.0ahead of external duplicates. Its descriptor isserver_streaming, MP3-only in v1, and maps genericmodel+textinput to the existing coreSpeechSynthesisTaskParams; core model cards/store/mounting/placement/runner inference stay authoritative.AudioChunkbase64 is decoded at the facade and emitted as rawInlineMediaAttachmentbytes plus schema-validated model/format/index/partial/sample-rate metadata. The descriptor is always described, whileAPI._sync_builtin_speech_capabilityadvertises thettstelemetry tag whenever an MP3-capable mounted TTS card withsupports_streaming=trueis ready, re-evaluating on instance create/delete/snapshot hydration/config update. Admission revalidates the requested model beforestarted; provider cancellation/deadline/transport failure cancels the core command and finalizes its DATA queue. The underlying core command still uses normal master placement/task routing; the generic provider opening and output lifecycle remain node-addressed/off-State. -
Reference-audio TTS:
POST /v1/audio/speechsupports two reference-conditioning paths. A card voice may name a checksummed profile shipped underresources/speech_reference_voices; the command carries only the stable profile ID and the selected worker resolves its local MP3 and exact transcript, so media and private paths never enter commands, State, or the event log. The multipart form instead accepts a request-scopedreference_audioupload capped at 25 MiB and cannot be combined withvoice. A supporting card must declareaudio.supports_reference_audio=true. For an upload, the API selects a ready single-host instance, pinsSpeechSynthesis.target_instance_id, and sends only filename/content-type/digest metadata through the command path. Raw bytes travel as orderedSpeechMediaPacketchunks plus a terminal SHA-256 overSPEECH_MEDIA; reference uploads require Zenoh because gossipsub broadcast is forbidden for private media. The target worker keeps bounded, expiring command-keyed buffers outside State, verifies contiguous sequence and digest, and injects bytes only into its local runner task. The runner creates a temporary file only while upstream generation executes and removes it infinally. Dispatch, cancellation, malformed input, transport failure, task completion, and expiry clear retained buffers. -
Built-in batch STT provider:
BuiltinSpeechProviderreservesstt@1.0.0, aclient_streamingbinary-input/batch-output contract over the authoritativeAudioTranscriptioncommand and speech runner. The transport mode is intentionally not unary: encoded audio travels as ordered rawInlineMediaAttachmentframes (1 MiB each, 25 MiB aggregate), callercomplete()half-closes input, and inference then returns one schema-validated completed payload with model/text plus optional language/segments. Thestttelemetry tag requires a ready single-host mounted STT runner; admission revalidates the requested model and metadata. The provider does not advertise progressive output or managed blobs. Provider ingress stays off State, and the shared core batch path retains raw audio only until authoritative placement before sending boundedSPEECH_MEDIAframes directly to the selected worker. The worker verifies owner, count, and digest before runner dispatch; no audio payload enters the ordered event log. -
Built-in realtime STT provider (Phase 4 second consumer):
BuiltinSpeechProviderreservesstt.realtime@1.0.0, abidirectionalmono PCM16-to-transcript contract. It is described unconditionally but advertised/admitted only with reachable mounted STT capacity declaring bothsupports_streaming=trueandsupports_realtime=true. Admission pinsRealtimeAudioTranscriptionto one ready single-host instance; the master creates the task without re-placement and reserves the instance against cross-API admission races. Transcript output follows normal owner-addressed DATA lifecycle, while caller PCM travels as bounded binaryRealtimeAudioPacketvalues onREALTIME_AUDIOand never enters State or the event log. Same-node ingress short-circuits in the router; remote ingress requires Zenoh and is not advertised on the gossipsub fallback. Transport rejection is routed back to the source API and fails only the affected command. A bounded multiprocessing channel carries worker input to the speech runner. The worker permits bounded pre-dispatch buffering, cancels overflow, and retains bounded finished-command tombstones so late frames cannot accumulate. The runner requires upstreamcreate_streaming_session, linearly resamples mono PCM16 to the session input rate, emits progressiveTranscriptionChunkdeltas, half-closes and drains on caller completion, and cancels promptly. After core output terminates, the provider sendsTaskFinishedand withholds its terminal until replicated task state is terminal or deleted; loss of that control-plane acknowledgement fails within a bounded deadline instead of releasing a next turn into stale busy admission.api/realtime.pyaddsWS /v1/realtime: same-origin browser or origin-less SDK clients send bounded OpenAI-style base64 PCM16 append/commit events; decoded 24 kHz mono bytes become raw provider frames, and provider output becomes delta/completed/failed events. The edge caps transcript text at 1 MiB per event and in its pre-commit buffer, emitting a typed failure and1011close on overflow. Optional typed server VAD incrementally resamples input to 16 kHz WebRTC frames, emits speech-start/speech-stop events, and auto-commits on silence or maximum duration. One socket serializes multiple utterances as distinct provider calls, rotates linked item IDs, resets VAD per turn, and rejects overlap while a committed turn drains. Optional response configuration sends final transcripts through a mounted chat model under a strict 1-4096 output-token ceiling (256 by default), with hidden reasoning disabled by default for speech-ready output, and optional mountedtts@1.0.0provider, exposing visible text and MP3 audio events; explicit cancellation and VAD barge-in cancel underlying commands. It has no noise reduction or tool execution. Cancellation on disconnect closes active Fabric/model work. Hypercorn caps client messages at 2 MiB and pings every 20 seconds. Dashboard chat requires both card-level realtime truth and the local API's livestt.realtimetag, captures microphone Float32 through an AudioWorklet, continuously resamples it to 24 kHz PCM16, bounds browser socket buffering, and retains the batch MediaRecorder path as fallback. -
Fabric speech composition surface:
WS /v1/fabric/chains/speech?stt_model=...reuses the hardenedRealtimeTranscriptionBridgerather than creating a parallel orchestration runtime. Its typedsession.updateselects server VAD plus optional mounted chat, TTS, and voice participants and optional bounded output-token and thinking controls. It therefore inherits realtime provider admission, remote data-plane routing, bounded conversation text, off-State media, cancellation, barge-in, and terminal guarantees from/v1/realtimewhile exposing the composition under an explicit Fabric endpoint. -
Built-in VAD provider: production
APIconstruction also prependsBuiltinVadProvider(extensions/vad.py) and always advertises stablevad@1.0.0. The bidirectional contract accepts bounded inline mono PCM16 at WebRTC-supported 8/16/32/48 kHz, re-frames arbitrary input chunks into exact 10/20/30 ms classifier windows, and emits typedspeech_started/speech_stoppedchunks.VoiceActivityDetectorowns per-call minimum-speech, silence-hangover, preroll, and maximum-utterance state; callers may manually half-close, partial terminal PCM is rejected, no model is mounted, and media bytes are never retained. -
Invariants: guarded dispatch (a raising extension is logged and skipped, inference never degrades); extensions never own the chunk stream (Skulk accumulates, observers get a summary); no external extension installed = external hooks inert (first-party facades are explicitly registered core adapters)
-
Steward tools: optional
StewardToolProvider(extensions/steward.py) offers typedStewardToolcontracts in theextension_*namespace. Modes arereador inertproposal; caller mutation permission filters proposals at discovery and invocation. Each model step binds an exact adapter/revision, revalidated before invocation; duplicate names, withdrawal and shutdown refuse dispatch. Limits: 32 adapters, 16 tools per adapter, 32 total tools/64 KiB prompt metadata, 8 KiB tool/arguments, 16 KiB result, cooperative two-second parallel discovery and five-second invocation. Exceptions expose sanitized errors; the hook receives no execution approval and does not replace provider authorization. In-process adapters remain trusted code. -
Dynamic readiness: optional
CapabilityReadiness.capability_ready(id@version)returns cached local boolean truth without I/O. False, exceptions, or shutdown hide descriptors and refuse new unary/stream dispatch; streaming rechecks after awaited admission. Existing admitted calls keep their deadline/cancellation contract. Providers without the facet retain their behavior; providers publish/withdraw telemetry tags as health changes. -
Lifetime: CLI creation and serving share one event loop.
on_start(context)runs once at API runtime entry, not construction. OptionalSupportsExtensionShutdown.on_stop()hooks run concurrently at API exit after discovery closes, shielded from outer cancellation with a collective thirty-second budget. Hooks must cooperate with cancellation; in-process extension code is trusted. -
Version gating: extension refused at load when
skulk_requiresdoes not match the running version (mixed plugin/fabric versions = mixed-version-cluster anti-pattern) -
Kill switch:
SKULK_EXTENSIONS_DISABLE=1skips discovery (node-local)
Node Facts (capability derivation, #614)
- Role: one probe pass per process gathers what the node observed about itself; a pure derivation turns it into the advertised backend tags plus loud conflicts. Principle inversion: detection creates capability, configuration overrides it, disagreement is always loud (#609/#612/#462 made structural).
- Lives in:
src/skulk/facts/(probe.pyobservation,derive.pyderivation,testing.pysynthetic-facts helpers); types insrc/skulk/shared/types/node_facts.py - Probe:
NodeFactsrecords ALL observed GPUs across the supported vendor vocabulary (GpuVendor = nvidia | amd | apple) withdetection_source(nvmlfull NVIDIA path /nvidia_device_nodedevice visible but NVML unusable, the #612 degraded state /amdgpu_sysfs/apple_platform), importable deps (pynvml,llama_cpp+llama_supports_gpu_offload(),mlx_audio), engine binary states forSKULK_LLAMA_SERVER_BIN/SKULK_VLLM_BIN/SKULK_RPC_SERVER_BIN(not_configured/ok/missing/not_executable), thellama-server --list-devicesreport, and the rawSKULK_*_BACKENDSdeclarations verbatim. Cached once per process (current_node_facts/refresh_node_facts). - Derivation:
derive_node_backends(facts) -> BackendDerivation(pure). Precedence per engine: operator declaration > the binary's own--list-devicesdevice list > hardware vendor inference (NVIDIA impliescuda; AMD impliesvulkanfor served engines,rocmfor vLLM) > CPU floor. One exception to declaration-wins: a declared GPU backend for an in-processllama_cppbuild that positively reports no GPU offload is dropped (advertisesllama_cpp-cpu) so GPU GGUF work is not routed to a degraded build. - Conflicts:
CapabilityConflictcodes:gpu_serving_disabled(GPU visible, all serving would run on CPU; error severity, the #609 silent-ngl 0class),gpu_detection_degraded(NVIDIA device visible but not fully readable; warn, #612),invalid_engine_binary(binary override unusable; warn, #462),backend_override_conflict(declaration claims unobserved hardware; honored but loud; warn). Severity source of truth:CONFLICT_ERROR_CODESinnode_facts.py, shared withnode_health. - Integration:
probe_node_backends()insrc/skulk/shared/backends.pyis now a thin cached delegate into this package.NodeResources.capability_conflictscarries the conflicts on existingTELEMETRYintocompute_node_health(four matchingHealthCodevalues) and the dashboard topology badges.
Doctor (skulk doctor)
- Role: the node environment contract, executable: on-demand audit plus safe idempotent remediation over the same
NodeFactssnapshot the capability pipeline uses - Lives in:
src/skulk/doctor/(checks.pyregistry,cli.py); subcommand dispatch insrc/skulk/main.py(before node launch wiring) - Checks:
engine-available,engine-packages(every add-on engine the node holds can be used for a new launch, read from the facts snapshot's quick file check, never hashed),capability-conflicts,models-storage(mirrors node_health's 10/2 GB disk thresholds),dashboard-assets. Verdictsok/degraded/fail; every non-OKCheckResultstates consequence + remediation. A crashing check degrades into afailverdict rather than killing the audit. --fix: provisions the pinned llama-server build (Linux, no engine present), installsnvidia-ml-pywhen NVIDIA detection is degraded by its absence, creates the models directory, and switches new launches of an add-on engine whose active build is damaged or no longer runnable to another intact build on the node's disk (the earlier one first; it deletes nothing, because only the running node knows which build a model is using).--jsonfor machine output. Exit codes: 0 ok, 2 degraded-only, 1 any fail.- Docs generation: the check list in
website/docs/node-doctor.mdis GENERATED fromREGISTRYbyscripts/generate_doctor_docs.py; edit the registry, not the page.
Engine provisioning (managed llama-server, #614 Phase 3)
- Role: pinned, checksum-verified upstream llama-server builds so a fresh Linux node serves GGUF without building llama.cpp
- Lives in:
src/skulk/provisioning/(manifest.pypins upstream llama.cpp releaseb11669with a sha256 per(arch, variant);llama_server.pydownloads, verifies, extracts, and wires) - Behavior: auto-runs at Linux node startup when
SKULK_LLAMA_SERVER_BINis unset; installs underSKULK_ENGINES_DIR(default~/.local/share/skulk/engines) and exportsSKULK_LLAMA_SERVER_BINfor the process (runner subprocesses inherit it; the facts probe then validates the managed binary like any other). Managed-source priority: pip-installed engine wheels outrank tarball provisioning and work offline once installed. The supervised startup wrapper detects either managed engine distribution before its project sync and usesuv sync --inexact, because the installer-managed platform wheel deliberately lives outside the locked project resolution and an exact sync would prune it. NVIDIA triesskulk-llama-server-cuda(Foxlight-built binary + NVIDIA's official runtime wheels as deps) thenskulk-llama-server-vulkan; AMD usesskulk-llama-server-vulkan(bundles the Apache-2.0 Khronos loader; the driver ICD, e.g. mesa-vulkan-drivers, remains the OS prerequisite). Each wheel'sllama-server-*shim wires the loader path and execs, itsggml-rpc-server-*sibling shim is exported asSKULK_RPC_SERVER_BINfor multi-node donors, and a wheel whose version does not packageLLAMA_SERVER_PIN(scheme0.<build>.<rev>) is ignored with a warning. Both wheels build from pinned upstream SOURCE in.github/workflows/engine-wheel.ymlwith sigstore build-provenance attestations (gh attestation verify <wheel> --owner Foxlight-Foundation). Source of truth is the Foxlight PEP 503 index on Cloudflare R2 (wheels.foxlight.ai, published byscripts/publish_wheel_index.py; the CUDA wheel's ~450MB exceeds PyPI's per-file limit); the Vulkan PyPI mirror was retired 2026-08-30, so new versions publish only to R2 while versions already on PyPI stay up. The guard step keeps manifest/packages/installer in lockstep. Variant selection for tarballs (select_variant_chain): NVIDIA triescudathenvulkan. Thecudatarball manifest slot is empty because upstream publishes NO Linux CUDA prebuilt; the CUDA channel is the Foxlight wheel (above). When an NVIDIA node has no usable CUDA wheel at provisioning time (bareuv synccheckout, GPU-cloud container that skippedinstall.sh's engine step, or a stale wheel after a pin advance),ensure_llama_serverinstalls it on demand (#661):try_install_cuda_wheelrunsuv pip install skulk-llama-server-cuda==0.<pin>.*against the Foxlight index (same flags as install.sh'sENGINE_INDEX_FLAGS), gated on the wheel's SM floor,allow_download(never on--offline), and the autoprovision opt-out. A runtime with no uv or a read-only environment that has pip (the operating-system packages) installs it for the running user instead (_install_cuda_wheel_for_user): the newest pin-matched, platform-compatible wheel on the Foxlight PEP 503 page is downloaded by exact URL and checked against the page's SHA-256, thenpython -m pip install --isolated --no-cache-dir --only-binary :all: --index-url https://pypi.org/simple/ --target(withTMPDIRinside the staging directory) stages it with NVIDIA's runtime wheels and moves it intoSKULK_ENGINES_DIR/wheels/skulk-llama-server-cuda/<pin>/, whoselaunchers/llama-server-cudaandlaunchers/ggml-rpc-server-cudashell launchers put thenvidia/*/libdirectories and the engine'sbinonLD_LIBRARY_PATH. Engine order is the environment CUDA wheel, then that user CUDA engine (same SM and pin gates, read byuser_cuda_llama_server), then any other environment wheel. Failure logs the manual remediation and degrades to the Vulkan lane (an installed Vulkan wheel outranks the tarball as always), which works on bare metal but not on container clouds with compute-only driver stacks (where the pre-#661 outcome was a CPU-tagged engine on a GPU node the facts probe plainly saw). The ARM64 CUDA wheel is admitted only when the detected compute capability exactly matches the compiledsm_121kernel. AMD usesvulkan(fleet-proven RADV); no GPU usescpu. Explicit overrides always win; an INVALID override is never masked by a managed binary (stays a loudinvalid_engine_binaryconflict). Opt-out:SKULK_NO_ENGINE_AUTOPROVISION=1. Provisioning failure logs a warning and the node starts anyway (a node must start without network). Apple Silicon macOS provisions the pinned upstream Metal build (llama-<pin>-bin-macos-arm64.tar.gz, Metal shaders embedded, dylibs beside the binary via@loader_path); its--list-devicesMetal device derivesllama_server-metal. That lane is gated to embeddings (_EMBEDDING_ONLY_LANESinshared/backends.py): MLX keeps owning chat on the Apple GPU, and opening it to other cards would move GGUF chat placements onto Macs before that is qualified. A barellama_servertag never expands to an embedding-only lane (expand_engine_backends); a card names the lane, or the embedding gate opts an embedding card in.-metallanes are admitted against unified memory (backend_offloads_to_vram,_has_gpu_offload_backend), and the runner launches the server under the shared parent watchdog because macOS has no PDEATHSIG. Intel Macs provision nothing. - Packaged distribution: the recommended macOS release is a signed and notarized Apple Silicon app that embeds one exact Skulk source commit, its locked runtime, native components, and built dashboard behind one application identity. Ubuntu/Debian publish
skulkas an exact-version meta-package overskulk-desktopplusskulk-runtimeforamd64andarm64;skulk-runtimeincludes the frozen runtime, launcher, dashboard, and systemd user unit and can be installed alone for a headless node. Homebrew and APT are the current update channels; the app does not yet self-update. - Source installer:
install.shat the repo root (#614 Phase 4): prerequisites (git/toolchain/rustup/uv) -> clone ->uv sync-> dashboard build through the pinnednodejs-wheel-binariesruntime (compatible system Node.js fallback) ->skulk doctor --fix. A normal install fails instead of silently omitting the UI if neither dashboard toolchain works;--headlessis the explicit API-only opt-out.--with-vllmoptionally prepares the same immutable vLLM 0.32.0 runtime that ordinary placement installs on first use. It uses a dedicated environment with uv-managed Python 3.12.13 (including development headers), hashed CUDA 12.9 or ROCm 7.2.3 dependency recipes, and GPU verification. It leaves explicit operator environments unchanged and discovers completed caches on restart. Related hard dependencies:nodejs-wheel-binariesis required on macOS/Linux so the normal installer can always build the dashboard, andnvidia-ml-pyis required on Linux (nothing optional may be load-bearing).
Engine packages (add-on engines)
- Role: engines Skulk does not name in its own code, delivered as signed packages and installed on the node that needs one. One package is one engine build for one platform and one accelerator class, plus an adapter program. The dashboard and the doctor call them add-on engines.
- Lives in:
src/skulk/provisioning/engine_packages.py(manifest contract, signature check, host fit),engine_trust.py(engine publisher trust),engine_index.py(the signed list of published builds),engine_install.py(install, activate, roll back, remove);src/skulk/engines/(inventory.py,on_demand.py,launch.py,protocol.py,adapter.py,estimate.py,actions.py,load_results.py,order_record.py,cli.py);src/skulk/worker/runner/engine_package/(the one generic runner);src/skulk/api/engines.py(the cluster report and change responses);src/skulk/shared/types/engine_packages.pyandengine_orders.py. - Identity: engine ID
publisher.engine; accelerator class (called the lane in code)metal/cuda/rocm/vulkan/cpu; backend tag<engine name>-<lane>; build identity = SHA-256 of the signed manifest claims, which is the generation directory's name, the value inNodeResources.engine_buildsand the build stamped on a shard. - Manifest: signed by an engine publisher with Ed25519 over a domain prefix, so a capability release signature is never accepted. Names the engine archive, the adapter (
pythonor native) and pinned external requirements with exact sizes and digests; a requirement may carryunpack(member paths and total size) so only named members of a.whlor.zipare kept. Declares platform, lane, compute targets, Skulk version range, control-protocol range, adapter Python range, generation, engine version andconservative_overhead_bytes. An optionaldraftingboolean (absent means false) says the build is loaded with drafting on; a manifest without it keeps the identity it always had. - Trust:
v1/engine-trust.json, a second signed target of the capability store's TUF repository, read byengine_trust_client()intoSKULK_DATA_HOME/engine-trust. Separate target, client, retained copy and revision floor from capability publisher trust. Consulted at install only; an installed package starts without it. Refusal codetrust_unavailable. - Engine store:
ENGINE_STORE_URL=https://engines.foxlight.ai/, fixed in host code and separate from the capability store, which only signs engine trust. It servesindex-v1.jsonand, per build,<directory>/manifest.jsonwith the archive and adapter beside it; pinned external requirements are fetched from the addresses their manifest names. Nothing there is trusted unverified. - Index:
index-v1.jsonunderENGINE_STORE_URL, signed under its own domain prefix, at most 512 KiB, kept inSKULK_DATA_HOME/engine-index. Decides offers only; the kept copy is the revision floor. The worker refreshes it 60 s after start and then every 3,600 s. Entries carry channelstableorcandidate. - On disk:
SKULK_ENGINES_DIR/packages/<engine id>/<lane>/<build identity>/{engine,adapter,requirements,manifest.json,installed.json}plusactive.json(active and previous build) and an install lock per lane. Sources:DirectoryPackageSource(air-gapped) orHttpPackageSource. Every file is checked against its signed size and digest; a generation is renamed into place only when complete.verify_installed_engine(deep=False)compares names, sizes, links and executable bits;deep=Truehashes every file (done on activation and rollback). - Node facts and telemetry:
NodeFacts.engine_packages,engine_package_builds,engine_package_installable_builds,engine_package_overhead_bytes,engine_package_problems. They reachNodeResources.backends,engine_builds,installable_engine_builds,on_demand_backends,engine_memory_settings(one entry per package backend tag) andengine_packages(NodeEnginePackage: statusactive/unusable/offered, build, versions, builds on disk, rollback build, problem, sizes, load results).engine_packagesis left off the wire when empty, so a node with none is unchanged. Placement reads the first five, and fromengine_packagesonlyunsupported_models(and an offered build's download size for a preview); the rest ofengine_packagesis for the report. - Unusable reasons: an installer refusal (
installation_damaged,generation_missing), a fit refusal read again at every listing (skulk_version_unsupported,protocol_unsupported,adapter_python_unsupported), orbackend_tag_ambiguous(a tag claimed twice, reserved, or a built-in engine's). - Engine order: three levels, first with an answer for a node wins: the person's order for the model (
State.model_engine_orders, at most 512 models and 16 tags each, saved per node inSKULK_DATA_HOME/engine-orders/model-engine-orders.json), the card'splacement.backend_preference, then the built-in fallback with packages after built-in engines.PlaceInstance.engine_orderandBaseInstance.engine_ordercarry an order for one launch; repairs keep it. An order only ranks. - Eligibility: a package is eligible for a model when the card names it in
placement.compatible_backends(bare engine name or one backend tag), or when the registry's signed engine-support list has asupported,upstream_compatibilityentry matching the card'sregistry_architecture,registry_artifact_format, quantization and a claimed capability whoseengineis the package's engine name or backend tag (registry_compatible_backends_for_node, read through_card_platform_backends). A card without a curated architecture carriesunknown:<card id>, so an entry for it covers that card only.place_instancetakes every package off offer for a placement with asystem_role(without_engine_packages): the steward needs tools and the package chat dialect has none._card_platform_backendsdrops package tags for a card that serves music, image, video, speech, embeddings or separation; a text card with avisionsection keeps them, and the runner refuses an image request (unsupported_request_reason). - Admission: weights plus the build's declared overhead. Before dispatching a load the worker asks the adapter (
estimate, 10 s) and sendsEnginePackageNeedStated; the master keepsState.engine_package_needs[runner]and reserves the larger of that and its own estimate. The engine reports need only, never what is free. - Load settings (
worker/runner/engine_package/request.py): stated outright to the adapter for bothestimateandload: the stamped context window, one stream (PARALLEL_STREAMS), cache precisiondefault, anddrafting, which is the installed build's manifest claim and nothing else. A load whose applied settings differ from the stated ones fails (settings_changed). Requests beyond the stream count wait in the runner's own queue (ServedConcurrentDispatchwithqueue_admitted=True, boundMAX_WAITING_REQUESTS= 256, the supervisor task channel's figure), oldest first; the loop keeps reading and acknowledging while its slot is busy, so the worker'sstart_tasknever waits on it and aCancelTaskfor a waiting request is delivered and drops it before it reaches the engine. A request past the bound fails at once withWAITING_LIMIT_MESSAGE. The queue-less form of the loop must not be used at one slot: it stops reading after the first waiting request, which holds the worker's planning loop until the slot frees. - Install on demand: an offered build is placed like a built-in on-demand engine. The worker's
InstallEnginetask (engine= package engine name,expected_build= the stamped build) installs and activates exactly that build;LoadModelwaits. The runner process starts before the install (so the model downloads meanwhile): the worker tells it the package is on its way (RunnerSupervisor.create(engine_package_awaited=True)), and the generic runner then reads the package at load instead of refusing an unknown engine at start. A package nobody is installing is still refused at start. The same gates apply as for built-in engines: offline,SKULK_NO_ENGINE_AUTOPROVISION=1, a node that runs no models, or packages turned off. - Launch contract (
engines/launch.py): a Python adapter runs under this node's interpreter in isolated mode with bytecode writing off; a native adapter runs directly. Environment built from nothing:SKULK_ENGINE_ID,SKULK_ENGINE_LANE,SKULK_ENGINE_BUILD_DIGEST,SKULK_ENGINE_GENERATION,SKULK_ENGINE_EXECUTABLE,SKULK_ENGINE_STATE,SKULK_ENGINE_REQUIREMENTSwhen the package pins requirements, a private home, cache and temporary directory,PATH=/usr/bin:/bin. Working directory is the state directorySKULK_ENGINES_DIR/package-state/<build identity>; the generation is never written; standard error goes to a private log capped at 8 MiB. - Control protocol (
engines/protocol.py, version 1): four-byte big-endian length then a UTF-8 JSON object of at most 64 KiB, over the adapter's standard input and output. Messages:hello,describe,probe,estimate,load,health,cancel,unload,stop, anderror. Each carriestype,sequenceandbuild_digest. Unknown fields and types are refused. Deadlines: start 30 s, default call 30 s, load 900 s, health and cancel 10 s, unload 20 s. Calls are serialized and never replayed after an uncertain outcome; a channel failure ends the session and its process group. - Data path:
loadreturns a loopback port serving chat dialect version 1 (POST /v1/chat/completions, streamed, with usage). The runner proxies generation to it. A 400 whosecodeortypeiscontext_length_exceededis a context overflow. The dialect carries no tools, images or logprobs:engines/dialect.pyholds the rule, the API's shared text dispatch point (_send_text_generation_with_images) answers 400 before dispatch when every instance the request could reach runs on a package (engine_package_refusal), and the runner applies the same rule as the final guard. Active generations own asynchronous HTTP reads and an independent cancellation observer (50 ms poll); control cancellation is serialized and its thread drained before permit reuse. An absent response ID or unconfirmed/mismatched acknowledgement retires the owned adapter; normal health failure replaces the runner. No generation read timeout is introduced. Successful completion requires a finish event and[DONE]; premature EOF emits an error and settles remaining engine work before permit reuse. Declared HTTP/stream refusals remain terminal outcomes. Settlement is shielded from observer shutdown and attempted only once; incomplete work never reports successful task completion. Retirement clearsbase_urlbefore permit reuse, so queued work cannot reach a new listener on the former port. - Shutdown: owned adapter close runs in
finallyeven when unload is interrupted.RunnerSupervisorgrants package backends 45 seconds for an active control exchange (10 s), unload (20 s), stop/drain/reap (up to 9 s), then 10 seconds after SIGTERM before KILL. Built-in runner grace is unchanged. - Load results:
engines/load_results.pykeeps the newest result per build (loaded,refusedwith the engine's code,failed) in process memory, bounded to 64 tags and 16 builds per tag, and attaches them to the report. Never persisted or replicated, and as last results never read by placement. - Refused loads fall back: a typed load refusal is marked
engine-load-refused. The worker sendsRefuseInstancePlacementwithengine_refusal_code; the master (_replace_engine_refused_instance) deletes the instance, records the failure (placement_failed, the engine's code only) and places the model again at the same width with the refusing build off offer (without_engine_builds), so the model's engine order picks the next engine. The refused instance's nodes are tried first (required_nodes), then the cluster._engine_refusal_lineage(master-local, at most 256) carries every build that refused earlier in the same chain to the replacement, so a chain is bounded by the number of builds. With no other engine the instance is torn down and the record says so. The node stays eligible for other models. - Unsupported models: a refusal with code
unsupported_modeldepends on the build and the model only. The node keeps it per build and model (EngineLoadResults.unsupported_for_tag, at most 32 per tag, cleared by a later successful load of that model on that build, by the build leaving the node, or by a restart) and reports it asNodeEnginePackage.unsupported_models.place_instanceand the unstamped shards ofadd_instance_to_placementstake every build that any node reports for the model off offer (engine_builds_unsupporting), on every node that holds or could install it, so later launches, repairs and previews go straight to the next engine. Other refusal codes are not remembered. A shard that names its engine explicitly keeps it. - Changes:
change_engine_package()(engines/actions.py) activates, rolls back or removes on the node that holds the package. Refusal codes:packages_disabled,generation_missing,installation_damaged, the three fit codes,generation_active,generation_in_use. Flow: API waits up to 100 s; master ordersEnginePackageChangeRequestedwith a 120 s expiry; the target worker answersEnginePackageChangeCompletedwith its freshNodeResources. - Settings:
engines.packages_enabledandengines.package_channelinskulk.yaml, re-read by each worker every 60 s.SKULK_ENGINE_PACKAGES_DISABLE=1turns packages off on one node at launch. With packages off the inventory is empty whatever is installed, andGET /v1/enginesreportspackagesEnabled: false. - Surfaces:
GET /v1/engines,POST /v1/engines/{engine_id}/{activate,rollback,remove},GET /models/engine-orders,PUTandDELETE /models/engine-order;skulk engines list|activate|rollback|remove; dashboard Settings, Add-on engines, "Engines on your machines"; doctor checkengine-packages. - Invariants: no engine name in core; a node with no package and none offered is byte-for-byte unchanged; a running model keeps its build; nothing a model runs on is removed; engine trust and capability trust never share a key or a client; the index never causes or authorizes an installation.
Storage
-
Event log:
src/skulk/utils/disk_event_log.py: append-only length-prefixed msgpack records (events.bin, uncompressed live); rotated archives are zstd-compressed (events.*.bin.zst) on rotation/close. Disk is treated as bounded: archives are capped by count (5) AND total bytes (1 GiB); any persistence failure (ENOSPC at init, append, or compaction) drops the log into a degraded counting-only mode with one CRITICAL line (indices keep advancing so follower replay coherence survives), and a proactive free-space floor (2 GiB, checked every 1024 appends) degrades BEFORE the disk hits zero. The API-side log (event_log/api/, backsGET /eventsdiagnostics only and records the replicated durable control stream) additionally ring-compacts: past 256 MiB of active file it keeps only the most recent 20k events. -
Model cache:
SKULK_MODELS_DIR(defaultSKULK_DATA_HOME/models; on Linux that's~/.local/share/skulk/modelsvia XDG, on macOS/Windows it's~/.skulk/models);SKULK_HOMEandSKULK_MODELS_DIRenv overrides apply -
Custom cards:
SKULK_CUSTOM_MODEL_CARDS_DIR(defaultSKULK_DATA_HOME/custom_model_cards) as TOML. A custom card overrides the signed or installed card for the same model id (#652 operator-override semantics) with one exception: machine-generated cards (fetch_from_hf) are stamped withgenerator_revision(CARD_GENERATOR_REVISIONinmodel_cards.py; bump it whenever generated output changes in a way that makes old cards worse than regenerating), and at load a stamped card OLDER than the current revision is superseded by the signed or installed card with a loud warning (a generated card is cached metadata plus generator logic, not operator intent; a stale one silently pins wrong engine selection, the fresh-fleet audit failure). An UNSTAMPED card is treated as hand-authored and keeps full override power; stale generated cards with no signed or installed counterpart still serve, with a regenerate-suggestion warning. Deleting a custom card rebuilds the catalog: the signed or installed card for that id takes its place, or the model leaves the catalog when neither exists. An executable custom card with no immutable source revision is not authorized merely because it survived an upgrade: runner validation blocks it until the operator re-adds it through the revision-pinning flow. -
External card registry:
src/skulk/shared/models/registry.pyuses stock python-tuf with a package-embedded root to verify schema-v2v1/catalog.json.model_cards.pyinstalls the complete signed snapshot and refreshes at most once per 60 seconds; custom cards remain final overrides. Successful targets produce a hash-bound last-known-good cache accepted for at most 30 days. While the registry cannot be read,get_association_cards()adds that cache's cards (read byload_cached_catalog()without the age limit) to the listed catalog for installed-artifact association only. The cache is never listed or placed from; an artifact it matches gains its own installed-card record and is then listed and served like any installed model. Registry aliases are runtime/store identities whileModelCard.source_repositoryremains the upstream byte origin, so exact quants in one repo do not collapse. Signed envelope-v2 cards may add a strictartifact_bundle: one content-derived executable bundle with an optional repository-relative loader root and an exact path/size/upstream-object manifest. Direct and store downloaders fetch only that allow-list, verify immutable metadata, preserve repository layout, and resolve engine loading beneath the declared root. When a model store is configured,Node._refresh_store_installed_cardsreads the store registry on each artifact-inventory pass (10 s bound, last answer kept on failure) and passes the store's base installed records tomodel_cards.record_store_installed_cards; the API's own five-second store read for the model list passes them on too. Custom records are left out. The card of the generation the store holds is then the active card of that alias on every node (_store_generation_card,_apply_store_generations): over a node-local installed record of another generation, older or newer, and for an alias the node holds no copy of, on the directory-scan, live-registration and store-read paths. A custom card keeps its precedence, and a store that holds the current signed card yields the registry's own copy of it. A newer signed card stays an update the store has not taken. The store refuses a base download request that names another signed card while it holds the current one (ModelStore._refuse_a_card_the_store_has_moved_past, decided under the download admission lock with the current card ID the server passes in; HTTP 409), so a launch made from a node that has not read the store since an update cannot put the older card back (store_installed_recordsinstore/installed_cards.pyis the shared validator the API's model list uses too). Bundle identity participates in installed generations and store keys, so multiple aliases may safely share a repository and revision; v1 cards retain their previous repository-wide tensor or pinned-GGUF behavior. Signed aliases are path-safe repository identifiers and signed payloads are forcibly non-custom, so catalog content cannot escape staging or opt out of registry revocation. Provenance (foxlight,agent, orcommunity) is signed catalog metadata outside immutable card identity. Structural validity activates a card; runtime evidence independently governs verified/recommended policy. Every separately hosted companion artifact carries its own full revision; a companion in the base artifact repository inheritssource_revision. Publishing any revision-pinned TUF-verified card authorizes the exact repository content it selects regardless of provenance; explicit custom-card addition is the corresponding operator decision and ordinary Hub additions resolvemainonce to an immutable commit. Historical cluster approval state and endpoints remain inert compatibility surfaces. Canonical-store requests carry the immutable card ID, which the store host verifies against its own complete catalog before downloading. Runner load separately verifies the installed-card sidecar, pinned revision, repository, selected file, and bundle identity; deterministic identity failures tear the instance down without retrying the unchanged generation. -
Canonical signed-bundle reuse:
ModelStore._reuse_verified_bundle_fileshashes registered files at the same immutable repository/revision against each selected member's signed SHA-256 and size, then hardlinks them before disk admission. A failed link earns no free-space credit; no copy fallback is allowed. Each bundle keeps its own installed generation and alias deletion unlinks only its own paths. Hash threads are read-only so cancellation cannot leave a writer running after the transfer lock is released. Canonical-store eviction and the 10 GiB reserve are unchanged. The reader accepts exactly catalog schema v2 and card-envelope schemas v1 and v2; later signed versions fail closed until an explicit parser upgrade lands. -
No shipped model cards: Skulk ships none; when a model is downloaded, so is its card. The catalog is signed registry cards, installed cards (
.skulk/installed-card.json, or a detached record for a read-only model root; no expiry), and custom cards.SKULK_OFFLINE=trueandskulk --offlineleave installed plus custom cards, with the cached catalog used for association only. A catalog left empty (registry never reached, nothing installed, no custom card) logs one warning per cause naming the remedies: connect once, copy a model directory with its.skulk/installed-card.json, or add a custom card. Curated cards live in thefoxlight-model-registryrepository'sseed/cards/; card edits go there, never into Skulk. Tests carry fixture copies of a few registry cards undersrc/skulk/shared/tests/fixtures/model_cards/, loaded throughsrc/skulk/shared/tests/model_card_fixtures.py, andtest_skulk_ships_no_model_cardsrefuses any TOML declaring amodel_idundersrc/skulk/resources. -
Optional model store: shared canonical host with resumable, range-capable HTTP staging (
src/skulk/store/). A node that starts withoutskulk.yamlwrites the same per-node bootstrap store configinstall.shwrites (write_bootstrap_config_if_absent, store inSKULK_DATA_HOME/model-store), so packaged and source installs start alike;PUT /configfills an enabled store's blank host and path frombootstrap_model_store_config(exposed aseffective.model_store_defaults); with no store configured,POST /store/models/{id}/downloadsends a whole-modelStartDownloadto the answering node and reportsdestination: node; after election, followers retrySTATE_SYNC_MESSAGESconfig bootstrap, receive the elected master's routablestore_http_host, stop superseded local servers, and repoint API plus worker clients together so the fleet has one canonical store. Explicit identicalstore_hostconfiguration still selects a different machine. Store-host staging hardlinks store files into the staging directory (ModelStoreClient._link_or_copy; store files are immutable once registered, staged files never mutated in place) with ashutil.copy2fallback on EXDEV/EPERM, so same-filesystem staging doubles no disk. Pinnedsource_revisionartifacts load from a revision-qualified canonical directory and staged copies carry.skulk-source-revisionmarkers; a revision mismatch replaces the copy instead of reusing it (see "Download progress admission" below and the model-store narrative in Architecture). Reachability is part of the resolution contract (#657):StoreUnreachableError(transport-level, distinct fromModelNotInStoreError) is raised after a small probe budget (3 attempts vs the 12-attempt transfer budget; a URL that cannot even be requested, such as one built from an empty host, classifies immediately with no retries) and routesModelStoreDownloaderto its inner direct-Hugging-Face path whenallow_hf_fallbackis on. An enabledmodel_storewith a blankstore_hostorstore_pathin a hand-editedskulk.yamlis refused at node startup, since that shape matches no store host and can never work (#888); Settings andPUT /configsaves fill those blanks witheffective.model_store_defaultsinstead of refusing — store-first when the store answers ("not present" still fetches via the store host), direct-origin when it never answers (the remote-member shape). The fallback preservessource_revision/pinned-GGUF semantics (it is the pre-store HF path), logs loudly, and with fallback disabled fails naming unreachability rather than claiming the model is missing. -
Installed artifact truth and reconciliation: every complete canonical or staged artifact owns
.skulk/installed-card.json(InstalledCardRecord: full card, registry snapshot/provenance, exact artifact selection, verification state, companion ownership, canonical file hashes); read-only model roots store the same path-and-manifest-bound record under Skulk's data directory.registry.jsonis schema-tolerant and rebuildable from sidecars; incomplete indexed generations are removed so healthy peer replicas remain importable. Installed cards load before registry access and remain active offline without the TUF last-known-good age limit.StoreReconcilerbehavior lives in the API/store plane: it polls/store/storageacross staging, direct-download, and read-only model roots, deduplicates replicas by installed identity plus manifest digest, obtains a target-bound expiring capability from/store/internal/exports, and asks the loopback-only store/importstransaction to resume, hash, and atomically publish the artifact. Inventory never enters replicated State or the event log. Operator deletion first records a schema-versioned.skulk/reconciliation-tombstones.jsonalias tombstone under the canonical store; automatic imports reject matching base artifacts and owned companions even if a node missed eviction, while cache placement remains visible. Deletion shares the publication lock, and only a successful explicit upstream download clears suppression.model_store.reconciliationcontrols enablement, inventory-only rollout, and polling interval. -
Installed-card cache invalidation: legacy directory association requires the existing model-completeness checks before writing a sidecar. LRU eviction, purge, explicit delete, stale-generation replacement, and distributed staged eviction unregister the removed base alias immediately and mark the process catalog dirty; the next read rebuilds installed state from remaining complete sidecars before registry access.
-
Reconciliation startup and recovery selection: the API reports the delayed first reconciliation pass as
scanningbefore sleeping, preventing operator clients from treating startupidleas convergence. Post-TUF registry-index recovery ranks companion generations with the current signed identity of their owning base alias, not the companion repository alias. -
Internal import boundary and compatibility:
/importsrequires a direct loopback socket and rejectsForwarded,X-Forwarded-*, andX-Real-IPheaders. A peer claim ofregistry_verifiedis rebound to the store host's independently TUF-verified immutable card payload and exact base/companion artifact identity before transfer. Reconciliation asks the running store to adopt complete adjacent sidecars into legacy canonical index entries under the publication lock before computing missing identities, so an upgraded store never imports its own bytes back into itself. Omittingregistry_card_idon the store download protocol remains backward-compatible by selecting the current card for that alias; an explicit ID still selects and verifies that exact generation.
Pubsub topics
Defined in src/skulk/routing/topics.py.
| Topic | Wire payload type | Inner payload | Publisher | Consumer |
|---|---|---|---|---|
GLOBAL_EVENTS | GlobalForwarderEvent | indexed Event (post-master indexing) | Master | All nodes |
LOCAL_EVENTS | LocalForwarderEvent | un-indexed Event | Workers (via event_router.py) | Master |
COMMANDS | ForwarderCommand | Command (PlaceInstance, DeleteInstance, RefuseInstancePlacement, TaskFinished, SetTracingEnabled, etc.) | API, Worker (RefuseInstancePlacement) | Master (command processor); Election (every node, observing commands to inform leader-changeover decisions) |
DOWNLOAD_COMMANDS | ForwarderDownloadCommand | DownloadCommand (StartDownload, DeleteDownload, CancelDownload, SyncConfig, PurgeStagingCache, RestartNode) | API (download/restart/sync admin ops), Master, Workers | All nodes |
STATE_SYNC_MESSAGES | StateSyncMessage | bidirectional: followers retry kind="request" through startup for snapshot/config bootstrap; master publishes kind="response" with the requested payload (StateSnapshotHydrated etc.) and its routable authoritative store address | All nodes (request: followers; response: master) | All nodes |
ELECTION_MESSAGES | ElectionMessage | bully election rounds on dedicated Python egress and a dedicated gossipsub behavior/protocol and handler queue; deduplicated legacy copy during migration | All nodes | All nodes |
AUTHORITY_MESSAGES | AuthorityNetworkEnvelope | signed stable-installation-addressed prepare/promise/accept/vote/commit/catch-up metadata; no secret authority payloads | Future authority service; deterministic harness today | Future authority service; registered router topic is otherwise dormant |
CONNECTION_MESSAGES | libp2p connection updates | peer arrivals / departures | Router | All nodes |
TELEMETRY | NodeTelemetry | GatheredInfo plus non-terminal DownloadPending / DownloadOngoing; bounded latest-value admission and an isolated gossipsub protocol | Workers | All nodes (applied into TelemetryView) |
OUTPUT_MEDIA | OutputMediaPacket | finished video container or thumbnail as raw frames: opened -> chunk* -> completed from the producing worker, accepted / transport_failed back from the owning API; node-addressed by target_node, stream-keyed by command, purpose, and source | Worker (render output) and API (acknowledgements) | Owning API (VideoStore assembly) and the producing worker |
DATA | DataChunk | {command_id, kind, chunk?, sequence, owner_node}: explicit started/chunk/completed/failed/cancelled lifecycle for token, image, video progress, embedding, transcription, and audio output | One serving output worker: rank 0 for text/embedding/speech, primary terminal stage for image generation | Owning API node only on Zenoh; API nodes on gossipsub; master does NOT consume it |
Telemetry plane (#279)
TELEMETRY carries readings that are last-write-wins and not decisions instead of event-sourcing them into State. Local producers offer without blocking into a 256-key OrderedDict: an existing node/reading key is replaced, and only a full map of distinct keys evicts its oldest entry. Download progress keys also include model ID. One serialized packet can wait beyond the in-flight publish. A dedicated Python egress loop feeds a second Rust gossipsub behavior negotiated under /skulk/telemetry/meshsub, with independent per-peer handler queues from ordinary control and election traffic. GET /v1/diagnostics/telemetry exposes aggregate capacities, depths, coalescing, drops, publish failures/bytes, no-peer publish count, and pending age without retaining payloads or completed identifiers. No-peer publish outcomes (NoPeersSubscribedToTopicError) are counted distinctly from transport-pressure failures and, when sustained past 30s, emit a rate-limited (60s) warning naming the consequence: a connected node whose telemetry protocol has no peers is invisible to membership while looking healthy locally, the signature of a build/wire mismatch (#660; observed live as a fully-synced ghost node during the 2026-07-22 remote-join spike).
The Rust telemetry publisher additionally reports its actual subscriber state
when NoPeersSubscribedToTopic persists with authenticated connected peers:
30-second grace, then at most one warning per 60 seconds. Counts cover connected
peers, known telemetry peers and negotiated protocol counts, topic subscribers and mesh peers, plus
the local subscription flag. No peer identifiers, addresses or payloads are
retained. A standalone node stays quiet. Reporting changes neither wire protocol
nor subscriptions; it uses normal PyO3 warning logging, not a RUST_LOG debug
filter or the suppressed raw gossipsub behaviour dumps.
Performance envelopes (observe-only; adaptive concurrency, Phase 0). The API node records one observation per completed generation into an in-memory PerformanceEnvelopeRegistry (src/skulk/api/performance_envelope.py), keyed by (hardware class, model, engine+backend, quantization) and bucketed by the in-flight concurrency the serving instance was handling when the generation began. Each bucket keeps a bounded reservoir of time-to-first-token and steady-state decode-rate samples; the read side computes per-bucket p50/p90 TTFT, mean/p50 decode tokens/second, aggregate decode throughput, and a simple knee (the concurrency where aggregate throughput peaks). A stream tap (API._tap_performance_envelope, a guarded passthrough alongside the field-telemetry tap) feeds it, and it wraps every text-generation surface through one shared helper (API._tapped_text_stream: chat completions, the Claude/Responses adapters, the Ollama endpoints, realtime assistant turns), not only /v1/chat/completions. Concurrency attribution is per serving instance and comes from the runner itself: the served engines (llama_server, vLLM) stamp their own serving node, resolved backend, in-flight-at-admission count, and batching mode onto the terminal GenerationStats (ServedConcurrentDispatch.stamp_runner_stats), and the in-process MLX runner does the same (Runner._stamp_stats in worker/runner/llm_inference/), reporting serving_batches=True and its batch position at admission when running the batch generator (BatchGenerator), serial when running the SequentialGenerator. The in-process llama_cpp runner stamps through the same mixin fields at its width of 1 (#692), on both the streaming and tool paths, so the registry sees the engine that was previously invisible to it. So the observation is correct across replicas and when several API nodes drive one instance, and reflects the true batch width regardless of engine. MLX is a batching engine on the batch path, not serial, which is why it must report rather than let the API guess. Only when a runner reports no serving node (a stats-less terminal, or the pre-gossip window before the shard's resolved_backend is stamped) does the tap fall back to this API node's outstanding-request count (_resolve_envelope_context, which records only when exactly one instance serves the model and skips served backends it cannot classify without the stamp). Hardware class comes from the serving node's AcceleratorMetrics + RAM tier via hardware_class(); quantization from the model card. It is exposed through GET /v1/diagnostics/performance-envelopes (local) and /v1/diagnostics/performance-envelopes/cluster (fan-out), rendered by the dashboard Performance tab. The explicit benchmark API retains the non-identifying serving_batches and in_flight_at_admission values so black-box release qualification can prove real batching; ordinary generation streams redact all runner-attribution fields, and node ids plus backend tags are always redacted. It changes no serving behavior and never touches State, the event log, or the telemetry gossip plane; the schema mirrors the harness concurrent suite fields so offline and online curves compose. The runner-reported serving fields on GenerationStats ride the DATA plane, so this is a same-version-fleet wire addition.
Slice 1 moved node_resources (a node's participation role, backends, and resolved data_transport); slice 2 moved node_memory and node_system (the highest-volume readings, carried together by MactopMetrics/MacmonMetrics); slice 3 moved the observational readings node_identities, node_disk, and node_rdma_ctl. The set that rides telemetry is TELEMETRY_PLANE_INFO in shared/types/telemetry.py; the worker forwards those GatheredInfo variants to the telemetry sender (worker/main.py), and apply_node_gathered_info treats them as no-ops (shared/apply.py). The set includes the payload-free NodeHeartbeat, published every two seconds as the named primary liveness reading. TelemetryView.node_last_heartbeat stores its local receipt time separately from node_last_telemetry, which stores ordinary telemetry receipt as a fallback. The TelemetryView survives master re-election (Node-owned), so a freshly promoted master does not start blind, and these readings are no longer carried in the failover seed (session_carryover.py). GET /state merges them back in from the view (API.get_cluster_state) so the dashboard's wire shape is unchanged. nodeResources.dataTransport is the router's startup-resolved gossipsub/zenoh choice, injected into both initial and election-recreated workers rather than re-derived from environment state. A --no-worker node has no gatherer but still owns DATA receivers, so the node lifecycle publishes an equivalent reading every two seconds with no backends and effective management-only participation; that cadence also supplies fallback liveness below the health-warning threshold. API health/resource filtering includes fresh telemetry-only participants, local or remote, because replicated worker membership can omit management nodes; the shared 30-second liveness timeout keeps stopped telemetry-only participants from becoming ghosts. compute_node_health emits error-level data_transport_mismatch reasons for every live node when both values are positively advertised; missing startup telemetry is unknown, not a mismatch. Node identity is assembled from two readings (MiscData friendly-name + StaticNodeInformation static fields), so TelemetryView.apply merges them into one NodeIdentity rather than overwriting. Fabric-citizenship adds node_capabilities to the view: extension-advertised capability tags carried by the NodeCapabilities reading (the write half of the plane; see the extension advertise_capability fact above). The view also holds the node's OWN outbound local_advertised_capabilities set, which is NOT a peer reading and so is deliberately not pruned when a peer times out. The same pattern carries capability-node summaries: node_capability_nodes and node_capability_nodes_received_at are peer readings (pruned; cleared by an empty NodeCapabilityNodes), while local_capability_nodes is this host's outbound map.
Election transport isolation. Python's Router gives ELECTION_MESSAGES its own bounded egress channel and publish loop instead of placing election behind the ordinary control/telemetry FIFO. rust/networking/src/swarm.rs composes two gossipsub behaviors into one libp2p swarm; the isolated behavior negotiates /skulk/election/meshsub/{1.1.0,1.0.0} and owns a separate per-peer connection-handler queue. During the migration window, election subscriptions and publications also use the default behavior so old and new binaries remain interoperable through a staggered upgrade. Election deduplicates identical candidates received over both protocols. Queue saturation on the shared path can therefore delay or drop ordinary fan-out without removing the isolated election path, while rolling compatibility does not double-count votes. A two-peer Rust integration test verifies custom-protocol negotiation and message delivery.
Connection stability. rust/networking/src/discovery.rs still dials every address once when mDNS first advertises it, preserving reachable Thunderbolt and other multi-homed paths. Each node repeats its mDNS query every 60 seconds (MDNS_QUERY_INTERVAL), because libp2p stops start-up probing at the first answer and multicast packets are lost often enough, especially over Wi-Fi, that a single exchange per pair is not reliable; records keep a 2,500-second TTL so ordinary loss does not expire a known peer. After a peer is connected on any path, failed link-local addresses are retried every 12 discovery rounds (60 seconds) rather than every five seconds; routable paths keep the normal retry cadence. Ping uses a five-second interval and timeout, and one socket closes only after three consecutive failures, with success resetting that socket's counter. The independent Python API reachability sweep continues probing advertised addresses so a working direct path can become a placement and ring-transport candidate. Together these rules retain fast links while keeping repeated link-local transport dials and transient scheduler stalls from manufacturing connection churn.
Download progress admission. Raw repository callbacks are first coalesced per file and normalized against the model store's canonical byte total. DownloadCoordinator then applies a monotonic per-attempt fraction high-water mark (5% steps, one-second floor, 30-second heartbeat). DownloadPending is an ordered lifecycle boundary; DownloadCompleted and DownloadFailed are the only download outcomes stored in event-sourced State; new DownloadOngoing values use bounded latest-value telemetry. TelemetryView.effective_downloads() overlays those live values for placement, workers, node health, and /state. Every new attempt/reset receives a DownloadAttemptId; terminal control events record it, and the view rejects mismatched or post-terminal telemetry, making cross-protocol reordering harmless. Legacy ongoing events still decode but apply() treats them as no-ops. A card's optional source_revision is also part of artifact identity: repository metadata and bytes are read at that full Hugging Face commit, store entries persist it, and direct/store staging caches carry a revision marker. A mismatch invalidates completed download shortcuts and replaces the staged or canonical copy instead of reusing mutable bytes.
Node artifact availability. NodeArtifactInventory is one compact, bounded, last-write-wins reading per node. Each node_cache entry carries only model ID, installed identity, byte count, manifest completeness, last-use time, and live-use state; the reading also carries store_host and truncated. The node-owned publisher runs with or without an HTTP API, scans immediately, debounces event-driven rescans, and repairs every 60 seconds. Detached installed-card records on read-only roots receive full hash verification once per stable file-stat fingerprint; subsequent operator scans reuse that process-local result, while any path/device/inode/size/mtime/ctime change forces a new hash pass. TelemetryView stores the local receipt timestamp, marks readings stale after 120 seconds, and prunes them with membership. The canonical store catalog, cards, and manifests never enter this reading. GET /store/registry identifies the store hosts from telemetry, reports them additively as cache_inventory.store_nodes, synthesizes exact store_local entries when an installed identity is available, projects additional node caches, and reports cache_inventory.state (syncing, current, degraded, or unavailable) plus observed/expected node counts. The store-node list preserves canonical locality for unresolved legacy entries without weakening the exact installed-identity contract. Stale known locations remain visible as partial truth under degraded. This projection never authorizes import, export, deletion, or execution: the reconciler retains direct bounded /store/storage reads and exact installed-identity/manifest verification before capability-bound transfer.
GET /state also attaches a derived nodeHealth map (#388, src/skulk/api/node_health.py, compute_node_health): per live node, a level (ok/warn/error) plus reasons (each code/message/remediation). It is a pure read-only derivation over the same response data: terminal DownloadFailed entries in State.downloads (error, pairs with the master's download-failure recovery #381), low/full models-volume disk from TelemetryView.node_disk (warn/error), and liveness staleness approaching the timeout prune (warn). Capability conflicts from backend derivation (#614) add four HealthCode values mapped one-to-one from NodeResources.capability_conflicts: gpu_serving_disabled (error), gpu_detection_degraded, invalid_engine_binary, and backend_override_conflict (all warn); the message/remediation were composed on the owning node, and severity comes from the shared CONFLICT_ERROR_CODES source of truth. The full HealthCode vocabulary also includes data_transport_mismatch, zenoh_isolated, version_mismatch, and unreachable (see below). Liveness is the freshest of the dedicated heartbeat receipt (TelemetryView.node_last_heartbeat), ordinary telemetry fallback receipt (node_last_telemetry), and State.last_seen (the last indexed control event, not a heartbeat), so the connectivity change-gate/de-dup does not false-warn on a healthy node. The dashboard renders it as an amber/red badge on the topology node whose hover names the problem and its fix.
Normalized accelerator metrics (collector-agnostic GPU telemetry). SystemPerformanceProfile carries an optional accelerator: AcceleratorMetrics block (shared/types/profiling.py): vendor/name/utilization_ratio (0..1)/vram_total_bytes/vram_used_bytes/gtt_total_bytes/power_watts/temperature_celsius/clock_mhz, each None when a collector cannot measure it (distinct from a real 0). gtt_total_bytes is the GPU's GTT (graphics translation table) size, the amount of system RAM the GPU can map. unified_memory (bool | None) and addressable_memory_bytes come from kernel facts in utils/info_gatherer/linux_gpu.py (classify_unified_memory): the GPU's KFD topology node (matched by drm_render_minor) reports a memory bank equal to the VRAM on a discrete card and equal to the TTM page limit (/sys/module/ttm/parameters/pages_limit x page size, amd-ttm's figure) on an APU in the kernel's prefer-GTT mode; without any KFD report, the APU-only device/uma/ interface marks an APU; a contradictory KFD bank or no kernel facts stays None. The unified limit is capped by gtt_total_bytes, since amdgpu allocates from GTT. shared/models/memory_estimate.py amd_unified_memory_limit is the one classifier placement (usable_vram_by_node, unified_memory_gpu_node_ids), the worker load guard and vLLM's ROCm share use; it falls back to GTT above the carve and covering RAM only when the verdict is None. On a unified-memory APU placement counts the addressable host memory toward usable GPU memory (see the PlaceInstance row). The expression is the same regardless of collector; normalization happens at the collector boundary, never downstream. macOS fills it from mactop (vendor="apple", utilization_ratio = gpu_usage/100; unified memory so vram_* stay None). AMD/Linux fills it from a new InfoGatherer._monitor_gpu_linux that reads passive amdgpu sysfs (gpu_busy_percent, mem_info_vram_*, hwmon/power1_average, temp1_input, pp_dpm_sclk via utils/info_gatherer/linux_gpu.py) and publishes a LinuxGpuMetrics telemetry variant carrying only the system profile (memory rides the separate MemoryUsage reading). Passive sysfs reads, never a GPU-colliding poll (the macmon/#249 lesson). NVIDIA/Linux fills it from the same _monitor_gpu_linux loop as an NVML fallthrough (AMD sysfs first, then NVML device 0) via utils/info_gatherer/nvidia_gpu.py: passive NVML queries through a small NvmlLike protocol (pynvml is a guarded import; a HARD dependency on Linux since #614 (nothing optional may be load-bearing), inert without an NVIDIA driver; the CUDA install recipe deployment/cuda/install-deps.sh provides it on CUDA nodes), vendor="nvidia", per-field degradation so one unsupported query never blanks the rest, legacy scalars (gpu_usage percent / temp / sys_power) filled like the AMD collector. CUDA engine advertisement derives from Node Facts (#614): an NVML-visible device implies cuda with SKULK_LLAMA_CPP_BACKENDS as an override, not a prerequisite. The AMD vram_total_bytes exposes a Strix Halo's BIOS-carved GPU VRAM pool, which node memory does not report; placement admits GPU-offload nodes against it (see the PlaceInstance row).
Connectivity readings stay on the control plane. node_network, node_thunderbolt, node_thunderbolt_bridge, and the derived thunderbolt_bridge_cycles are NOT telemetry: apply() builds the RDMA topology graph from node_thunderbolt (MacThunderboltConnections to replace_all_out_rdma_connections) and recomputes TB-bridge cycles from node_network + node_thunderbolt_bridge, and the planner reads node_network for host selection. Those define the graph placement runs on, so they must be ordered event-sourced state, not an unordered last-write-wins plane (#279 slice 3 scoping; refines the original "all of NodeGatheredInfo to telemetry" target). Because they stay on the ordered log but change rarely, the worker forwards a connectivity reading only when its payload differs from the last value the master confirmed indexed (worker/main.py:_forward_info gates on _confirmed_forwarded_info, which _event_applier populates from the master's indexed-event echo; unsorted psutil interface order on Linux is normalized by sorting in get_network_interfaces so an unchanged topology is byte-stable). Gating on the echo rather than on "last sent" matters: the delivery retry (event_router out_for_delivery) is bounded (retry_max_attempts = 6), so a change sent during a long masterless window can be dropped permanently; an unconfirmed reading simply re-sends on the next poll until it lands, then goes quiet. No periodic keepalive is emitted. This keeps the event log flat except for genuine topology changes. Without it, connectivity churn (~2/s per fleet) filled the master's 10k-event REPLAY_TAIL_RETENTION_EVENTS in ~83 min; a joining/failing-over node then replayed that burst and saturated bounded gossipsub send queues into a flap livelock. Liveness is decoupled from these events and carried primarily by the telemetry plane instead. The payload-free NodeHeartbeat publishes every two seconds and is tracked separately from ordinary telemetry fallback. The master warns once at a ten-second heartbeat gap and prunes only when heartbeat, ordinary telemetry, and the last indexed event have all exceeded 30 seconds. The resulting NodeTimedOut.evidence persists each age plus the effective deciding age and timeout. A re-elected master retains the Node-owned telemetry view and sees fresh heartbeats without waiting on a connectivity change.
Topology edges: probes plus established sessions (#662). Each worker's connection sweep (every 10s) HTTP-probes peers' advertised interfaces (/node_id identity readback on port 52415) and emits TopologyEdgeCreated/TopologyEdgeDeleted for verified/lost paths. That alone left a NAT'd or proxied remote member EDGELESS — a floating node in the dashboard, ineligible for placement cycles — because every advertised address is unreachable in both directions while the actual libp2p session works fine. Two changes: (1) each worker records its authenticated libp2p sessions as first-class topology edges (_session_edge_ingress, fed by ConnectionMessage which now carries the connection's observed remote_ip/remote_tcp_port from the Rust discovery layer): noise authentication binds peer id to node id, a STRONGER identity check than the probe's readback; sessions are refcounted per peer and the edge is deleted when the last connection closes. The probe sweep's delete pass only manages port-52415 edges, so it never tears session edges down. (2) Unreachable-address probe backoff: an advertised address that fails three consecutive sweeps is probed only every sixth sweep (~1 min cadence) until it verifies again, ending the warning flood and socket churn that full-rate probing of permanently dead addresses produced on both sides of every WAN membership; an edge whose address sat out a sweep is never deleted on that sweep. Address ADVERTISING is deliberately untouched: link-local paths (Thunderbolt) are load-bearing on same-segment fleets. Never-member reap (#671): apply_topology_edge_deleted runs a worklist seeded with BOTH endpoints, removing any node with no last_seen entry and no remaining IN-edges and cascading through the sinks of each removed node's out-edges so a phantom chain reaps fully; real members always carry last_seen and are NodeTimedOut's to reap, and reaping a live-but-preembryonic node is safe because the membership emission gate means it had no legitimate edges in state and it self-heals within a sweep of membership. Complementary worker rules: session-edge EMISSION is gated on membership (peer in state.last_seen), so a timed-out peer's lingering or reconnecting socket re-mints nothing until it republishes NodeGatheredInfo; the worker keeps socket-truth bookkeeping (_session_edge_counts/_session_emitted_edges) as endpoint memory; and every probe sweep re-emits any live member edge missing from state, so a wrong reap or a same-process recovery heals within one sweep. Ephemeral node ids make a crash-looping never-member mint a NEW phantom per attempt, which is why reap-on-last-edge matters more than the per-event odds suggest.
Placement reads two views. The memory-fit check and the context-admission ceiling read node_memory from the TelemetryView, not State. Because the ceiling must be identical across ranks (divergent verdicts deadlock the collectives) and telemetry is unordered last-write-wins, the master computes the ceiling once at placement time and stamps it onto the instance (BaseInstance.context_token_limit, event-sourced); every worker rank, and the API's admission pre-flight, then read that stamped value instead of recomputing it.
Capability-aware placement (heterogeneous nodes). Backend tags are <engine>-<compute> (mlx-metal, mlx_audio-metal, llama_cpp-vulkan, llama_cpp-rocm, llama_cpp-cuda, llama_cpp-cpu); the engine selects the worker runner class, the compute names the accelerator (src/skulk/shared/backends.py). A node's backends come from the Node Facts pipeline (#614; probe_node_backends in src/skulk/shared/backends.py is now a thin cached delegate into skulk.facts): macOS advertises {mlx, mlx-metal} (plus {mlx_audio, mlx_audio-metal} when mlx_audio imports); other engine tags are derived per engine with precedence declaration > binary device list > hardware vendor inference > CPU floor (see the "Node Facts" component entry), so an unset SKULK_LLAMA_CPP_BACKENDS no longer forces llama_cpp-cpu on a node whose GPU and build are positively observed. Tags gossip in NodeResources.backends on the telemetry plane, alongside NodeResources.capability_conflicts carrying every loud observation-vs-declaration disagreement. A model card's PlacementCardConfig carries two axes orthogonal to memory/topology: compatible_backends (a hard filter: the planner excludes a node when resources.backends & compatible_backends is empty, src/skulk/master/placement.py) and backend_preference (an ordered soft score, _cycle_backend_preference_score). GGUF cards stamp the llama.cpp tags as compatible; MLX text/vision cards keep MLX; speech cards use mlx_audio. Curated GGUF text cards list BOTH llama.cpp engines in compatible_backends but order backend_preference with the served llama_server-* tags ahead of llama_cpp-* (#607): on a node advertising a llama-server binary the model resolves to the served engine, whose --parallel slots scale aggregate throughput under concurrent load where the in-process single-stream runner stays flat (SKULK_LLAMA_SERVER_PARALLEL defaults to the release-qualified 16-slot width, is honored exactly, and uses a unified KV cache so every slot keeps the full stamped window while exact prompt-plus-output reservations queue FIFO before aggregate occupancy exceeds the pool, #689); a node without one falls through to in-process llama_cpp unchanged. Narrative rationale in Architecture "Heterogeneous nodes and capability-aware placement". The master resolves each node's winning backend tag at placement (resolve_node_backend: card compatible_backends ∩ that node's advertised backends, ordered by backend_preference) and stamps it onto the node's shard as resolved_backend (#330); the worker reads that persisted tag at spawn (bootstrap._resolve_text_engine) so dispatch is deterministic from replicated state and cannot disagree with placement, falling back to a node-local re-probe only when the field is absent (resources had not gossiped yet). This also lets a card resolve to different engines per node on a heterogeneous cycle. See website/docs/amd-strix-halo-nodes.md for a non-Mac node.
Adaptive placement and model authorization (#845). Repository-code authorization is model-scoped and follows the card's entry path rather than node placement or evidence provenance. Signed publication and explicit custom-card addition authorize their selected repository content, and an installed card without a registry identity (recorded from a card an earlier Skulk release shipped) stays authorized by that release; no secondary allow-list participates in placement. ModelCard.load is catalog-only and may refresh signed metadata but never fetches or persists an unknown Hub repository; trusted local tooling uses the explicitly named load_or_fetch_from_hf, while network callers must cross authenticated /models/add or /models/add-card. GET /instance/previews and POST /place_instance invoke the same planner against current facts, and an unavailable first engine choice falls through to the next admissible node/backend without a client selecting or reserving a preview. Historical State.model_trust_approved_remote_code_identities, approval commands/events, configuration, and endpoints remain inert rolling-upgrade compatibility surfaces. Caller-specified POST /instance rejects embedded shard cards that differ from the effective authorized catalog card, including same-alias content changes, with model_card_identity_mismatch. The elected master repeats exact-card validation for both quick and exact placement commands against its command-ordered catalog view, so a replacement or deletion ordered after API lookup but before placement prevents the stale card from launching. Exact authorization comparison excludes only registry_snapshot_id, the publication containing an otherwise immutable card. Backend and hardware identifiers remain open strings, so new engines do not require a wire-contract enum change.
Model-add operator boundary. POST /models/add requires a direct loopback or trusted-fabric request (private LAN or CGNAT socket peer, no proxy-shaped headers, browser Origin on the same trust classes or naming one of this node's own hostnames including its MagicDNS name, which admits hostname-browsed dashboards while staying DNS-rebinding-proof) or an authenticated operator-gateway request carrying operations:write; the trusted-fabric admission matches the cluster's standing posture (such a peer can already join the mesh as a full member) and lets a LAN-browsed dashboard add models. POST /models/add-card remains loopback-or-gateway only. The add action is the repository-code authorization decision. Both paths withhold success until the exact command-correlated card mutation is ordered, persisted, and visible in the responding API catalog. Historical executable custom cards without immutable revisions fail closed and must be re-added; executable installed cards without a registry identity likewise require an immutable source revision. Every separately hosted processor, vision-weight, assistant, MTP, or speculative-draft companion requires its matching immutable revision on signed, custom, and installed cards. Installed custom-card sidecars retain artifact truth but never recreate selectable catalog authorization after the durable custom TOML is deleted. The operator-only POST /download/start route requires its embedded shard card to exactly match current authorized catalog truth before dispatch. OperatorGatewayAuthorization stamps an internal ASGI scope marker only after bearer validation; canonical handlers never trust a caller-provided header. POST|DELETE /models/remote-code-approvals/{card_id} and model_trust configuration remain deprecated compatibility surfaces and have no effect on current model execution. Config broadcasts carry hf_token over the PSK-encrypted fabric so a token entered on any node converges fleet-wide (the store host and allow_hf_fallback workers are the nodes that actually fetch); an absent-or-blank incoming token never erases a recipient's local one, every write remains atomic mode-0o600, and the HTTP GET /config surface still never returns the token.
Headless exact-card qualification. POST /models/add-card and DELETE /models/custom/{model_id} additionally accept the exact high-entropy bearer configured as SKULK_EXACT_CARD_QUALIFICATION_TOKEN; no other handler accepts that service credential. Comparison is constant-time and values shorter than 32 characters are never active. The add path requires a full immutable source revision, clears every registry_* trust field, authorizes the exact temporary card by that add action, and assigns the persisted qualification_only ownership marker only to service-authenticated installs. A service caller cannot replace or delete any pre-existing non-qualification card; only loopback or an authenticated operator may manage operator-owned exact or custom cards. Service cleanup supplies the complete original candidate card, and the command carries that expected unsigned card to the elected master, which requires exact equality against its serialized ordered view before emitting a delete event. An older job therefore cannot delete a newer qualification card that reused the alias. Older indexed echoes never rewrite newer command-time truth; a promoted master lazily seeds a fresh view from its converged catalog, and later signed-registry refreshes supersede stale signed or qualification-owned entries without displacing operator custom truth. Add and service-cleanup success are withheld until that command ID's exact event has persisted and converged into the responding API catalog, so pre-existing state cannot acknowledge a retry; conflicts and timeouts fail explicitly. Downloaded artifacts remain durable after cleanup, but installed records carrying qualification_only are not projected back into the catalog after the lifecycle custom file is removed. qualification_only remains lifecycle ownership rather than executable artifact truth.
Model truth vs platform truth (capability gating). A card's compatible_backends declares MODEL truth: which engines the model's artifacts run on. Which of the card's declared capabilities our runner implementations can currently exploit is PLATFORM truth and lives in code, never on cards: platform_compatible_backends (src/skulk/shared/backends.py) subtracts engines whose runner cannot serve a capability the card declares, and every placement-side read of compatible_backends goes through it (placement._card_platform_backends), as does the worker's fallback probe (bootstrap._resolve_text_engine). Current gates: MLX and in-process llama_cpp retain their existing vision paths; llama_server vision is additionally enabled only for GGUF cards that pin both an exact vision.projector_file and immutable vision.projector_size. Those projectors are staged and manifest-verified before the runner passes --mmproj; homogeneous CUDA, ROCm, or Vulkan RPC vision is allowed with image media delivered only to the driver, while mixed-backend RPC remains gated off. Legacy GGUF vision cards without a projector pin remain on the in-process compatibility path. _SPEECH_SERVING_ENGINES = {mlx_audio} keeps TTS/STT cards off text/image/embedding runners, and _EMBEDDING_SERVING_ENGINES = {mlx, llama_server} keeps TextEmbedding cards on engines with an embedding runner (the transformers runner serves mlx placements; llama_server placements run a dedicated --embeddings server, on Linux Vulkan/CUDA/CPU and on the Apple Silicon Metal lane; the worker refuses any other resolved engine with the reason). The llama-server embeddings mode (worker/runner/llama_server/embeddings.py) launches with one slot and -b/-ub equal to the window, which is min(stamped serving window, card.context_length) (the card must declare context_length; placement may stamp less when memory admits less), truncates at that same window, admits only TextEmbedding through the shared dispatch, truncates over-long inputs through the server's /tokenize and /detokenize (llama.cpp refuses them otherwise), and proxies /v1/embeddings into an EmbeddingChunk in input order; pooling and L2 normalization follow the GGUF and llama.cpp's defaults. That runner reads each model's pooling mode, normalization, and truncation length from the artifact's sentence-transformers metadata (worker/runner/embeddings/recipe.py; no metadata keeps mean pooling, normalization, and 512 tokens) and refuses pipelines it cannot reproduce, such as Dense projections. Mounted TextToSpeech cards serve POST /v1/audio/speech through SpeechSynthesis tasks and the single-node mlx_audio speech runner, which emits AudioChunk data-plane output; stable stream=true requires the card to declare audio.supports_streaming = true, while non-streaming requests collect chunks into one raw audio response. Mounted SpeechToText cards serve POST /v1/audio/transcriptions: the API accepts multipart audio and retains it until the master creates an AudioTranscription task, then sends bounded raw SPEECH_MEDIA frames directly to the selected worker. The worker verifies the authoritative owner, frame count, and digest before dispatching the speech runner. Batch requests collect terminal TranscriptionChunk output in json, text, verbose_json, srt, vtt, or ndjson format. Card-qualified stream=true preserves actual model delta boundaries as typed SSE events; explicit response_format=ndjson streams the legacy chunk shape, and disconnect cancellation reaches the core command. Translation-capable STT cards reuse that path through standard POST /v1/audio/translations, with an English target mapped to family-specific generation arguments. TTS cards with static audio.voices and audio.default_voice expose them through GET /v1/audio/voices; optional ordered audio.voice_catalog entries add display names and preferred BCP 47 language tags. Dashboard Auto selection chooses the first preferred-language match and pins it across every sentence-sized request in one response. Cards declaring audio.supports_reference_audio=true may receive a bounded multipart reference clip; raw media travels only over the node-addressed Zenoh speech-media plane and never enters State. A card may additionally declare true realtime support: the stable stt.realtime@1.0.0 provider accepts mono PCM16 on any API node with reachable mounted capacity and streams partial transcripts from the selected single-host runner. Same-node PCM short-circuits locally; remote PCM uses bounded node-addressed REALTIME_AUDIO packets over Zenoh and never enters State or the event log. The transcription-only WS /v1/realtime edge adapts OpenAI-style 24 kHz PCM16 append/commit events onto that provider without changing capability truth. The registry's mlx-community/Voxtral-Mini-4B-Realtime-2602-4bit card is the first truthful realtime STT card; batch Parakeet and Whisper cards remain non-realtime. The dashboard voice loop consumes readiness and capability metadata: TTS can play draft/final assistant text; batch STT uses MediaRecorder; and realtime STT is selected only when the card declares it and the local API advertises stt.realtime, then captures and resamples microphone PCM through the WebSocket edge. When a runner gains a capability, flipping the code table lights up every affected card at once with no card edits. Related platform default: resolve_node_backend's no-preference fallback orders -cpu compute tags last, so a card without an explicit preference for an engine never resolves a CPU build over a GPU build on alphabetical accident. Speech-serving narrative (TTS/STT/realtime/VAD end to end): Architecture "Speech serving".
Engine compatibility and qualification. model_engine_requirements reads
card engine declarations and the validated typed native profiles of legacy cards.
registry_compatible_backends_for_node adds active upstream architecture/engine
mappings without requiring qualification. Actual node/package and implemented
runner requirements constrain placement; empirical qualification remains scoped
reporting with its original tested card/build/hardware/workload identity.
registry_supported_backends_for_node is a reporting matcher, not launch permission.
Node engine builds and AMD KFD gpu_architecture/CUDA SM facts retain real compiled
target checks. Tested GPU names never become package eligibility. Engine/cache
settings are advertised and stamped separately from immutable card truth.
Dashboard reference audio: the dashboard exposes bundled reference profiles through the same stable voice selector used for model-native speakers. It separately exposes a reference clip and optional transcript only when the selected mounted TTS card declares audio.supports_reference_audio=true. The clip stays browser-local until synthesis, is submitted through the multipart speech contract without a catalog voice, and the same File is reused across every sentence request in one response. Selecting another TTS model clears it. Uploads remain request-scoped conditioning, not a persistent custom-voice resource.
Dashboard TTS streaming: a streaming-qualified TTS card may include pcm in audio.response_formats. The speech runner converts model floats to clipped mono signed-16-bit little-endian samples, and POST /v1/audio/speech exposes sample rate/channel/sample-format headers. The dashboard feeds those samples to a bounded AudioWorklet queue when the secure-context interface exists; ordinary LAN HTTP instead coalesces arbitrary network chunks into scheduled 100 ms AudioBufferSourceNode frames on the unrestricted AudioContext surface. Visible assistant text is segmented into ordered sentence requests; reasoning/tool channels are excluded by the existing content splitter. Synthesis requests remain serial, but completion of one response body starts the next request without waiting for its audio to drain; all sentence responses append to one response-scoped browser audio timeline. Playback starts on the first PCM with no startup or lookahead requirement, so a short opener may naturally underrun before the following sentence arrives. Both playback paths enforce the same eight-second ceiling and four-second resume threshold, queue pressure pauses HTTP reads, and stop propagates through queued requests, the active fetch, the core command, and runner cancellation. Batch-only cards retain encoded complete-response playback.
Served-backend engine (llama_server). A third engine class, distinct from the in-process mlx and llama_cpp runners: instead of loading the model in-process, the worker launches an external llama-server subprocess and proxies its OpenAI HTTP API (src/skulk/worker/runner/llama_server/runner.py). This is the only path to llama.cpp's native multi-token-prediction speculative decoding (--spec-type draft-mtp): for models that ship MTP heads (Qwen3.6, DeepSeek-V3/R1, GLM, Kimi, Nemotron) the MTP orchestration lives in the server application (tools/server), not in libllama or llama-cpp-python, so it cannot be driven in-process. The runner spawns the server on an ephemeral port (reaped on parent death via PR_SET_PDEATHSIG), health-checks /health, then proxies the streaming /v1/chat/completions SSE into the normal ChunkGenerated data plane (reasoning_content becomes is_thinking token chunks; structured tool_calls become a ToolCallChunk). Per-request cancellation aborts the proxied HTTP connection (stopping server-side generation); SIGTERM is for instance teardown of the whole server, not a single request. The server emits structured reasoning/tools itself, so the in-process harmony/think/tool text parsers are unused here. A node advertises llama_server (plus compound tags) when SKULK_LLAMA_SERVER_BIN points at a llama-server binary (_probe_served_backends); cards route to it via compatible_backends = ["llama_server-…"]. The spec mode is card-driven: RuntimeCapabilityCardConfig.served_spec_type (draft_mtp / draft_eagle3 / draft_simple / draft_dflash / ngram) plus served_spec_n_max map to the --spec-type / --spec-draft-n-max flags; only this engine reads them (MLX speculation stays the mtp_* / assistant_model_repo fields). Some spec modes need a separate draft GGUF rather than baked-in heads: served_spec_draft_repo + served_spec_draft_file name that file (downloaded as a companion alongside the base, present-on-disk-checked, and passed as --model-draft). draft_simple / draft_eagle3 / draft_dflash always require one (DFlash is a separate block-parallel speculator; supported for the drafter families upstream's dflash arch implements, which as of b10434 excludes Laguna's gated-attention drafter, #676; DFlash2 landed upstream in b10753 and that exclusion has not been re-verified against it); Gemma 4 is draft_mtp driven by its assistant as a separate draft GGUF (llama.cpp PR #23398); Qwen3.6 / DeepSeek / GLM draft_mtp leave it unset (heads baked into the base GGUF). When the draft repo IS the base repo (a bundle shipping base + draft, e.g. Gemma 4), the draft shares the base's store entry and staging directory, so it is co-fetched with the base through the model-store download protocol (the worker sends extra_gguf_files on the download request; select_store_gguf_download_files keeps the draft's shard group, a registration guard verifies it landed, and ModelStore.entry_missing_files re-downloads a stale base-only entry to recover it). The staging fast path is draft-aware (_staged_same_repo_draft_missing), so a dir staged before the draft existed re-stages rather than serving without it. A separate-repo draft has its own model_id / staging dir and rides the normal companion path. Single-node placements are group-less. Dispatch shares the vLLM runner's concurrent loop (ServedConcurrentDispatch, #591): SKULK_LLAMA_SERVER_PARALLEL defaults to the release-qualified 16-slot width, is honored exactly (_llama_server_parallel), and above one slot the runner adds --kv-unified (_slot_server_args, #689). Every launch also passes --jinja and --no-reasoning-preserve (_chat_template_server_args): from b11669 llama-server keeps earlier turns' reasoning in rendered prompts unless told otherwise, and Skulk keeps it out so an engine pin advance does not change multi-turn prompts. The unified cache is what makes the count honest: llama_context sets a slot's context (n_ctx_seq) to the whole -c window when the cache is unified and to n_ctx / n_seq_max when it is not (src/llama-context.cpp), and the server reads exactly that per slot (tools/server/server-context.cpp, llama_n_ctx_seq), so without it N slots would each serve a fraction of the context_token_limit placement stamped and the API admits against. It costs no memory (cells allocated are n_ctx_seq * n_stream, and n_stream collapses to 1 when unified). Setting the value explicitly to 1 retains the validated serial command line for draft-mtp validation or RPC-driver isolation. The earlier min(requested, floor(n_ctx / KV_CONTEXT_BUDGET_TOKENS)) cap is removed with the slicing it protected against. To make shared-pool contention safe, the runner calls llama-server's /v1/chat/completions/input_tokens endpoint before generation, applies Skulk's shared 4096-token default when max_tokens is omitted, and reserves exact rendered input plus maximum output. A weighted condition gate queues requests FIFO until their aggregate reservation fits n_ctx, preventing later small reservations from starving an earlier large one; if token counting is unavailable, the request reserves the whole pool and runs alone rather than guessing low. Only requests past this gate count as resource-active in performance-envelope telemetry. The shipped width of 16 therefore remains a real concurrent ceiling for bounded traffic without allowing aggregate long-context demand to terminate the server. Measured on a Strix Halo (Radeon/Vulkan, llama.cpp b9820): dense Qwen3.6-27B with draft-mtp ran 2.19x vs no MTP (72-77% acceptance) end-to-end through Skulk's API. The shape (managed inference server plus OpenAI proxy) is shared with the vllm engine below.
A request the server refuses is raised with the server's own reason (raise_for_server_status reads the error body; httpx's status error names only the status and URL), and a context-size refusal carries the API's CONTEXT_LENGTH_EXCEEDED_PREFIX so the API answers 400 context_length_exceeded as it does for its own admission check.
Served-backend engine (vllm). The second served engine, reusing the llama_server managed-subprocess-plus-OpenAI-proxy shape with the vllm serve process (src/skulk/worker/runner/vllm/runner.py). vLLM is the GPU-serving fast path: its continuous batching and paged attention hold latency flat and grow aggregate throughput under concurrent load where the single-stream engines collapse. A Phase 0 spike on an A100 (gpt-oss-120B, same MXFP4 weights on both engines, driven by vllm bench serve) measured llama.cpp's time-to-first-token hitting ~31s at 64-way concurrency versus vLLM's ~0.5s, with vLLM's aggregate throughput ~1.75x and climbing while llama.cpp plateaued; conversely llama.cpp won single-stream ~2.8x, because the A100 (Ampere) has no native FP4 and vLLM's MXFP4 runs through the bf16 Marlin kernel (this flips on Blackwell, which has native FP4). So vLLM coexists with the in-process engines rather than replacing them: the planner picks by hardware and expected concurrency. The runner spawns vllm serve <model_dir> --served-model-name <id> --gpu-memory-utilization <f> --max-model-len <n> --tensor-parallel-size 1 --max-num-seqs <N> on an ephemeral port (reaped on parent death via PR_SET_PDEATHSIG), health-checks /health (a bare 200, unlike llama-server's JSON status), then proxies the streaming /v1/chat/completions SSE into the normal ChunkGenerated data plane. vLLM auto-detects CUDA vs ROCm from its own install, so there is no per-compute-backend flag; a node advertises vllm (+ vllm-cuda/vllm-rocm) when an explicit SKULK_VLLM_BIN CLI or managed installed/installable runtime matches the observed GPU and runtime prerequisites (_derive_vllm in src/skulk/facts/derive.py, #614: declaration chain SKULK_VLLM_BACKENDS > SKULK_LLAMA_SERVER_BACKENDS > SKULK_LLAMA_CPP_BACKENDS, else vendor inference from observed GPU hardware, NVIDIA -> cuda / AMD -> rocm; GPU-only, no cpu floor since a vLLM node with no GPU is not a useful candidate, and SKULK_VLLM_BIN set with no usable GPU backend raises a loud conflict). vllm- joins the GPU-offload prefixes in placement_utils, so discrete-VRAM admission auto-applies. Dispatch is concurrent: main() keeps up to N TextGeneration requests in flight at once, each streaming its own /v1/chat/completions request on a worker thread (a ThreadPoolExecutor of N workers, N from SKULK_VLLM_MAX_CONCURRENT_REQUESTS, default 32), so the server sees concurrent load and its continuous batching actually engages; a serial runner would defeat the engine's whole purpose. Because a ThreadPoolExecutor caps active threads but has an unbounded submit queue, an N-permit semaphore (_dispatch_permits) is acquired before each submit and released when a generation finishes, so submitted jobs are capped at N too: excess load blocks the dispatch loop (backpressuring the task receiver / master) instead of accumulating an unbounded in-process backlog. While saturated the loop still polls server liveness. N is also the server's --max-num-seqs: vLLM never sees more sequences than the runner admits, and vLLM 0.31 refuses to start a hybrid Mamba-cache model (Qwen3.5/3.6) whose sequence cap exceeds its Mamba cache blocks, which the 256 default did at a placement-sized memory share. Runner status is RunnerRunning while _inflight > 0 and RunnerReady when the last generation drains (a lock-guarded counter, since worker threads finish concurrently; _generate is status-neutral, the dispatch loop owns the transition); MpSender event sends are thread-safe and each DataChunk carries command_id+sequence so the API demultiplexes interleaved streams. Lifecycle tasks (LoadModel, Shutdown) run inline on the dispatch thread; shutdown sets CANCEL_ALL, drains the pool, then tears down the server. Teardown signals the server's PROCESS GROUP (start_new_session at spawn, killpg at teardown, single-process fallback): vLLM runs its EngineCore as a grandchild, and terminating only the direct child left an orphaned engine core holding the full GPU allocation when teardown raced a node restart (#653, ~73 GB observed). The crash shapes neither PDEATHSIG nor group teardown reaches are covered by a worker-startup sweep (src/skulk/worker/runner/vllm/orphan_sweep.py, called from Worker.run): it SIGKILLs processes carrying the VLLM::EngineCore marker whose parent is init (a healthy engine core always has a live vllm serve parent; a nohup'd manual vllm serve has ppid 1 but no engine-core marker, so the rule cannot match anything an operator still wants), logging each reap loudly before the node advertises capacity. Single-node text generation with tool calling in this slice: a card that pins runtime.vllm_tool_call_parser launches the server with --enable-auto-tool-choice --tool-call-parser <name> (explicit pin ONLY, no family fallback: one family string spans tool-call generations with different wire formats, Qwen2.5 Hermes JSON vs Qwen3.6 XML, and a wrong parser fails at request time; pin only pod-validated names), tool requests run non-streamed through _generate_with_tools (mirroring llama_server: server-side parsing to structured tool_calls, tool_calls_from_message -> ToolCallChunk, blocking_call_stats + #596 attribution, mid-flight cancel drain, prose fallback preserving finish_reason), a card with no resolvable parser rejects tools loudly (#385), and TextGenerationTaskParams.tool_choice now carries the previously-dropped OpenAI tool_choice to every served engine; per-token logprobs remain rejected loudly (follow-up), --gpu-memory-utilization is sized to the placement footprint unless SKULK_VLLM_GPU_MEMORY_UTILIZATION pins it; the live subprocess/streaming path validates on GPU hardware. Context windows for vLLM placements are capped at the placement stamp: instance_context_token_limit min()s vllm-resolved placements against VLLM_MAX_MODEL_LEN (32768, shared/models/memory_estimate.py), because vLLM pre-allocates and CUDA-graph-captures its FULL --max-model-len at startup (a 262k-context card turned a ~3-minute bring-up into ~90 minutes on an A100-80GB even though the window fit). Applying the cap at the stamp keeps admission and the served window in agreement; the runner min()s against the same constant as defense in depth for instances stamped by a pre-cap master. The cap retires with vLLM-aware admission. Speculative decoding is card-driven: RuntimeCapabilityCardConfig.vllm_spec_method ("mtp" = the checkpoint's native prediction heads, vLLM resolves the drafter architecture like Qwen3_5MTP, no separate draft model; "dflash" = a separate block-parallel DFlash speculator, requiring vllm_spec_draft_repo, which maps to the speculative-config model key and resolves through vLLM's own HF cache at engine start with store-staged drafts a follow-up) plus vllm_spec_num_tokens map to --speculative-config JSON; the card validator enforces the pairing (dflash requires a draft repo, mtp forbids one); only the vllm engine reads them (served_spec_type remains the llama_server equivalent). Probe-measured on A100-80GB: Qwen3.6-27B-FP8 2.01x single-stream decode at depth 2 (77% acceptance), 35B-A3B-FP8 1.51x. The dflash method is the card-absorbed-vendor-scheme demonstration: the Laguna XS 2.1 FP8 card pairs Poolside's published DFlash drafter at depth 15 with no engine code beyond the generic fields (vLLM >= 0.25.1; fresh-box measured 1.35x single-stream on A100-80GB, acceptance length 3.44; the DFlash JIT additionally needs a CUDA >= 12.8 toolchain on the node). Spec depths >= 8 also make the runner pin --max-num-batched-tokens = max(8192, 2048 + seqs * (depth - 1), seqs * (1 + depth)) against the pinned sequence cap: a DFlash sequence costs 1 + depth slots of the batched budget per decode step, so batched >= seqs * (1 + depth) keeps every admitted sequence decoding (0.25.1 refused to start below that; from 0.28 the engine starts but decodes fewer sequences per step than it admits), and the batched default is version- and hardware-band-dependent, so the runner pins it rather than relying on an assumed default; shallow MTP depths keep vLLM's batched default. vLLM's own tensor/pipeline parallelism (multi-node) and vLLM-aware admission are later tracks. The concurrent-dispatch loop itself is shared with llama_server via the ServedConcurrentDispatch mixin (src/skulk/worker/runner/served_concurrency.py, #591): receive tasks, dispatch each TextGeneration to the bounded thread pool, serialize lifecycle tasks on the dispatch thread; the concrete runners supply _generate, server liveness, and teardown. The in-process llama_cpp runner routes through the same mixin at width 1 (#692): not for parallelism (the llama_cpp_python Llama object cannot generate concurrently, so generations stay strictly serial) but for the admission machinery, so the last engine without one gains bounded admitted work, lock-guarded cancellation, and the #596 admission stamp; its server hooks are a no-op liveness check (an in-process crash kills the runner process itself) and a teardown that releases the model. The supervisor's runner task channel is bounded at 256 like its sibling channels (runner_supervisor.py), so a broken upstream admission path backpressures loudly instead of growing runner memory without bound. Thinking control on the in-process llama_cpp engine: the served engines forward enable_thinking as chat_template_kwargs to their servers, but llama-cpp-python's create_chat_completion has no template-kwarg channel, so the runner wraps the default GGUF-template Jinja formatter (TemplateKwargFormatter + install_template_kwarg_formatter in llama_cpp/runner.py) with a per-request slot that the strictly serial width-1 dispatch makes race-free; the wrapper is installed only on the default Jinja path for text models whose template actually reads enable_thinking (guessed family formats, vision chat handlers, and control-less templates are untouched), and any internals mismatch degrades loudly to the previous ignore-the-toggle behavior.
GPU compute-capability telemetry. AcceleratorMetrics carries compute_capability ("<major>.<minor>", the NVIDIA SM level) plus derived native_fp4 / native_fp8 flags, filled by the NVML collector (nvidia_gpu.read_accelerator_metrics via nvmlDeviceGetCudaComputeCapability; derived at the collector boundary: FP4 = Blackwell sm100+ i.e. >= 10.0, FP8 = Ada/Hopper sm89/sm90 i.e. >= 8.9). This is the signal capability-keyed placement needs: the same model+engine performs oppositely across GPU generations (see the vLLM spike above), so engine/quant/placement must key on compute capability, not vendor. None on collectors that do not report it (AMD sysfs, Apple).
Multi-node GGUF placement (RPC driver + donors, #328). llama_server is a multi-node-capable engine (_MULTI_NODE_ENGINES in src/skulk/shared/backends.py, alongside mlx; the in-process llama_cpp stays single-node). Placement models it as an asymmetric served placement, not a Skulk-sharded pipeline: the planner mints a LlamaRpcInstance (src/skulk/shared/types/worker/instances.py, InstanceMeta.LlamaRpc) whose driver node runs llama-server --rpc donor:port,... and holds the model file, while each donor node runs ggml-rpc-server and lends GPU memory. llama.cpp splits weights/KV across the pooled devices proportional to their free memory itself, so Skulk computes NO GGUF layer math: the driver's shard nominally spans all layers, donors carry the degenerate RpcDonorShardMetadata (no layer range; the distinct type is what worker dispatch keys on). Placement rules (src/skulk/master/placement.py): a multi-node cycle is admissible only under the common-engine cycle rule (some single engine advertised by every node in the cycle AND multi-node capable) (this also fixed #414's mixed-engine hole for hybrid cards); a cycle resolves to the RPC shape when llama_server is the common multi-node engine and mlx is not; the driver is the biggest-usable-VRAM node (tie: download presence); donor endpoints are chosen at placement from observed connections via the ring's transport prioritiser (Thunderbolt first, VPN last) and stamped on the instance (donor_endpoints, the donor binds exactly that ip:port, never 0.0.0.0 and never link-local: a two-TB-port node routes 169.254/16 out one port only, so link-local endpoints break asymmetrically). Pooled admission uses the same UMA-aware usable-GPU figure as single-node placements (usable_vram_by_node): on a unified-memory APU the BIOS VRAM carve is not an allocation boundary (the GPU maps system RAM through GTT), so a carve-only figure falsely refuses pooled placements that load and serve fine (proven live on the Strix pair: pooled gpt-oss-120b, refused under a carve-only figure, loaded 40.6G driver / 22.8G donor and served at 44 tok/s). An RPC cycle node missing its accelerator telemetry surfaces as info-pending rather than falling back to the system-RAM formula. Smallest-cycle ranking still prefers single-node whenever the model fits one node, so the RPC shape only fires for the pooled-only model class; existing placements are behavior-identical. RPC is memory pooling, not speedup (spike: 120B MoE pooled decode 42-45 tok/s vs 56 single-node, prefill unchanged; TB improves load time, not decode). Donor death kills the driver (llama-server SIGABRTs), which the standard crash cascade turns into instance teardown + re-placement. Worker side: dispatch keys on the SHARD TYPE (bootstrap.entrypoint routes RpcDonorShardMetadata to the donor runner, src/skulk/worker/runner/rpc_donor/runner.py, which spawns ggml-rpc-server -H <stamped-ip> -p <port> -c and reports RunnerReady with no LoadModel; binary via SKULK_RPC_SERVER_BIN or the SKULK_LLAMA_SERVER_BIN sibling); the driver is the served runner with --rpc <endpoints> appended (rank 0 of a LlamaRpcInstance is the only multi-node shape it accepts). The plan gates are role-aware (worker/plan.py): donors skip the download/load/warmup gates entirely (no model file ever lands on a donor), _init_distributed_backend skips RPC instances (no ConnectToGroup: llama-server dials the donors directly), the driver's LoadModel requires the download on ITS node only plus every donor RunnerReady (endpoints answer before llama-server dials), and _pending_tasks never forwards inference tasks to a donor. The worker's local pre-spawn fit guard is skipped for RPC instances (llama.cpp decides the split at load; pooled admission already sized every node against its usable GPU memory, and a genuine misfit fails at llama-server load into the crash cascade).
Data plane (#279 Phase 2)
DATA carries per-token generation output off the event log. Exactly one serving output worker publishes DataChunk ({command_id, GenerationChunk}) on this topic: rank 0 for text, embedding, and speech families, or the primary terminal pipeline stage for image generation. RunnerSupervisor._emit diverts ChunkGenerated to the data sender and diverts completed per-rank TracesCollected payloads to TRACE_DATA; task status, acknowledgements, and runner status stay on the ordered control-plane event sender. The owning API node drains DATA in API._apply_data and demuxes by command_id into the per-command stream queues (_dispatch_generation_chunk), exactly as the event path did. The sibling PROVIDER_DATA topic carries generic provider ProviderStreamPacket values keyed by call id plus direction, preserving provider-specific schemas and binary attachments outside the closed GenerationChunk union. REALTIME_AUDIO carries built-in realtime STT input as a bounded JSON lifecycle header plus raw PCM bytes from the owning API to the selected worker. SPEECH_MEDIA carries bounded request-scoped TTS reference audio and batch STT uploads from the API owner to selected speech workers. TRACE_DATA carries one terminal task-trace payload per runner rank to the owning API for bounded assembly and local persistence. VISION_MEDIA carries VLM and image-edit input from the API owner directly to every MLX rank in the instance, or only to the stamped driver of a LlamaRpcInstance; RPC donors never execute inference. Targets come from the authoritative TaskCreated event. The same plane carries video reference attachments (keyframes, reference clips, reference audio) for VideoGeneration with payload="reference_media": raw bytes keyed by attachment slot, larger per-request bounds (512 frames, 256 MiB), and per-slot size plus SHA-256 verification against the task's references before the worker writes them to task-local files and opens the plan gate. OUTPUT_MEDIA carries a finished video container (and optional thumbnail) the other way: the producing worker streams OutputMediaPacket frames (opened -> chunk* -> completed with raw bytes, purpose video or thumbnail) to the owning API, which assembles them in its VideoStore, verifies size and digest, and returns accepted or transport_failed; the worker keeps its copy until every declared artifact is acknowledged or a five-minute deadline passes. Egress rides a dedicated Zenoh lane (_output_networking_publish) whose per-stream hand-off blocks when full, so a slow owner throttles the worker's file reads instead of growing memory; the gossipsub fallback delivers only to the target node and the store reorders a bounded window of early chunks. Only the node the master placed the render on may deliver its output. Pre-open frames held across all jobs share one 128 MiB budget, a completion frame that overtakes a chunk on the fallback is held until the assembly fills, and every failure path funnels through API._finish_video_job, which deletes partial files, releases held frames, deadlines, and the placement record, fails the job, and closes its queue. The VideoStore keeps at most SKULK_VIDEO_STORE_MAX_BYTES (default 32 GiB) of committed plus in-flight artifacts and leaves a 1 GiB reserve on its filesystem; a new artifact evicts the oldest completed jobs (whole jobs, never one still receiving) to fit, and those jobs' expires_at moves to now. A video job completes only when the render's terminal VideoChunk (on DATA, carrying the VideoOutputManifest) and every artifact the manifest declares have arrived and match it by digest, size, and content type, in either order, within ten minutes of the first; a session reset fails jobs still waiting for media. The master sees only the control-sized command and task lifecycle: it never indexes, persists, or application-relays data-plane payloads.
MLX vision execution. A single-node bundled vision model is loaded through its native mlx-vlm family implementation rather than loading a text-only mlx-lm model and splicing image embeddings into it. Processor resolution first uses upstream metadata and then the native family processor exported by mlx_vlm.models.<model_type> (including processing submodules), so Qwen image-grid metadata reaches the model without routing supported native processors through PyTorch or torchvision. The macOS runtime still declares a pinned torchvision dependency because Transformers 5 gates its AutoImageProcessor fallback behind that package and supported families use the fallback. mlx-vlm 0.6.4 mutates already-converted Qwen3.5/3.6 RMSNorm weights while loading; Skulk narrowly guards those MLX safetensors until the MLX 0.32-compatible upstream fix can be adopted. Missing processors, malformed structured messages, and failed image preprocessing are terminal request errors. Falling back to text-only generation after accepting image input is prohibited because it can return a plausible but unrelated hallucination. A card-declared MLX vision instance is served by DualModeGenerator: rank-zero arrival order defines distributed FIFO modality cohorts, consecutive text-only requests are delegated to BatchGenerator, and each request carrying assembled image bytes is delegated alone to SequentialGenerator. Only one child engine is active at a time. Cancellation is agreed by the coordinator and forwarded to the active child; queued work can be cancelled without changing mode. Terminal GenerationStats.serving_batches and in_flight_at_admission are selected per task rather than per model instance. The temporary split remains until #716 adds native per-sequence multimodal state to the batch engine. Distributed MLX placements continue to use the sharded Skulk generation path.
Output frames never mutate State, so removing them from the ordered log remains loss-free for state correctness. RunnerSupervisor now emits started at sequence 0, payload frames after it, and exactly one completed, failed, or cancelled; status-only completion/cancellation still emits a terminal before producer state is cleared. The API reorders whole frames by the per-command sequence on gossipsub and uses O(1) sequence dedupe on Zenoh. A duplicate is idempotent. A bounded reorder window repairs normal reordering, but an unresolved gap, queue drop, or arrival-mode sequence jump is a transport failure: the API sends a terminal ErrorChunk, cancels a still-active producer, closes the endpoint queue, and increments transportFailures instead of skipping ahead and returning incomplete output. Stream state exists only while the command queue is live and is dropped on finalization. Vision input uses opened -> chunk* -> completed -> accepted, with cancelled and source-routed transport_failed terminals. Duplicate identical sequences are idempotent, conflicting duplicates fail the command, and workers release assembled base64 input to runner planning only after exact sequence/count/metadata/SHA-256 and authoritative-task-owner validation plus successful acknowledgement admission. Timed-out acknowledgement admission is retried without exposing the task early. Every selected rank must return accepted; a five-minute source deadline fails and cancels transfers missing an acknowledgement. Incomplete streams are bounded by frame count, per-command and process bytes, active streams, and a five-minute age limit.
Vision hard bounds are 64 API-staged plus active commands, 32 MiB per command, and 512 MiB across staged plus active source transfers; 16 remote dispatcher streams total/per destination owner, 66 queued frames per stream (one open, at most 64 payload, and one completion), and 64 concurrent rejection tasks; and 64 worker streams, 64 media chunks/32 MiB per command, 512 MiB per worker process, and 64 retained pre-task failure reports. Frames are capped at 512 KiB. Network receive uses independent 66-frame payload and 1024-frame metadata-only terminal lanes; overflow is source-routed as a typed failure when terminal capacity remains. The dispatcher geometry therefore caps queued serialized image media independently of generated output, while API and worker accounting remain charged through verification or terminal cleanup. Same-process producer and consumer channels are rendezvous-only. Reverse acknowledgements key their egress queues by command and producing rank so one rank's terminal cannot close another rank's acknowledgement.
Mixed-version clusters remain unsupported. To prevent a stale or malformed participant from reintroducing payloads during an upgrade mistake, the master rejects every legacy SendInputChunk command and applies an explicit event-jurisdiction guard before ordering. Payload-bearing runner IPC events, observational telemetry, and transient download progress remain decodable but are skipped at their source sequence before indexing, retention, replay, state application, or global broadcast. Only the enumerated durable control decisions, download reset/terminal transitions, and ordered connectivity facts can enter the event log.
Because DATA has no replay, token and streaming-audio receivers retain the 120-second mid-stream idle deadline. It wraps producer receive only, arms after real output, and does not bound queueing/prefill time. A stall becomes a terminal error; a still-active producer is cancelled, while an already-terminal task follows normal cleanup. Independently, every producer-side remote command queue has a 30-minute no-frame resource lease. Every producer frame observed by egress renews it; expiry closes and tombstones the queue before any recovery publish, releases owner/process admission, and best-effort emits a correctly sequenced typed failure. This longer lease bounds orphaned egress state without applying the API's post-output deadline to model prefill. DataPlaneObserver reports lifecycle counts, first-byte and stream-span samples, duplicates, out-of-order frames, skipped sequences, late frames, missing starts/terminals, idle timeouts, and synthesized transport failures through NodeDiagnostics.data_plane. DataPlaneEgressObserver contributes current/peak queue depth, active command queues, local short circuits, remote enqueue/publish/drop/failure counts, idle stream reclamations, bytes, latency, and per-owner pressure. The dashboard Node tab renders the operational subset.
Zenoh data-plane transport (shipping default, #315/#316). The DATA, PROVIDER_DATA, REALTIME_AUDIO, SPEECH_MEDIA, TRACE_DATA, VISION_MEDIA, and OUTPUT_MEDIA topics ride an Eclipse Zenoh peer session by default; control, telemetry, and election planes stay on libp2p. Transport selection is resolved by _resolve_zenoh_enabled(SKULK_ZENOH_DATA_PLANE, SKULK_ZENOH_LISTEN): explicit SKULK_ZENOH_DATA_PLANE of 1/true/yes/on forces Zenoh on, 0/false/no/off forces gossipsub, and unset selects Zenoh on a fresh install. _resolve_zenoh_listen uses an explicit SKULK_ZENOH_LISTEN when present; otherwise it selects the best non-virtual address from the model-store policy only when that address belongs to a private LAN or CGNAT overlay, falling back to loopback on offline or public-only hosts. Binding a public address therefore requires an explicit listener override. With no explicit SKULK_ZENOH_CONNECT peers the session enables local multicast scouting; an explicit peer list retains the fleet-qualified multicast-off posture for routed and Tailscale deployments. Cluster boundary (network v0.0.3): the session is scoped and authenticated by the libp2p pre-shared key, from which rust/networking/src/data_plane_trust.rs derives everything one way (swarm::data_plane_trust; the key never leaves swarm.rs): (1) a multicast scouting port on group 224.0.0.224 (SHA-256 of skulk-zenoh-scout-v1 + NUL + key, mapped into 20000 to 26999 with 21027/22000 skipped, never Zenoh's shared 7446), so clusters with different namespaces normally scout apart (a shared port, about 1 in 7,000, only lets scout packets meet; TLS refuses the foreign key); exposed as ZenohHandle.scouting_address() / Router.zenoh_scouting_address() and logged at startup; (2) an Ed25519 certificate authority (HKDF-SHA256 of the key, info skulk-zenoh-ca-v1) that every node derives byte-identically, plus a per-process ephemeral P-256 member certificate (serverAuth and clientAuth, unbounded validity); every link is TLS 1.3 with enable_mtls, transport/link/protocols = ["tls"], and transport/unicast/max_links = 1, with all material passed inline (base64) and redacted from errors; (3) a member name skulk-dataplane-<authority key digest>.invalid carried by every member certificate and enforced by a default-deny Zenoh access_control policy keyed on cert_common_names, because Zenoh's TLS dialer also trusts the public Web PKI roots. A device without the key can neither join, read, nor inject; passive observers see TLS 1.3. On the default namespace, or a blank one (which derives its own key), the key is public (libp2p parity): encrypted but joinable by any Skulk. Python always passes tls/ locators: _resolve_zenoh_listen emits tls/, and _normalize_zenoh_endpoint / _resolve_zenoh_connect rewrite operator tcp/ endpoints to tls/ with one warning and refuse other protocols; the Rust session refuses any non-tls/ endpoint. Mixed transports remain unsupported and are never bridged. Each node advertises its already-resolved choice in NodeResources.data_transport; /state exposes it and derives data_transport_mismatch health errors when live nodes disagree, while node diagnostics adds a matching warning. Zenoh isolation visibility: uniform advertisement is not a formed mesh, so NodeResources.zenoh_connected_peers carries the number of authenticated cluster members the session holds a transport to (ZenohSession::connected_peer_count via session.info().links(), counting a peer only when every link's TLS identity is the cluster member name, so a quarantined foreign transport never masks isolation; surfaced as Router.zenoh_connected_peer_count), sampled by ZenohPeerSampler (src/skulk/routing/zenoh_status.py) at each NodeResources advertisement (worker InfoGatherer and the management-node publisher alike). The sampler advertises None during a 90-second startup grace window while the session has never connected (and on sample failure), so health never fires on normal mesh formation; a trustworthy 0 with at least one OTHER live Zenoh node raises the error-level zenoh_isolated health reason (_zenoh_isolated_reason, node_health.py), and the node's own _monitor_zenoh_isolation loop (main.py, 30-second cadence, 5-minute warning floor) logs the remediation locally. Canonical failure shape: a zero-config remote/overlay member that multicast scouting cannot reach, whose control plane stays healthy while every remote stream dies with transport errors. The Router holds an optional ZenohHandle (skulk_pyo3_bindings, backed by rust/networking/src/zenoh_session.rs). Vision ingress owns a separate bounded dispatcher and observer from generated/provider/realtime output, so upload pressure cannot consume their queue or stream admission. Publishers use Reliable + Block on a single priority so one producer's frames are FIFO per key. Model DATA keeps its transport-conditional reorder policy; provider DATA always applies CapabilityStreamReceiver because the generic contract requires bounded duplicate/reorder/gap handling independent of the selected transport. Remote realtime and reference audio are disabled on the explicit gossipsub fallback so private audio is never broadcast cluster-wide; batch STT, trace payloads, and vision media retain target-filtered gossipsub fallback delivery on the trusted fabric.
Key-addressed unicast uses data/<owner_node> for model output, provider-specific keys for PROVIDER_DATA, realtime_audio/<target_node> for PCM ingress, speech_media/<target_node> for reference or batch transcription audio, trace_data/<owner_node> for completed rank traces, and vision_media/<target_node> for image input and reverse acknowledgements; each node subscribes only to its own suffix. The in-process networking channel carries an OutboundPacket with topic, routing key, command stream key, terminal marker, and serialized bytes. Same-node frames are delivered before egress and short-circuit Zenoh entirely. Remote frames enter a bounded queue per logical stream; every stream has an independent publish task and five-second publish deadline. Queue saturation or publish failure drops only that stream's frame. Input transport rejection is converted to a source-routed transport_failed packet so the owning API terminates only the affected command. Trace transport is best-effort diagnostics: an undeliverable rank packet expires from the owner's bounded incomplete assembly without affecting inference. Terminal delivery closes the stream worker. NodeDiagnostics.visionMediaEgress reports the isolated upload queue depth, active streams, local short circuits, remote enqueue/publish/drop/failure counts, bytes, latency, lease reclamations, and per-target pressure; visionMediaIngress reports API-staged/active commands and bytes, pending worker acknowledgements, worker-side retained streams/frames/bytes, verification, rejection, and expiration outcomes. On gossipsub, target-tagged batch STT, trace, and vision packets are network broadcasts. Vision is filtered in the router; speech workers and trace-owning APIs discard non-target packets before assembly or persistence. Remote realtime ingress and all reference-audio ingress are unavailable.
Media framing decision (#509). OpenAI-compatible response models retain base64 strings in AudioChunk, and the speech runner still receives one verified base64 field across its local process boundary. Neither representation is the Fabric media contract or the cluster upload path. extensions/streams.py defines a typed JSON lifecycle header plus either raw InlineMediaAttachment bytes or a BlobMediaAttachment (staged id, byte size, SHA-256, media type); encode_capability_stream_frame and SPEECH_MEDIA keep cluster media bytes outside JSON. scripts/benchmark_data_plane_framing.py measures the two shapes. On the development machine (50 median iterations), 64 KiB/256 KiB/1 MiB payloads used 1.338/1.334/1.334x wire bytes under base64 DATA JSON versus 1.004/1.001/1.000x under binary framing; base64 encode+decode median cost reached about 4.0 ms at 1 MiB versus about 0.008 ms for header framing. These timings are machine-specific; the size ratio is structural. Therefore provider and batch speech media use inline binary on the cluster transport, large immutable results use staged blobs, and text/tool/transcription metadata stays schema-validated JSON.
Version policy: all cluster nodes must run the same Skulk version and source build; a mixed-build fleet is a degraded deployment window, not a supported workload mode (see "Deployment & versioning" in Architecture). Correctness-bearing events, commands, state, telemetry envelopes, and DATA types keep extra="forbid"; there is no legacy bridge or transition-hydration concession. Peer operational diagnostics are deliberately different: parse_peer_node_diagnostics validates with recursive extra="ignore", additive counters carry defaults, /v1/diagnostics/cluster reports aggregate/per-node versionStatus, and /state.nodeHealth emits version_mismatch while live identity telemetry disagrees. This keeps a staged rollout observable without claiming cross-version inference or state compatibility.
Text return-path admission continues after placement in
API._token_chunk_stream: a one-second receive poll checks the authoritative
text task's rank-zero producer and owning API against fresh local
TelemetryView.node_resources_received_at receipts (shared 30-second liveness
bound) and zenoh_isolated_nodes. Positive endpoint isolation produces
data_plane_unavailable; active tasks receive TaskCancelled, terminal tasks
receive TaskFinished, and API queues are released before the terminal error.
Same-node output, missing/stale/unknown resources and unrelated isolation do
not fail a request. Buffered output wins, slow prefill/queueing has no
first-token limit, and polling preserves the existing inter-output idle budget
without counting consumer backpressure. No wire schema or SDK contract changes.
Events
Discriminated union at src/skulk/shared/types/events.py. Selected events:
| Event | Emitted when | Applied by |
|---|---|---|
InstanceCreated | Master places a model | All nodes (update State.instances) |
InstanceFailureRecorded | A runner, placement, or node failure makes a placement terminal. Emitted before deletion while model, instance, role, and assigned-node truth still exists; apply deduplicates by instance and retains the newest 64 records in State.instance_failures. Each record retains at most 64 assigned nodes; instance, model, and node identifiers over 256 UTF-8 bytes become stable SHA-256 references, while non-string node identities fail strict replay. Clean operator stops do not emit it. | All nodes |
InstanceDeleted | Master deletes a placement | All nodes |
RunnerStatusUpdated | Runner subprocess transitions state | All nodes |
RunnerFailed | Runner crashes or exits unexpectedly | All nodes |
TaskAcknowledged | Worker accepts a task | All nodes |
TaskStatusUpdated | Task transitions state (Running, Failed, Cancelled, Complete, TimedOut, the last emitted by the worker on shutdown timeouts, worker/main.py:474). The Complete variant is emitted by the runner / worker on natural finish (e.g. worker/main.py:362,388,450, runner send_task_status(..., TaskStatus.Complete)). The TaskFinished command sent by API on stream end triggers TaskDeleted only (master/main.py:444-450), not this event. The Cancelled variant (operator instance deletion via get_transition_events) additionally makes the API terminate that command's open stream with an error chunk. | All nodes |
TaskFailed | Master plan loop fails in-flight API tasks (TextGeneration / ImageGeneration / ImageEdits / TextEmbedding) whose instance is gone or dying (orphaned_task_failure_events in master/main.py, emitted BEFORE InstanceDeleted/NodeTimedOut so it indexes ahead of the applies that delete the task). Complementarily (#647), stale_lifecycle_task_failures reaps worker LIFECYCLE tasks (Shutdown / CreateRunner / LoadModel / ...) left Pending/Running with no instance in state past a 60s grace (ORPHANED_LIFECYCLE_TASK_GRACE_SECONDS): an ungracefully killed worker returns with a new ephemeral node identity that can never report, and instance deletion removed the task-to-node attribution, so the reap is grace-based, master-local-tracked, suppressed during the topology-settle grace, and emits the same terminal TaskFailed (error_type=executor_lost). apply_task_failed sets task_status=Failed (terminal, making re-emission idempotent) plus error fields. The API reacts by delivering a terminal ErrorChunk into the command's stream (_terminate_command_stream): streaming closes with an error event, non-streaming returns 500. On master failover the new session cannot carry old tasks, so the API's session reset() fails all open command streams directly instead (_fail_open_command_streams_for_session_reset). | All nodes |
TaskDeleted | Task is purged from cluster state | All nodes |
ChunkGenerated | Runner IPC emits an output chunk (token, tool call, error) | Runner supervisor diverts it to DATA; the master rejects any legacy event copy |
TracesCollected | Runner IPC emits trace events for one rank | Runner supervisor diverts it to TRACE_DATA; the master rejects any legacy event copy |
TracesMerged | Legacy decode-only trace envelope | Not emitted; the owning API merges TRACE_DATA packets directly |
TracingStateChanged | Cluster tracing toggle changes | All nodes |
EnginePackageNeedStated | A worker asked an engine package's adapter what one placed load takes, after its own memory check passed | All nodes: State.engine_package_needs[runner_id]; the master reserves the larger of it and its own estimate; removed with the placement |
EnginePackageChangeRequested | The master orders a ChangeEnginePackage command; carries target and owner nodes, engine ID, lane, action, optional build and an expiry | The target node's worker makes the change; a replay after the expiry changes nothing |
EnginePackageChangeCompleted | The target worker finished or refused an engine package change; a success carries its fresh NodeResources, a refusal a short code | The owning API answers its caller; the master puts the node's reported facts into its telemetry view before the answer is broadcast, so a launch sent straight after is stamped with the build that is now active |
ModelEngineOrderChanged | A person's engine order for a model was set or cleared | All nodes: State.model_engine_orders; each node also saves it to its own file |
StagedModelEvicted | A store-deleted model's locally-staged copies should be dropped fleet-wide (#427) | All nodes: apply removes the model's download entries from State (so the planner re-stages on a future placement instead of loading deleted files); each worker reacts by rmtree-ing the model's staged directory (_evict_staged_model → ModelStoreClient.evict_shard, which never touches the store's canonical copy) |
Apply function: src/skulk/shared/apply.py::apply, a pure (State, IndexedEvent) -> State.
Snapshot bootstrap is followed by a retained-tail request. The master serves at most EVENT_LOG_REPLAY_BATCH_SIZE (10,000) events per request, but does not enqueue that tail as one burst: a single background replay worker coalesces overlapping requests and emits EVENT_LOG_REPLAY_CHUNK_SIZE (32) events followed by EVENT_LOG_REPLAY_CHUNK_INTERVAL_SECONDS (250 ms) of pacing. Replay therefore cannot block the command processor, and repeated NACKs cannot create concurrent full-tail broadcasters. Separately, EventLogGrowthMonitor resets during active tasks/downloads and warns when otherwise-idle indexing remains at or above 60 events/min across a 60-second window, with a five-minute warning cooldown.
Commands
Two distinct command unions on two distinct topics:
COMMANDS topic: Command union
Discriminated union at src/skulk/shared/types/commands.py. Carried as ForwarderCommand over the COMMANDS pubsub topic.
| Command | What it requests | Master action |
|---|---|---|
PlaceInstance | Spin up a model on the cluster. Optional excluded_nodes: list[NodeId]: planner treats those nodes as if absent for this placement only; already-running instances on them are not affected. Optional excluded_install_ids: list[UUID] retains explicit stable machine exclusions, whether connected or absent; restore and repair carry them, and placement resolves current node IDs for each attempt. | Pick ranks based on memory + topology (filtered by excluded_nodes and positive zenoh_isolated data-plane evidence); emit InstanceCreated. Unknown Zenoh peer counts remain eligible during startup, while an otherwise viable cycle touching a node that reports zero peers is rejected before a runner is created. Memory admission is per-node (Tensor = even split, Pipeline = proportional to available): a node's weight share x an engine-aware overhead factor (memory_overhead_factor, 1.30 for MLX / 1.10 for GGUF; see below) + an explicit KV-cache reservation for KV_CONTEXT_BUDGET_TOKENS (8192, the admission floor, NOT the served size: the runner serves the larger memory-fit window from instance_context_token_limit, up to the card's max, which fits because it is derived from this same per-node working set; a card whose own advertised max context is below 8192 serves that smaller max, a gguf card whose fit is uncomputable clamps back to this floor to avoid a load-time OOM, and a gguf instance on a node WITHOUT discrete VRAM, whose window is committed in system RAM, is sized from the live ram_available the master admitted the placement against, capped at the working-set ceiling and the static fit and never below this floor, keeping the floor when no live reading exists) + MEMORY_OVERHEAD_FLOOR (256 MB), each node capped at GPU_WORKING_SET_FRACTION (0.75) of ram_total (the Metal GPU working-set ceiling, since gossiped ram_available can exceed what the GPU may wire). On macOS the gossiped ram_available is itself the GPU-wireable figure total − wired − anonymous − compressor (vm_stat snapshot per telemetry sample; see MemoryUsage below) rather than the naive free-plus-inactive figure that counted reclaimable file cache as used. A node that reports discrete GPU VRAM (AMD/NVIDIA vram_total_bytes in node_system) is instead admitted against its usable VRAM (min(vram_total − vram_used, GPU_VRAM_WORKING_SET_FRACTION (0.90) × vram_total) via usable_vram_by_node), because a GPU-offload engine (llama.cpp/vLLM) allocates weights + KV from VRAM, not system RAM (e.g. a Strix Halo's 64 GB VRAM pool, separate from its 64 GB system RAM, which a 0.75×system-RAM cap would wrongly refuse). On a unified-memory APU node (the accelerator's GTT spans the whole system: gtt_total_bytes > vram_total_bytes AND gtt_total_bytes ≥ ram_total) usable GPU memory is the working-set-capped VRAM (0.90 × vram_total) plus the system RAM the GPU can map via GTT, minus UMA_GPU_OS_HEADROOM (16 GB), so a model larger than the BIOS VRAM carve-out runs through GTT (e.g. a 58.5 GB GGUF gpt-oss-120B on a 128 GB Strix Halo with a 64 GB carve-out). The dual gate matters because a discrete amdgpu card also reports a gtt_total_bytes (its default can equal VRAM); requiring GTT to cover all of system RAM keeps a dedicated card on the conservative VRAM-only path. Apple unified-memory nodes report no discrete VRAM and keep the system-RAM ceiling. The weight-overhead factor is engine-aware (memory_overhead_factor): GGUF/llama.cpp models use LLAMA_CPP_MEMORY_OVERHEAD_FACTOR (1.10), lighter than MLX's 1.30, because the C++ runtime carries no MLX buffer cache or Python interpreter overhead. Estimation lives in skulk.shared.models.memory_estimate, shared with the worker's local pre-spawn OOM guard so the two checks use the same estimator. The worker guard (_local_shard_fit_error, footprint_exceeds_usable) applies a _LOAD_FIT_TOLERANCE (10%): it refuses only when the footprint exceeds live usable beyond that margin, because the footprint is already padded (overhead factor + KV + floor) and the master admits on a gossiped figure that can sit a few hundred MB above the worker's live reading. Without the tolerance a sub-GB live-versus-gossip jitter flips a master-admitted borderline split to a refusal (#383: a 0.2GB / 2% miss refused a 24B model at the LoadModel re-check across a 3-node ring); a gross shortfall still refuses, preserving the leak-on-OOM guard. Failures raise typed PlacementErrors, with PlacementInfoPendingError for the cluster-startup windows where cluster info has not finished gossiping (connection edges lag identities; memory info lags the edges). The API dry-runs placement before forwarding (400 on impossible, 503 after a 15s wait on pending info). Instance listener ports (ring ephemeral_port, JACCL coordinator, RPC donor ports) are allocated by random_ephemeral_port from the reserved band _PLACEMENT_PORT_RANGE (24000-31999), below BOTH the Linux (32768+) and macOS (49152+) OS ephemeral ranges, and exclude ports already held by live instances (_listener_ports_in_use), so a placement's listener can never collide with a short-lived OS connection or a sibling instance; band exhaustion raises PlacementError loudly instead of looping (#457). |
DeleteInstance | Tear down a placed model | Emit InstanceDeleted; workers tear down runners |
FailInstance | Worker reports a terminal runner or immutable model-identity failure with a stable category and bounded payload-free explanation. | Emit InstanceFailureRecorded before the normal InstanceDeleted teardown; an unknown/already-removed instance is an idempotent no-op. |
RefuseInstancePlacement | Worker → master: this node cannot fit its shard at load time (the live GPU-wireable reading sits below what the gossiped telemetry admitted). Carries instance_id, node_id, reason, and engine_refusal_code when the refusal is an engine package's instead (the master then places the model again at the same width on another engine; see Engine packages). | Delete the refused instance and re-place the same model one node wider (min_nodes = refused width + 1, via replacement_command_for_refused_instance + place_instance), so each node holds a smaller share. If no wider cycle exists (PlacementError), the master does not stop there on a heterogeneous cluster: it falls back to single-node width excluding the refuser (fallback_command_for_refused_instance, #455), because the wider-split assumption (every node can hold a smaller share) breaks when engines differ per node (a GGUF model refused by one GPU node may still fit alone on another GPU node but can never widen onto a Mac). Fallback instances are tracked in _fallback_placed_instances: a refusal against a fallback placement is terminal (tear down, cancel the model downloads the doomed placement started via cancel_unnecessary_downloads, give up; #456), bounding the refusal chain at two hops so it cannot oscillate between refusers. Idempotent: a refusal for an already-removed instance is a no-op. Fixes #290 (place-then-silently-vanish on tight multi-node splits). |
TaskFinished | Mark a streaming task complete (sent by API on stream end) | Emit TaskDeleted (TaskStatusUpdated(Complete) is emitted earlier on the chunk path, not from TaskFinished directly) |
TaskCancelled | Cancel an in-flight command (sent by API on /v1/cancel) | Emit TaskStatusUpdated(Cancelled) |
VideoGeneration | Render one audio-video clip; carries VideoGenerationTaskParams and the owning API owner_node | Resolve the mode, pick the least-loaded instance whose card serves it, emit TaskCreated(VideoGeneration); no eligible instance yields a Failed task plus TaskFailed(video_mode_unavailable) |
SetTracingEnabled | Cluster-wide tracing toggle | Emit TracingStateChanged |
AddCustomModelCard | User-added model card | Emit CustomModelCardAdded; nodes persist locally |
DeleteCustomModelCard | Remove user card. Optional expected_card makes the removal exact: a signed-card adoption retiring a custom override names the card it saw. | Emit CustomModelCardDeleted; refuse when expected_card is set and the ordered card differs, or when a qualification cleanup no longer owns the alias |
ChangeEnginePackage | Ask one node to activate, roll back or remove an engine package build it holds (target_node, owner_node, engine_id, lane, action, optional build; for a roll back the build is the one expected to become active, so a replay is harmless) | Emit EnginePackageChangeRequested with a 120-second expiry; record the answer |
SetModelEngineOrder | Set or clear a person's engine order for one model (engine_order of backend tags, or none to clear) | Emit ModelEngineOrderChanged; refuse a malformed order where the command is built |
EvictStagedModel | Drop a store-deleted model's locally-staged copies fleet-wide. Sent by the API right after DELETE /store/models/{id} removes the store host's canonical copy, because workers cache their own staged shards independently of the store (#427). | Emit StagedModelEvicted |
Download-failure recovery (#381, plan loop, not a command): a multi-node instance whose ring forms but where one rank's model download fails terminally (disk full, transient HF/network error) sits at RunnerConnected forever: the failed rank never becomes load-ready and nothing fails or recovers it. The master's _plan reconcile (_recover_download_failed_instances, gated on the same TOPOLOGY_SETTLE_GRACE_SECONDS as the liveness passes) detects it via instances_wedged_by_download_failure (a not-all-ready instance whose any rank node carries a terminal DownloadFailed for the model), fails in-flight API tasks bound to it (cause surfaced), tears it down, and re-places at the same width excluding the failed node(s) (replacement_command_for_download_failed_instance + place_instance(excluded_nodes=...)). Every repair re-placement (this path, the #290 wider refusal re-place, and its anywhere-fallback) also carries the ORIGINAL placement's excluded_nodes, stamped on BaseInstance.excluded_nodes at placement time (#658): before the stamp, repair reconstructed intent from the instance and silently widened eligibility back to the full topology, landing repaired instances on exactly the nodes the caller excluded. PlacementError (no healthy node set hosts the width, e.g. a cluster-wide failure) is terminal: stop at the teardown. The search exclusions accumulate across a repair lineage: _download_failure_lineage (master-local, keyed by the replacement instance id, which is the replacement command id) carries every node that failed earlier in the chain into the next hop's excluded_nodes, while stamped_exclusions stays the original intent so a transient failure never becomes permanent placement intent. Without it each hop excluded only the latest failure, and because the reset below clears the stale record, a failure that repeats on every node cycled forever under new instance ids; with it a lineage makes at most one attempt per node before PlacementError ends it. A memory refusal (#290) of a lineage's replacement excludes the lineage's failed nodes from both its wider and fallback searches and moves the lineage to the refusal's replacement, so alternating refusal and download-failure hops stay bounded. A lineage retires (retire_download_failure_lineages, each recovery pass) once its replacement is all-ready or, having been seen in state, is gone; a replacement not yet seen is a pending creation and is kept. A new master starts fresh lineages. Deduped via _download_failure_recovered (same rationale as _refusal_replaced: events are emitted by the plan pass but not applied until they round-trip). A ready/serving instance is never torn down by this path even if a stale DownloadFailed lingers. Recovery also consumes the terminal failure record (#454): it emits a NodeDownloadProgress(DownloadPending) for each failed node+model, which apply() replaces over the stale DownloadFailed; without the reset the stale record lingered in session state and the wedge scan condemned every future placement of that model touching that node long after the cause (e.g. a freed disk) was gone. RPC donor nodes are excluded from the wedge scan (RpcDonorShardMetadata ranks never download the model, #328), so a stale failure on a donor cannot condemn a pooled instance.
DOWNLOAD_COMMANDS topic: DownloadCommand union
Discriminated union at src/skulk/shared/types/commands.py. Carried as ForwarderDownloadCommand over the DOWNLOAD_COMMANDS pubsub topic. Used for cluster-wide config sync and model-store coordination, separated from the main command channel because these are typically larger payloads and have different retry semantics.
| Command | What it requests |
|---|---|
SyncConfig | Broadcast cluster config; carries hf_token for fleet-wide convergence (blank dropped; deprecated model_trust stripped); followers merge and persist locally, never letting an absent token erase a local one |
| Model store ops | Download / staging coordination commands (see src/skulk/store/) |
Tasks (not commands)
Note CancelTask is a task (src/skulk/shared/types/tasks.py), not a command. Tasks are work units the runner executes; commands are imperative requests to the master. Cooperative task cancellation is implemented as a CancelTask task delivered to the runner over the mp.Queue.
API endpoints
Lives in src/skulk/api/main.py (route registration in API.__init__).
Inference
| Endpoint | Method | What |
|---|---|---|
/v1/chat/completions | POST | OpenAI Chat Completions; SSE when stream=true |
/v1/instances/{instance_id}/chat/completions | POST | Chat on one exact instance within required allowed_node_install_ids; no replica fallback; returns X-Skulk-Instance-Id |
/v1/responses | POST | OpenAI Responses |
/v1/messages | POST | Anthropic Messages |
/v1/embeddings | POST | OpenAI Embeddings |
/v1/images/generations | POST | OpenAI Images Generation |
/v1/images/edits | POST | OpenAI Images Edits |
/v1/videos | POST | Create an audio-video generation job (JSON or multipart with attachments); returns the OpenAI-shaped video object |
/v1/videos | GET | Page through this node's video jobs (limit, after, order) |
/v1/videos/{video_id} | GET | Retrieve one video job |
/v1/videos/{video_id} | DELETE | Cancel if live, delete stored content, forget the job |
/v1/videos/{video_id}/content | GET | Download the finished MP4 or its thumbnail (variant) |
/v1/videos/{video_id}/cancel | POST | Cancel a queued, running, or uploading video job |
/ollama/api/chat | POST | Ollama chat |
/ollama/api/generate | POST | Ollama generate |
/v1/cancel/{command_id} | POST | Cancel an in-flight task |
Models / placement
Discrete-GPU admission uses usable_vram_by_node / reserve_instance_vram:
min(observed usable VRAM, 90% of physical VRAM - committed concrete shard footprints). Footprints use each instance's stamped context window. Master-local
creations reserve before event submission and retire their temporary reservation
when indexed; deletion and observed release are distinct. API preview/preflight,
ordinary/exact placement, repair and steward paths share these inputs. Exact and
quick-launch refusals retain placement_failed under their acknowledged instance
identity even when an earlier API preflight passed. RPC runtime-selected
partitions remain observation-only; UMA retains combined-pool admission. Non-RPC
exact shards with omitted backends are resolved from node engine telemetry before
context/footprint admission and persisted with that choice. Missing engine
evidence is refused; restored unstamped GPU-host shards reserve conservatively.
| Endpoint | Method | What |
|---|---|---|
/models, /v1/models | GET | List available models |
/models/search | GET | Search Hugging Face repos (search_hugging_face_models, src/skulk/api/model_search.py, #515). A .gguf-filename query adds a bounded manifest fallback (HF search indexes repo metadata, not file manifests): progressively broadened name-prefix terms, at most 100 inspected candidate repos fetched full=True, exact-basename match returned as matched_file (repo-relative), stop at the first tier with a match, ordered by downloads. |
/models/add | POST | Register a custom model card through direct loopback, a direct trusted-fabric peer (private LAN/CGNAT, no forwarding headers), or the authenticated operator gateway, and wait for its exact ordered mutation to converge locally before returning. Optional gguf_file pins one exact quant from a multi-quant GGUF repo: ModelCard.fetch_from_hf(model_id, gguf_file=...) -> select_requested_gguf (repo-membership-verified) instead of select_preferred_gguf; the pin is carried by StoreDownloadRequest.gguf_file on POST /store/models/{id}/download, and staging fast paths reject a staged dir missing the pinned quant or its shard group (_staged_pinned_gguf_missing, store-side recovery before staging). |
/models/add-card | POST | Persist one complete exact card through direct loopback or the authenticated operator gateway. Preserves artifact pins but forces is_custom=true and removes registry card, snapshot, and provenance claims; the explicit add authorizes the pinned repository code for pre-publication qualification. |
/models/custom/{model_id} | DELETE | Remove a custom card |
/instance | POST | Place a fully specified CreateInstanceParams; every embedded shard card must exactly match the effective authorized catalog card. Returns the accepted command_id, exact submitted instance_id, and model card so clients can correlate the acknowledgement with runtime and failure truth. |
/place_instance | POST | Place an already-cataloged model: master picks ranks. Takes PlaceInstanceParams (model id + placement preferences, optional excluded_nodes: list[NodeId] to exclude specific nodes from this placement) and returns the accepted command_id plus its exact instance_id; an unknown alias returns 404 rather than triggering Hub discovery. Not interchangeable with /instance, which takes a fully-specified CreateInstanceParams. |
/instance/{instance_id} | GET / DELETE | Fetch / delete an instance |
/instance/placement | GET | Compute placement preview |
/store/storage | GET | Local node's storage breakdown: staged models (size, last-use, in-use incl. companions), installed identity, verification, manifest completeness, companion ownership, explicit locationKind (store_local or node_cache), event-log bytes, and disk free. This direct inventory remains reconciliation truth even though operator availability is projected through telemetry. Staging eviction: cleanup_on_deactivate default true; not-in-use staged models kept newest-first up to staging_keep_recent_gb (40 GiB default), enforced at deactivate AND node startup (crash-orphan reconciliation). In use (Worker._models_in_use) = a live runner's model and companions, every model and companion an instance in State places on this node whether or not its runner exists (RPC donor shards excluded), and active downloads. Worker._refresh_in_use_markers touches each in-use model's .last_used marker once a minute from the planning loop; the startup pass passes protect_used_since so any copy used within STARTUP_RECENT_USE_GRACE_SECONDS (30 min) survives whatever its size, which covers process restarts (new node id) and the election winner's recreated worker. Inside each serialized store staging transaction, disk safety overrides that grace budget and evicts the idle LRU tail until the exact additional registered artifact bytes fit with 10 GiB OS headroom; resumable manifest data is credited, same-filesystem hardlinks count as zero, and every active base-plus-companion transaction and live runner is protected. An unsatisfied target becomes DownloadFailed before transfer; src/skulk/store/staging_eviction.py, Worker.prepare_staging_transfer. Canonical store downloads are separately serialized and admitted against their exact selected manifest without eviction; store-unreachable direct fallback applies the same reserve to the actual model cache. Companion repos (MTP sidecar / assistant / served draft / split vision weights) resolve through companion_download_specs() (src/skulk/download/download_utils.py) on every resolution path: required companions (vision) fail the load loudly, best-effort companions (sidecar/assistant/draft) log and degrade to plain decode. |
/instance/previews | GET | List candidate placements |
/models/engine-orders | GET | Every person-set engine order, with each model's card default beside it |
/models/engine-order | PUT / DELETE | Set or clear one model's engine order (SetModelEngineOrder); waits up to 10 s for the cluster to confirm, else 503 |
/v1/engines | GET | Every engine package a node holds or is offered, grouped by engine ID, from node telemetry; read-only; packagesEnabled says whether packages are on for the answering node |
/v1/engines/{engine_id}/activate, /rollback, /remove | POST | Change a package on one node (ChangeEnginePackage): body names nodeId, lane and, to activate or remove one build, build. 404 for a node, package or build that is not there, 409 for a change the node's state does not allow, 503 when the node did not answer within 100 s. Needs operations:write through the operator gateway |
State / events
| Endpoint | Method | What |
|---|---|---|
/state | GET | Cluster state snapshot |
/events | GET | Stream stored events (debug) |
/node_id | GET | Local node identity |
/config | GET / PUT | Cluster config (sanitized) |
Field telemetry (opt-in)
- Consent lives in
skulk.yamlundertelemetry:(tri-stateconsent:unasked/enabled/disabled; separatediagnostics_consent;install_id= random UUID, the anonymous rate-limit key AND deletion capability;consented_at/consented_versionstamps;ingest_url). Persisted in the file so it survives restarts (State is rebuilt per session); edited via the dashboard (first-run consent modal, then Settings). Nothing is queued or sent whileunaskedordisabled. - Collector:
src/skulk/api/field_telemetry.pyon the API node. Taps the chat-completions chunk stream (innermost wrap, before the extensions tap), records one sample per generation (model id, canonical hardware classes likeapple-m4-24gb, TTFT, decode tok/s, token COUNTS,error_classenum), plus peer-observednode-deathsamples by diffing the visible node set between flushes. Bounded queue (1000, drop-on-overflow, drops counted), 60s fail-silent flush toPOST <ingest_url>/v1/telemetry, batch kept on failure. Content-free by construction; the ingest service enforces the same allowlist independently. - Dashboard: first-run consent modal (localStorage
skulk-telemetry-consent-seenis the browser-local no-nag marker; dismissal leaves the fleet settingunasked), permanent toggles in Settings, andGET /v1/telemetry/previewshows the exact pending batch.
Tracing
| Endpoint | Method | What |
|---|---|---|
/v1/tracing | GET / PUT | Cluster tracing on/off |
/v1/telemetry/preview | GET | Field-telemetry consent state + the exact pending sample batch |
/v1/traces | GET | List local traces |
/v1/traces/cluster | GET | List traces from all reachable peers |
/v1/traces/{task_id} | GET | Get one local trace |
/v1/traces/{task_id}/stats | GET | Aggregated timing stats |
/v1/traces/{task_id}/raw | GET | Raw Chrome-trace JSON |
/v1/traces/cluster/{task_id} | GET | One trace, proxied if remote |
/v1/traces/cluster/{task_id}/stats | GET | Stats for a cluster trace |
/v1/traces/cluster/{task_id}/raw | GET | Raw JSON for a cluster trace |
/v1/traces/delete | POST | Delete saved local traces |
Diagnostics
| Endpoint | Method | What |
|---|---|---|
/v1/diagnostics/node | GET | Local node diagnostics bundle |
/v1/diagnostics/telemetry | GET | Aggregate local telemetry admission and isolated-egress metrics |
/v1/diagnostics/node/capture | POST | On-demand local capture (sample, vmmap, footprint) |
/v1/diagnostics/node/runners/{runner_id}/cancel | POST | Cooperative runner-task cancel |
/v1/diagnostics/cluster | GET | Fan-out: every reachable node's diagnostics |
/v1/diagnostics/cluster/timeline | GET | Cross-rank merged flight recorder |
/v1/diagnostics/cluster/{node_id} | GET | One peer's diagnostics |
/v1/diagnostics/cluster/{node_id}/capture | POST | Capture proxied to peer |
/v1/diagnostics/cluster/{node_id}/runners/{runner_id}/cancel | POST | Peer runner cancel |
Tools / store / admin
| Endpoint | Method | What |
|---|---|---|
/v1/tools/web_search | POST | Built-in tool: web search |
/v1/tools/open_url | POST | Built-in tool: fetch URL |
/v1/tools/extract_page | POST | Built-in tool: extract page text |
/store/health | GET | Model store health |
/store/registry | GET | Canonical model-store registry plus telemetry-derived cached_on_nodes, location_kind, and cache_inventory coverage (syncing/current/degraded/unavailable) |
/store/reconciliation | GET | Fleet cache reconciliation status |
/store/reconciliation/rescan | POST | Loopback-only immediate reconciliation retry |
/store/internal/exports | POST | Internal target-bound artifact export grant |
/store/internal/exports/{token}/{path} | GET | Internal range-capable artifact export |
/store/models/{model_id}/download | POST | Request store download |
/store/models/{model_id}/download | DELETE | Cancel a pending or active store download while preserving resumable partial files |
/store/models/{model_id} | DELETE | Delete store model |
/admin/restart | POST | Request node restart. Prefer node_install_id for a stable host target resolved against live telemetry; legacy node_id remains session-scoped, and omitting both restarts the local node. |
Bench
| Endpoint | Method | What |
|---|---|---|
/bench/chat/completions | POST | Bench chat completions (separate code path for benchmarking) |
/bench/images/generations | POST | Bench image generation |
/bench/images/edits | POST | Bench image edits |
Pydantic models
Tasks
src/skulk/shared/types/tasks.py. Discriminated union of:
TextGeneration: chat / responses / messages / ollama-chatTextEmbedding: embeddingsImageGeneration: images.generationsImageEdits: images.editsVideoGeneration: audio-video renders (VideoGenerationTaskParams: prompt, model, seconds, explicitmode, size, steps, seed, lora, audio,referenceswith per-slot kind/role/size/sha256 and a worker-filledlocal_path,total_input_chunks). The master places it on the least-loaded single-host instance whose cardvideo.modescontains the resolved mode and fails it terminally (video_mode_unavailable) otherwise.- Sentinel:
Shutdown,CANCEL_ALL_TASKS
Chunks
src/skulk/shared/types/chunks.py. Per-token output:
TokenChunk: text / tool / token-level metadataToolCallChunk: tool callsErrorChunk: error result; terminalPrefillProgressChunk: distributed prefill progressImageChunk: image generation outputVideoChunk: video render progress (stage,step/total_steps,progress, bounded JPEGpreview) and the terminal frame carryingVideoOutputManifest(sha256, size, dims, frames, fps, seconds, audio rate/channels, optional thumbnail digest) plusVideoGenerationStats; the container itself travels onOUTPUT_MEDIAEmbeddingChunk: embedding output
State
src/skulk/shared/types/state.py. Treated as immutable by convention (replaced wholesale by apply() rather than mutated in place); the model itself is not declared frozen=True on model_config, so direct mutation is technically possible but considered a bug at every call site.
instances: Mapping[InstanceId, Instance]: placed model instances (each carries shard assignments + per-runner state)runners: Mapping[RunnerId, RunnerStatus]: per-runner status uniondownloads: Mapping[NodeId, Sequence[DownloadProgress]]: durable completed/failed download outcomes per node; live pending/ongoing progress resides inTelemetryViewand is overlaid for consumerstasks: Mapping[TaskId, Task]: in-flight or recently-completed taskslast_seen: Mapping[NodeId, datetime]: last indexed control-plane event per node; not a heartbeat or proof of current liveness, and stale by design for healthy nodes with no changing control statetopology: Topology: cluster-wide node graph + capabilities (encoded/decoded viaTopologySnapshotfor JSON round-tripping)tracing_enabled: bool: cluster-wide tracing flagmodel_engine_orders: Mapping[ModelId, tuple[str, ...]]: each person-set engine order, backend tags most preferred first; set and cleared only by an explicit request; carried across a master changeengine_package_needs: Mapping[RunnerId, int]: bytes an engine package said a placed load takes; present only for runners on a package whose engine gave a figure; carried across a master change with the placementslast_event_applied_idx: int: water mark for the local applynode_network,node_thunderbolt,node_thunderbolt_bridge: Mapping[NodeId, *]: the connectivity per-node maps that stay on the event path because they define the topology graph (see "Connectivity readings stay on the control plane" under the Telemetry plane section). They update at independent frequencies viaNodeGatheredInfo.node_resources(slice 1),node_memory+node_system(slice 2), andnode_identities+node_disk+node_rdma_ctl(slice 3) are notStatefields: they moved to the telemetry plane (TelemetryView, gossiped onTELEMETRY, see "Telemetry plane" above) as part of #279.Statekeepsextra="forbid", so a pre-#279 snapshot carrying the oldnodeResources/nodeMemory/nodeSystem/nodeIdentities/nodeDisk/nodeRdmaCtlkeys is rejected, which is the intended behavior, since mixed-version clusters are unsupported and a node never reloads its own persistedStateacross restart anyway (identity is ephemeral; State is rebuilt from the event log / state-sync). An earlier before-validator that stripped those keys was removed in #294 because it broke state-sync (it forced strict Python-mode validation, rejecting ISO datetime strings likelastSeen).thunderbolt_bridge_cycles: Sequence[Sequence[NodeId]]: detected Thunderbolt-bridge cycles where every node has it enabled (>2 nodes)
Note: there is no master_node_id field on State. Master identity lives outside the event-sourced state: each node tracks the current master independently via the election protocol (src/skulk/shared/election.py). placements is also not a field; placement information is derived from instances (each Instance has its own shard assignments).
Diagnostics
src/skulk/shared/types/diagnostics.py. Major models:
NodeDiagnostics: runtime + identity + resources + processes + supervisor_runners + placements + warnings. Cross-node reads use the tolerant operational decoder, which ignores unknown additive fields recursively; missing additive stream-reclamation counters default to zero.warningsincludes mixed-build, mixed-DATA-transport, and leaked-wired-memory alerts (_leaked_wired_warninginsrc/skulk/api/main.py). The wired-memory warning is emitted whenresources.current_wiredexceeds ~5GB with zeroprocess_aliverunners (the signature of wired memory leaked by an abnormal Metal termination that only a reboot reclaims, #239). Server-side counterpart oftests/preflight_mem.sh. To stop a doomed runner from compounding such a leak, the worker circuit-breaks runner crash loops (CrashWindowinsrc/skulk/utils/crash_window.py, 3 failures within 60s) and gives up rather than relaunching it. The shipped systemd unit complements that subprocess boundary withOOMPolicy=continue: an OOM-killed runner child does not make systemd stop the Skulk parent, API, or co-hosted model store. The give-up action depends on why: a genuine crash or GPU wedge sendsFailInstance, which retains a classified cause before ordinary teardown, while a memory fit refusal (the pre-spawn guard rejecting the shard) sendsRefuseInstancePlacementinstead, so the master records the refused placement and re-places the model one node wider rather than letting it silently vanish (#290). A third trigger is a first-status-report deadline (#272,_RUNNER_FIRST_REPORT_DEADLINE_SECONDS, 120s, viarunners_never_reported): a runner frozen between spawn and its first status report (SIGSTOP, a hang in early import) never trips the crash breaker (the process is alive) and stallsConnectToGroupforever (the group-init gate waits for every rank to report), so on expiry the worker gives the instance up through the same edge-latched breaker. The supervisor distinguishes "reported idle" from "never reported" viahas_reported_statusbecausestatusdefaults toRunnerIdlebefore the process ever speaks.ProviderDiagnostics: bounded process-local provider evidence included inNodeDiagnostics.provider: active unary/stream calls and concurrency limits, stream admissions and overload rejections, caller-input queue depth, frame and inline-media byte volume, first-output/lifetime timing, terminal outcomes, cancellation requests, and missing terminals. Values are aggregated and keyed only by qualified capability ID; completed call IDs and payloads are not retained.NodeResourceDiagnostics: gathered_memory, current_memory, current_wired (OS-level wired in use; macOS-only viaread_wired_memory_bytes/psutil, since MLX's own accounting can't see leaked wired), disk, system, network.current_wiredis read locally on the diagnostics path and deliberately kept OFF the gossipedMemoryUsageso theNodeGatheredInfoevent wire format is unchanged across a mixed-version rollout.MemoryUsage: ram_total, ram_available, swap_total, swap_available. On macOS,ram_availableis the GPU-wireable figuretotal − wired − anonymous − compressorfrom avm_statsnapshot taken per telemetry sample (MachMemoryCategories/parse_vm_stat_outputinsrc/skulk/shared/types/profiling.py), falling back to mactop's rawavailable(free+inactive+speculative, which counts reclaimable file cache as used) whenvm_statfails. Value-only change: the gossiped shape is unchanged, so mixed-version clusters interoperate.RunnerSupervisorDiagnostics: flight_recorder, status, phase, MLX memory, in_progress_tasks, milestonesRunnerFlightRecorderEntry: at, phase, event, detail, attrs, context, mlxMemoryMlxMemorySnapshot: active, cache, peak, wired_limit (MLX's configured limit, not OS wired usage)ClusterDiagnostics: fan-out wrapper with aggregateversionStatus; everyClusterNodeDiagnosticsentry carries its own comparison status and remains present when reachableClusterTimeline: cross-rank merged: runners (synopsis) + timeline (entries sorted byat) + unreachableNodesDiagnosticCaptureResponse: capture bundle (process samples, flight recorder, MLX memory)
Node facts
src/skulk/shared/types/node_facts.py (+ derivation in src/skulk/facts/derive.py, doctor verdicts in src/skulk/doctor/checks.py); all frozen:
NodeFacts: everything one probe pass observed/was-declared on this node; no derived capability.platform,gpus: tuple[GpuDeviceFact, ...](all vendors, all devices; each withvendor,name,index,detection_sourceinnvml/nvidia_device_node/amdgpu_sysfs/apple_platform,vram_total_bytes,gtt_total_bytes,compute_capability), importable-dep flags (pynvml_importable,llama_cpp_importable+llama_cpp_gpu_offload,mlx_audio_importable),EngineBinaryFactper engine env var (statenot_configured/ok/missing/not_executable),llama_server_device_probe: LlamaServerDeviceProbe(--list-devicesoutcome + computes), and the raw declaredSKULK_*_BACKENDSstrings verbatim.CapabilityConflict: one loud observation-vs-declaration disagreement:code(gpu_serving_disabled[error] /gpu_detection_degraded/invalid_engine_binary/backend_override_conflict[warn]),message,remediation(composed on the owning node). Advertised onNodeResources.capability_conflicts; mapped one-to-one ontonodeHealthreasons. Severity source of truth:CONFLICT_ERROR_CODES.BackendDerivation(facts/derive.py): the pure result ofderive_node_backends(facts):backends: frozenset[str](the tags to advertise),conflicts, and informationalnotes(one warning-level log line each).CheckResult(doctor/checks.py): one doctor verdict, self-contained for rendering:check_id,title,verdict(ok/degraded/fail),detail,consequence,remediation,fix_available(whetherskulk doctor --fixcan remediate safely).
Model card
src/skulk/shared/models/model_cards.py::ModelCard. Fields:
model_id,family,quantization,base_model,n_layers,hidden_size,num_key_value_headstasks: list[ModelTask]: what task types this model servescapabilities: list[str]: text / vision / thinking / thinking_toggle / embedding / tts / sttcontext_length,storage_size,supports_tensor,trust_remote_code,is_customsource_revision: str | None: full immutable Hugging Face commit used for qualified artifacts;Nonefollows mutablemainmin_skulk_version: str | None: oldest Skulk release that can serve the card (plain PEP 440 release, normalized).card_requires_newer_skulk(card, running_version)compares it withskulk.shared.version.get_skulk_version()(a pre-release or dev build counts as its release; an unreadable version fails closed). Below the floor, the card is skipped where it loads:registry_model_cards, the installed-record snapshot (_apply_installed_card_snapshot), and the custom-file loader (_load_cards_from_dir), each warning once per card;POST /models/add-cardrefuses it with 422. Builds older than the field skip it through the registry's vocabulary-skew rule (extra_forbidden), so a floored card never reaches a release that predates it.gguf_file: str | None: repo-relative GGUF weight path this card serves (GGUF cards only). Default selection isselect_preferred_gguf(quant preference order); a caller-pinned file usesselect_requested_gguf(repo-membership-verified, #515). Shard-group co-download and staged-directory completeness checks key off this path.vision: VisionCardConfig | None: image_token_id, model_type, BOI/EOI tokens, optional weights_repo/processor_repo, and matching immutable revisions for either repository when separately hosted by a signed external card. GGUF served vision additionally uses pairedprojector_file/projector_size; the owning card must also pingguf_fileandsource_revision.reasoning: ReasoningCardConfig | None: supports_toggle, supports_budget, format, default_effortmodalities: ModalitiesCardConfig | None: supports_native_multimodal, supports_audio_inputaudio: AudioCardConfig | None: kind (tts/stt), default_response_format, response_formats, supports_streaming, supports_realtime, supports_voice_listing, voices, ordered voice_catalog metadata (including optional bundledreference_profile), default_voice, supports_reference_audio, supports_translation, sample_rates. TTSsupports_streaming=trueenables the stable chunked HTTP/provider path without an experiment gate.tooling: ToolingCardConfig | None: tool_call_format, supports_tool_calling, builtin_toolsvideo: VideoCardConfig | None: audio-video generation contract.modes(t2va,fl2va,ref2va; each implies exactly oneModelTaskofTextToVideo/ImageToVideo/ReferenceToVideo, andtasksmust agree),min_seconds/max_seconds,fps,frame_grid_multiple/frame_grid_offset(valid frame counts satisfycount % multiple == offset;align_frame_countandframe_count_for_secondssnap up),canvas_multiple,default_short_edge,max_pixels,aspect_ratios(W:H),audio_outputwithaudio_sample_rate/audio_channels,default_steps,video_shift/audio_shift,reference_limits(required forref2va: max_images, max_videos, max_audio_clips, max_files, clip and total durations), andcompanions: pinnedlora/model_patch/embedding/graph_template/preprocessorfiles withpath, optional externalrepoplus mandatory immutablerevision,size_bytes,modes, lora-onlysteps/video_shift/audio_shift, a preprocessor-onlyrole(pose_estimator,person_detector,depth_estimator; each at most once per card) and an optionallicense(the hosting repository's declared identifier). At most one graph template per mode. Names no engine; engines map these facts onto their own mechanisms.ModelCard.external_video_companions()lists each distinct external(repo, revision)once; downloads (companion_download_specs, required; direct downloads and store transfers alike fetch exactly the named files at their pinned revision, the store verifying each at its declared size throughselect_store_video_companion_files, since a companion transfer applies its owner's signed bundle only to a base artifact pertransfer_bundle), the completeness gate (model_companions_present_on_disk, offline included), the worker and API in-use sets that protect staged artifacts from eviction, installed records (artifact_role = "video_companion"), and the store host's companion verification all read it. Acontrolclip is ordinary footage:shared/types/video.derivable_guides(video, mode)lists the guides a card derives (each needs the card's ControlNet for the mode plus the preprocessor roles inVIDEO_GUIDE_PREPROCESSORS: pose needspose_estimatorandperson_detector, depthdepth_estimator, edges none);control_kindselects one (defaultpose), the API refuses an underivable kind before dispatch,/v1/modelspublishesvideo.guidesanddefault_guide, and the comfy graph inserts ComfyUI's own chain (derive_*nodes: RT-DETR plus SDPose, Depth Anything 3, or Canny) between the clip's frames and the ControlNet'scontrol_video. The comfy engine maps each preprocessor role to its ComfyUI folder (checkpoints,diffusion_models,geometry_estimation), refuses to start with a named companion unstaged, and adds each staged companion repository toextra_model_paths.yamlas its own search root.license: LicenseCardConfig | None: operator-facing license facts (name,url,spdx_id,notice,display_namethat UIs must show prominently). Surfaced by the catalog, never enforced by download or placement.runtime: RuntimeCapabilityCardConfig | None: prompt_renderer, output_parser, metal_fast_synch, mtp_heads, mtp_max_depth, mtp_sidecar_repo, mtp_norm_convention, mtp_concat_order, assistant_model_repo, served_spec_draft_repo, vllm_spec_draft_repo, each matching companion revision when separately hosted, vllm_tool_call_parser and vllm_reasoning_parser (explicit vLLM server-side parser pins, no family fallback), and speculative_multi_node (setfalsewhere multi-node speculation measures slower than plain sharded decode, e.g. gemma-4-26B-A4B MoE, 2026-06-06 matrix: 30.2 plain vs 28.2 MTP on 2 nodes; single-node speculation unaffected; card-driven so the agreement collective stays rank-symmetric)placement: PlacementCardConfig(the only section the planner reads directly,master/placement.py).compatible_backends: frozenset[str]is a hard filter (route only to nodes whose advertisedNodeResources.backendsintersect it; default{"mlx"}).backend_preference: tuple[str, ...]is a soft, ordered rank among those backends: the planner prefers a cycle that can serve an earlier-listed tag (_cycle_backend_preference_score) and the runner picks the earliest backend the node has. Backends use compound<engine>-<compute>tags (mlx-metal,mlx_audio-metal,llama_cpp-vulkan,llama_cpp-rocm, and so on; vocabulary + node probing insrc/skulk/shared/backends.py); nodes also advertise the bare engine tag (mlx) for back-compat with original{"mlx"}cards, andmlx_audiofor speech-capable macOS nodes whenmlx_audioimports. The split is deliberate: filter answers "which nodes are allowed", preference answers "fastest for this model" (Vulkan vs ROCm performance is model-dependent), so a Vulkan-preferring model still degrades gracefully onto a ROCm-only node. Alsomin_vram_gib(hard),max_context_tokens(soft KV-budget cap), andmax_pipeline_split_layer(hard upper boundary for later pipeline ranks when a model tail reuses earlier KV; constrained allocations are memory-checked before launch).
Capability profile
src/skulk/shared/models/capabilities.py::ResolvedCapabilityProfile. Computed at request time from card + tokenizer + task params:
family(string)supports_thinking,supports_thinking_toggle,supports_thinking_budgetsupports_image_input,supports_audio_input,supports_native_multimodalsupports_speech_synthesis,supports_transcription,supports_speech_translationsupports_audio_output,supports_realtime_audio,default_audio_response_format,audio_response_formatssupports_tool_callingthinking_format: ReasoningFormat: None_ / TokenDelimited / ChannelDelimiteddefault_reasoning_effort,disabled_reasoning_effortprompt_renderer: PromptRendererType: Tokenizer / Gemma4 / Dsmloutput_parser: OutputParserType: Generic / Gemma4 / GptOss / DeepseekV32 / MuseGlimmertool_call_format: ToolCallFormat: Generic / Gemma4 / GptOss / Dsml / Atembuiltin_tools: tuple[BuiltinToolType, ...]
Pipeline-parallel sharding strategies
Family-specific in src/skulk/worker/engines/mlx/auto_parallel.py. Each is a class implementing TensorParallelShardingStrategy. Dispatched at lines 830-905 via isinstance(model, X) chain (consolidation tracked under #130):
| Strategy | Applies to | Lines |
|---|---|---|
LlamaShardingStrategy | Llama, Ministral3 | 939+ |
DeepSeekShardingStrategy | DeepseekV3, DeepseekV32, KimiK25 | 995+ |
GLM4MoeLiteShardingStrategy | Glm4MoeLite | 1080+ |
MiniMaxShardingStrategy | MiniMax | 1226+ |
QwenShardingStrategy | Qwen3Moe, Qwen3Next, Qwen3_5Text, Qwen3_5Moe | 1267+ |
Glm4MoeShardingStrategy | Glm4Moe | 1428+ |
GptOssShardingStrategy | GptOss | 1476+ |
Step35ShardingStrategy | Step35 | 1519+ |
NemotronHShardingStrategy | NemotronH | 1564+ |
Family-specific code locations
Inventory snapshot; see #130 for consolidation plan.
| Family | Total lines | Primary locations |
|---|---|---|
| Gemma 4 | ~480 | gemma4_prompt.py, parse_gemma4_thinking_channels in model_output_parsers.py, native-vision branches in generate.py:1337-1900; image pooling is mlx-vlm's own (its vision tower sizes pooled tokens from the real patch grid, so Skulk no longer wraps it) |
| Qwen (5 variants) | ~350 | QwenShardingStrategy in auto_parallel.py:1267-1567 |
| DeepSeek V3.2 | ~350 | dsml_encoding.py, parse_deepseek_v32 in model_output_parsers.py:374-516 |
| GLM-4 (Lite + MoE) | ~280 | Two strategies in auto_parallel.py |
| MiniMax | ~225 | MiniMaxShardingStrategy + custom attention wrapper in auto_parallel.py:1148-1226 |
| NemotronH | ~210 | NemotronHShardingStrategy + Mamba2 hybrid cache |
| GPT-OSS | ~180 | MLX: parse_gpt_oss (token-level Harmony parser via openai_harmony) + GptOssShardingStrategy. llama.cpp: HarmonyTextParser in harmony_text_parser.py reparses the harmony channel markers from llama.cpp's detokenized string deltas (the engine exposes no token ids), splitting analysis→reasoning / final→content and stripping markers; wired in llama_cpp/runner._generate, gated on OutputParserType.GptOss, and dependency-free (no MLX/openai_harmony) so it runs on non-Mac GPU nodes. |
| Step 3.5 | ~95 | Sliding-window cache tracking in auto_parallel.py:639-650 |
| Muse Glimmer | ~450 | Family default in capabilities.py (_is_muse_glimmer_family: always-on channel reasoning, no toggle, default strength high, ATEM tools, OutputParserType.MuseGlimmer; muse_glimmer_template_kwargs maps reasoning_effort onto the template's reasoning_strength). MLX: MuseGlimmerTextParser in llm_inference/muse_glimmer_text_parser.py (pure Python, routes to=self to reasoning, to=user to content, tool-addressed channels through the shared ATEM reader, bounded marker hold-back) wrapped by parse_muse_glimmer in model_output_parsers.py (special-token ids reconstructed when a detokenizer drops them). Served engines parse natively (llama-server b10353+, vLLM 0.28 and later muse_glimmer tool and reasoning parsers); llm_inference/reasoning_controls.py translates effort to chat_template_kwargs.reasoning_strength for both served runners. In-process llama.cpp is gated off by the binding's llama.cpp vintage. |
| Llama / Ministral | ~70 | LlamaShardingStrategy (default); the unmarked tool dialect (end-of-message stop token plus bare-object block opening, see "In-process tool-call dialects" below) in utils_mlx.py and tool_parsers.make_text_dialect_parser |
In-process tool-call dialects
worker/runner/llm_inference/tool_text_parser.parse_tool_calls_from_text is
the shared dialect reader. The llama_cpp runner calls it directly for every
call its bundled chat handlers did not already parse. The mlx engine reaches
it only through the parsers wired onto the tokenizer in utils_mlx: the
generic <tool_call> dialect (_parse_generic_text_tool_calls), the Gemma 4
dialect (_parse_gemma4_tool_calls, delegating to the shared
gemma4_calls), the Mistral
dialect (_parse_mistral_tool_calls, wired when the chat template speaks
[TOOL_CALLS]; the end marker is an impossible sentinel rather than the EOS
literal, since </s> can occur inside generated arguments, so the block
closes only at end of generation, the same way the unmarked dialect closes), and the unmarked dialect (make_text_dialect_parser)
delegate to it, while a family parser the tokenizer supplies itself is wrapped
by make_mlx_parser and called directly, and gpt-oss and DeepSeek V3.2 bypass
it entirely for their own token-level parsers (parse_gpt_oss,
parse_deepseek_v32). Adding a dialect here therefore reaches llama.cpp and
those MLX paths, not every MLX model.
When the caller passes the model's resolved tool_call_format, dialect
selection is card truth first: a Gemma-format model parses only its dialect, a
gpt-oss model only harmony, an ATEM-format model only ATEM, and any other specialized format gets no text
inference at all (its foreign-marker or bare-object echoes are content). Only
the Generic family, and callers with no profile, fall to text inference:
there, a message opening with a valid JSON object is the unmarked dialect,
selected first and exclusively (the outermost structure is JSON, so markers
inside its string values are content), and otherwise the dialect is selected
by the EARLIEST recognized marker in the text and parsed exclusively (the cross-dialect injection guard: a quoted argument may
carry another dialect's shape in either direction, so the outermost structure
decides and no later branch rescans the message; a selected dialect that
parses nothing yields no call rather than a fallback scan). Recognized
dialects: harmony to=functions.NAME channels (gpt-oss); Muse Glimmer ATEM
<atem:function_calls> blocks (complete blocks only, atem_calls, shared with
the MLX channel parser); Gemma 4
<|tool_call>call:NAME{...}<tool_call|> blocks (only complete, quote-aware
marker-delimited blocks parse, shared with the MLX family parser so both
engines read one implementation); <tool_call> blocks carrying Hermes JSON, Qwen3 XML, or GLM
<arg_key>/<arg_value> pairs; Llama <|python_tag|> calls (which use
parameters rather than arguments and may chain several with ;; the
chained objects are read as successive balanced JSON spans, string-aware, so
a semicolon inside a quoted argument is data rather than a split point);
Mistral
[TOOL_CALLS] arrays; and an unmarked call object opening the message, which
the model may keep writing after. For the two dialects that know where their
markup ends (the unmarked object and the Mistral array),
parse_tool_calls_with_remainder also reports the visible text around the
call: the llama.cpp recovery path delivers it as content alongside the
ToolCallChunk, and the MLX terminal path routes it through the
message-finishing scan via ToolParser.parse_split (make_mlx_parser
attaches the split overlay for the [TOOL_CALLS] opener; a split miss
defers to the inner parser, so Mistral's displaced upstream NAME[ARGS]
form keeps parsing whole-block). The remainder is empty whenever no call
survives, so a non-call message still falls back to the whole content. The
unmarked rule is deliberately narrow,
since it is otherwise indistinguishable from a model answering in JSON: the
message must begin with the object, the object must carry a name alongside an
arguments or parameters value, and the offered-tools filter below removes
anything naming a tool the caller did not offer. The served engines (llama_server, vllm) do not use this
path: their servers parse tool calls themselves and return structured
tool_calls.
The mlx engine drives this through a rolling marker scan
(model_output_parsers.parse_tool_calls). A generation chunk is whatever the
streaming detokenizer resolved that step, not a token, so a marker that is one
token id still arrives split (<tool, _, c, all>). _block_start_index
therefore searches the accumulated text rather than each chunk, and
_partial_marker_suffix_length carries forward only the trailing run that
could still become a marker. That run is shorter than the longest marker, so
ordinary answers stream with at most a few characters of latency and nothing
is held for a message containing no call. The one longer hold is the anchored
dialect's message-opening {, which opens a block only provisionally:
_classify_anchored_prefix releases the buffered prefix the moment it can no
longer be a call (a top-level key outside the call signature, a non-string
name, malformed JSON, or the object closing without the signature) and commits
the block once a "name" plus "arguments"/"parameters" signature is
distinguishable, so a plain JSON answer streams after a delay bounded by its
first decisive key rather than losing all incremental output to a hold that
could only resolve at the terminal chunk (the unmarked dialect's closing token
is a generation stop that never arrives as text). Released text rejoins the
ordinary scan, so a distinctive marker later in it still opens a real block.
The scan does not stop once ordinary
text has been released, so a model that writes a sentence before calling still
has its call found. A block closes at the first end_parsing found in the
accumulated block (find_close_marker, whose ToolParser.close_scan mode
skips the dialect's quoted string spans where the wiring knows the interior's
quoting rules: infer_close_scan selects Gemma-quote awareness from the Gemma
opener and JSON-string awareness from a template that renders arguments as
JSON, keeping the plain scan for Qwen3 XML and unknown interiors, whose values
carry unbalanced quote characters freely), or at
the end of generation, where ToolParser.parse_split also reports visible
text the model wrote after its call so it reaches the caller as content. The calls of every block in one message are coalesced
into a single ToolCallResponse, which is the OpenAI shape and is what makes
parallel calls survive: several families write each call in its own block, and
API._token_chunk_stream stops at the first chunk carrying a finish reason, so
a response per block would deliver the first call and drop the rest. Trailing
text is therefore released without its finish reason and the tool response is
the terminal chunk. The marker is located rather than matched at the end so
that text the model writes after the call ("</tool_call> Done.") returns to
the opening scan as ordinary text, where a second call in the same message is
still found. Reasoning chunks
(is_thinking=True) pass straight through and take no part in the scan, which
both keeps a thinking preamble from hiding the call and stops a call the model
only contemplated from being executed.
Four properties on ToolParser carry the family differences:
extra_start_parsing: further markers that also open a block. Llama writes the bare call object but prefixes<|python_tag|>when it names a tool, and a marker that does not open the block reaches the caller as content.anchored: whether the primary marker opens a block only at the start of a message. Set for the unmarked dialect, whose marker is{: distinctive markers may open a block anywhere, but a brace also appears in prose and in JSON answers. The families writing that dialect put the call in the whole message, so anchoring costs nothing, and their<|python_tag|>marker still opens a call after a preamble.unparsed_is_text: a block that fails to parse is content, not a failure. Set for unmarked dialects, which open on{and therefore also catch a model answering in JSON.start_markers: the read-side union of the primary and extra markers.
reject_unoffered_tool_calls wraps parse_gpt_oss and parse_deepseek_v32,
which decode their calls from the token stream themselves and are selected
before the marker path, so they would otherwise bypass the rule below entirely;
a call it rejects is re-serialized as content.
tool_parsers.declared_tool_calls drops calls naming a tool the request did
not offer, and a block left with no offered tool is delivered as content. On
the llama.cpp path the same filter covers calls its bundled chat handlers
parsed natively (offered_tool_calls_from_message); since the handler consumes
the raw markup while parsing, a dropped native call is re-serialized as content
(dropped_call_text) rather than leaving a blank answer. This
is what keeps a model's own built-ins (Llama print, gpt-oss python /
browser) from reaching a caller that has no implementation for them. A
request that declared no tools is still scanned on the MLX path:
apply_all_parsers wires the tool parser whenever the tokenizer provides one
and passes emit_calls=bool(tools), so nothing may come back as a call but a
recognized block is still converted to content with its markers stripped.
That is what makes tool_choice: "none" hold on the in-process engines, at
the cost that a no-tools response opening a block is buffered until the block
resolves. The llama.cpp runner does skip its recovery branch with no tools
offered, since its native handler only produces calls when tools are passed;
what covers that engine, and the served engines whose server-side parsers
also never run without tools, is scaffolding_scrub.py: on a no-tools
request the llama_cpp, llama_server, and vllm runners stream content
through StreamingScaffoldingScrub, which strips the cross-dialect marker
vocabulary while holding back partial markers across chunk boundaries, so a
model writing a call anyway cannot leak control markup to the caller.
Logprobs requests on llama_cpp are exempt, because rewriting a token
chunk's text would detach it from its per-token logprob.
declared_tool_calls itself treats a None tools list as "no list to
check against" rather than "nothing may be called", because the steward parses
its own turns through the same dialects without passing one; whether a
no-tools request may return a call is decided where the request is visible,
by emit_calls.
utils_mlx.load_mlx_items adds <|eom_id|> to eos_token_ids for any
tokenizer whose vocabulary has it. Llama declares only <|eot_id|>, so without
this the model generates past the end of its own tool call and emits the next
turn's header into the answer. Detection is by vocabulary, not by the chat
template mentioning the token: Llama's template routes tool results through the
ipython role and never writes <|eom_id|> or <|python_tag|> literally.
KV cache backends
Selectable per-cluster via inference.kv_cache_backend config or SKULK_KV_CACHE_BACKEND env:
| Backend | What | Trade-off |
|---|---|---|
default | Standard MLX, fp16 | Highest memory; baseline |
mlx_quantized | Upstream MLX quantized | Lower memory, decode overhead |
turboquant | Random orthogonal rotation + scalar quant | Storage savings, no decode perf benefit |
turboquant_adaptive | TurboQuant with FP16 edges | Slightly better quality |
optiq | Rotated-space attention trick | Decode-time perf benefit; falls back to default for incompatible head dims |
RotorQuant (block rotations + deferred quant) is research and lives in PR #103; it is not yet in the merged backend set. Verify the current valid values against src/skulk/worker/engines/mlx/constants.py.
Selection logic: src/skulk/worker/engines/mlx/cache.py::make_kv_cache. Some backends fall back to default for incompatible models (e.g., optiq for non-divisible head_dim).
Configuration knobs
skulk.yaml
| Section | Field | What |
|---|---|---|
model_store | enabled, host, port, path | Shared model store config; fresh per-node bootstrap values converge on the elected master's routable store endpoint |
model_store.staging | enabled, node_cache_path, cleanup_on_deactivate (default true; gates the lifecycle recency pass), staging_keep_recent_gb (default 40, warm-cache grace budget for idle copies; 0 = strict evict-on-deactivate) | Staging behavior. Lifecycle recency runs at deactivate + startup. Independent per-transaction capacity enforcement serializes exact registered artifact admission and transfer, protects active base-plus-companion work and live runners, and may override the grace budget to fit only the additional physical allocation plus 10 GiB OS headroom, even when lifecycle cleanup is off. Store-delete (EvictStagedModel) and POST /store/purge-staging remain separate unconditional paths |
inference | kv_cache_backend, served_context_tokens (default 32768, 256 to 1,048,576) | KV cache selection; the context window llama-server, in-process llama.cpp and vLLM placements get when the placement names none (read by the master at placement time from the converged config; MLX is unaffected) |
engines | packages_enabled (default true), package_channel (stable default, or candidate) | Whether nodes use engine packages at all, and whether they also install builds still being tested. Cluster-synced; each worker re-reads them every 60 seconds. An absent section means the defaults and is not written until a person changes one |
logging | enabled, ingest_url | Centralized logging opt-in |
tracing | retention_days | Saved-trace retention for the API janitor (default 3 days; 0 disables pruning) |
hf_token | (string) | Hugging Face token; propagates fleet-wide via config broadcast and join-time bootstrap (never returned by GET /config) |
Environment variables
Skulk settings use SKULK_* names; legacy EXO_* aliases are not accepted.
The table also identifies upstream engine variables that Skulk configures.
| Var | What |
|---|---|
SKULK_HOME | Override the base data directory used to derive SKULK_DATA_HOME (and from there SKULK_MODELS_DIR, SKULK_CUSTOM_MODEL_CARDS_DIR, SKULK_EVENT_LOG_DIR). It also moves the default staging folder (model_store.staging.node_cache_path) to staging inside that directory, so two nodes on one machine never share staged models; without it the default staging folder is ~/.skulk/staging on every platform. Default base: XDG-derived ~/.local/share/skulk on Linux; ~/.skulk on non-Linux. See src/skulk/shared/constants.py:34-149. |
SKULK_FAST_SYNCH | Force MLX_METAL_FAST_SYNCH on ("on") or off ("off"); overrides per-model card. Resolution order: operator override → card metal_fast_synch pin → OFF for speculative-decoding cards (mtp_heads / mtp_sidecar_repo / assistant_model_repo; FAST_SYNCH collapses the MTP loop ~46x, measured 2026-06-06) → cluster default (OFF since #261) |
SKULK_PIPELINE_EVAL_TIMEOUT_SECONDS | Per-eval timeout in pipeline collectives (default 60s) |
SKULK_GROUP_CONNECT_DEADLINE_SECONDS | Hard deadline for distributed group formation (mx.distributed.init, default 120s). Ring init with strict=True blocks forever when a neighbor socket fails the post-TCP rank handshake (#265); on expiry the runner exits via the wedge path, the worker gives the instance up on first failure (#260), and a fresh placement mints a new ring port (also clearing stale-socket handshake collisions) |
SKULK_WARMUP_DEADLINE_SECONDS | Hard deadline for runner warmup (default 300s). A wedged Metal eval parks warmup forever at 0% CPU and silently blocks all dispatch; the watchdog hard-exits the runner instead (supervisor reports RunnerFailed, node keeps working) |
SKULK_EXTENSIONS_DISABLE | 1 skips Python entry-point discovery and managed capability admission; managed owner configuration remains available. See Extensions component section. |
SKULK_TEST_CAPABILITY_NODE | An absolute http(s) URL; when set, this host publishes one stand-in capability node with a single link surface at that URL so the topology satellite layer can be exercised without a managed plugin |
SKULK_GPU_TELEMETRY_VENDOR | nvidia pins Linux GPU telemetry (and the worker VRAM fit guard) to the NVIDIA adapter on mixed-GPU hosts; default prefers AMD sysfs, then NVML |
SKULK_TELEMETRY_DISABLE | 1 hard-disables field telemetry on this node regardless of the fleet consent setting |
SKULK_ENABLE_EXPERIMENTAL_MODE | Node-local master gate for in-development features (off unless truthy: 1/true/yes/on). Read by experimental_mode_enabled (src/skulk/shared/experimental.py); surfaced in GET /config as effective.experimental_mode_enabled. NO built-in experiment is currently active: every speech flag graduated to standard, so the entire experiments config section (tts_streaming, stt_realtime, speech_translation) is deprecated accepted-but-ignored compatibility surface, and the dashboard no longer renders an Experiments section. The gate machinery stays for future features. Speech translation (/v1/audio/translations) is gated only by the mounted card's audio.supports_translation. |
SKULK_MLX_HANG_DEBUG | Emit periodic stack traces from stuck phases |
SKULK_MLX_HANG_DEBUG_INTERVAL_SECONDS | Interval for above (default 30s) |
SKULK_MLX_CACHE_LIMIT_MIB | Per-node cap, in MiB, on MLX's freed-buffer cache in each MLX runner (limit_mlx_buffer_cache in src/skulk/worker/engines/mlx/utils_mlx.py, applied after load beside the wired limit). Unset or blank: a tenth of max_recommended_working_set_size, at least 512 MiB (mlx_buffer_cache_limit). 0 disables the cache. A negative or non-integer value is logged and ignored. Without a cap MLX lets the cache grow to its memory limit (about 1.5x the recommended working set); a 12B model on a 24 GB Mac held 9.5 GB of cache after one response, with no speed difference measured once capped. |
SKULK_MAX_OUTPUT_TOKENS / SKULK_MAX_TOKENS | Default max_tokens (cluster default 4096; DEFAULT_MAX_OUTPUT_TOKENS constant) |
SKULK_NO_BATCH | Disable continuous batching |
SKULK_KV_CACHE_BACKEND | KV cache backend selection (overrides config) |
SKULK_LIBP2P_NAMESPACE / SKULK_LIBP2P_NAMESPACE | libp2p namespace for cluster isolation |
SKULK_ENGINE_BUILDS | Optional JSON mapping engine/backend to canonical build identity for provenance and known package requirements. It never creates a backend or substitutes for runtime probes. Installed distributions report versions and native binaries report content hashes. Malformed declarations log an error; qualification matching remains reporting. |
SKULK_LLAMA_CPP_BACKENDS | Comma-separated llama.cpp compute backends this node was built with, e.g. vulkan or vulkan,rocm (valid: vulkan/rocm/cuda/cpu; metal is MLX-only and ignored). Semantics changed by #614: an OVERRIDE over facts-based derivation, no longer the sole source. Declared, it wins (a GPU compute no observed hardware supports raises a backend_override_conflict but is still honored). Unset, derivation takes over: a binding that positively reports GPU offload (llama_cpp.llama_supports_gpu_offload()) on a node with a visible GPU derives its tags from the hardware (NVIDIA -> cuda; AMD -> vulkan,rocm); otherwise the CPU floor (llama_cpp-cpu). Inert until a node has llama_cpp importable. The GPU-offload cross-check still applies to declarations: a declared GPU backend on a wheel with no GPU offload compiled in (the classic case where uv sync restored the CPU-only PyPI wheel over a source-built GPU wheel) is dropped to llama_cpp-cpu with a loud conflict, so GPU GGUF work is not routed to a degraded build. The service entrypoint (deployment/install/skulk-startup.sh) runs uv sync --inexact when this declares a GPU backend, so a routine sync does not prune the source-built wheel in the first place. |
SKULK_LLAMA_CPP_LOGITS_ALL | Whether the llama.cpp runner loads each GGUF with logits_all=True, enabling per-request logprobs (src/skulk/worker/runner/llama_cpp/runner.py, _logits_all_enabled). Defaults off: logits_all makes llama.cpp pre-allocate an n_ctx * vocab * 4 logits buffer up front, which at the model's full trained context is enormous (e.g. 131072 * 152064 * 4 = 74 GiB for a Qwen2.5 vocab) and OOMs the node on load. So logprobs is opt-in (=1); the runner is loaded once and the flag cannot be toggled per request. With it off a logprobs request degrades to a clear error chunk. Regardless of this flag the served context window is the instance's memory-fit ceiling (serving_n_ctx returns instance_context_token_limit: the largest context that fits the hosting node's working set after weights and overhead, capped at the card's advertised max), never the model's full trained context (n_ctx=0), which would size the KV cache beyond available memory and exhaust the node on load. Placement admits the node against the SAME working set (VRAM on a GPU node) this ceiling is derived from, so the KV cache fits at that window by construction, and on an admitted node it is at least the KV_CONTEXT_BUDGET_TOKENS admission floor -- except when the model's own advertised max context is smaller (then it serves that smaller max), when the fit is uncomputable for a gguf card (no num_key_value_heads, missing memory, RPC-donor shard), in those cases instance_context_token_limit clamps back to the floor so llama.cpp never preallocates a window that OOMs on load. A gguf instance on a node WITHOUT true discrete VRAM (Apple unified memory, a CPU-resolved shard, whose static fit is the RAM working set even on a host with a discrete GPU, and a unified-memory AMD APU, whose startup amdgpu allocation also consumes host pages so the combined BIOS VRAM/GTT pool placement uses does not bound the fixed-window load peak) commits its window in system RAM, so the master sizes that window from the live ram_available it admitted the placement against, which the master has already taken net of the footprints of committed placements that telemetry may not show yet, pending ones included (reserve_system_ram_usage over reserve_instance_system_ram, the system-RAM twin of reserve_instance_vram, applied by the master to the node-memory inputs of every placement path before the GPU pool is derived from them, so admission on system RAM and a unified-memory APU's pool charge those placements too, except a loaded Vulkan shard on a unified-memory AMD APU (carve_first_gpu_node_ids), which sits in the BIOS carve that the observed vram_used already takes off the pool and is charged only while its load has not shown; the charge is against the node's working-set ceiling, at the stamped window for a fixed-window engine and at the KV_CONTEXT_BUDGET_TOKENS floor for a lazily growing MLX cache, and a placement whose runners have not reported loaded, pending ones included, is also subtracted from the observed figure, and stays so for RESERVATION_SETTLE_SECONDS after a loaded transition the master applied, since memory telemetry is sampled on its own cadence; a runner loaded before the master watched reads as reflected at once), capped at the node's GPU working-set ceiling less the worker guard's LOAD_FIT_TOLERANCE as headroom (so the guard's allowance cannot be spent on memory that is not there) and at the static fit, never below the floor, and keeps the floor when a hosting node has no live reading; the worker's pre-spawn guard then checks the stamped window against its current free memory before loading, against system RAM for a shard resolved to a non-offloading backend even beside a discrete GPU, and on a unified-memory APU a fixed-window shard is checked against host RAM as well as the combined pool, since its window was sized from host RAM (_local_unified_memory_gpu), except a Vulkan shard on an AMD APU that reports its carve usage (_local_carve_first_gpu, vulkan_fills_carve_first), which fills the carve before it takes host pages and is bounded by the combined pool alone. The large served context is therefore available on unified memory as well as on a discrete GPU. That memory fit is the ceiling; what is stamped is served_context_window (master/placement.py): a caller's requested_context_tokens (from context_tokens on POST /place_instance, persisted on the instance so repair re-placements keep it) exactly when it fits, a PlacementError naming the ceiling when it does not, and otherwise, for a shard that shard_preallocates_kv_upfront, the smaller of the ceiling and the fleet default inference.served_context_tokens (SERVED_CONTEXT_DEFAULT_TOKENS, 32768), which the master reads from the converged config at each placement. Exact POST /instance placements keep their own contextTokenLimit (or the legacy backfill when omitted); the default applies to PlaceInstance. Previews compute the ceiling without the default and report max_context_tokens, default_context_tokens, reserves_context_at_load, and kv_bytes_per_token. This replaces the previous fixed 8192 clamp, which made served models unusable for real-context work (a codebase does not fit in 8192 tokens). |
SKULK_LLAMA_CPP_FLASH_ATTN | Whether the llama.cpp runner loads each GGUF with Flash Attention (src/skulk/worker/runner/llama_cpp/runner.py, _flash_attn_enabled). Defaults on (=1): FA is the modern llama.cpp default and matters most for models with per-layer-varying V embeddings (gemma's interleaved sliding-window attention), where without it llama.cpp pads the V cache and falls back to a full-size SWA cache, wasting VRAM and slowing attention. It is a load-time construction flag (cannot be toggled per request). Set =0 to disable on a backend whose compiled build lacks Flash Attention kernels. |
SKULK_LLAMA_SERVER_BIN | Path to the external llama-server binary the served-backend engine (llama_server) launches and proxies (src/skulk/worker/runner/llama_server/runner.py). When set to an existing executable, the node advertises the llama_server engine (+ compound tags) via _probe_served_backends and becomes a placement candidate for served-engine cards; when unset, startup may provision a pinned managed binary on supported Linux nodes unless automatic provisioning is disabled. The binary must be recent enough to expose --spec-type (>= llama.cpp b9196 for draft-mtp). |
SKULK_LLAMA_SERVER_BACKENDS | Compute backends the llama-server build was compiled with (comma-separated, e.g. vulkan or vulkan,rocm; same vocabulary as SKULK_LLAMA_CPP_BACKENDS). Semantics changed by #614: an OVERRIDE over derivation, no longer the sole source. Declared (or falling back to a SKULK_LLAMA_CPP_BACKENDS declaration; the GPU is the same whichever engine drives it), it wins. Unset, derivation asks the configured binary itself (llama-server --list-devices, ground truth for what the build can drive on this machine), then infers from observed GPU hardware (NVIDIA -> cuda, AMD -> vulkan), then floors at cpu; a CPU-only resolution on a node with a visible serving GPU raises the error-severity gpu_serving_disabled conflict instead of silently launching -ngl 0. |
SKULK_MAX_CONCURRENT_REQUESTS | MLX batch-generator admission width (src/skulk/shared/constants.py): how many generations the in-process MLX engine runs concurrently before queueing. Default 8. Each ADMITTED task owns its own KV cache and MLX has no aggregate KV admission budget (unlike the served engine's fixed-context slot split), so raising this raises worst-case memory with it; the default stays at the memory-safe 8 until admission accounts for aggregate KV (#683 review). Operators on known hardware can raise it per node. |
SKULK_LLAMA_SERVER_PARALLEL | Concurrent-generation slot count for the served llama.cpp engine (_llama_server_parallel, src/skulk/worker/runner/llama_server/runner.py). Default 16; an unparseable or below-1 override falls back to that default loudly. The value is honored exactly and becomes both --parallel N and the ServedConcurrentDispatch width; above one slot the runner also passes --kv-unified so every slot keeps the full stamped window instead of n_ctx / N (#689). Total KV memory stays what placement reserved. The unified pool is shared, so the runner counts each rendered prompt through llama-server, adds its bounded maximum output, and queues requests FIFO until the aggregate reservation fits. A failed count reserves the whole pool and runs alone. Set 1 only for serial isolation. |
SKULK_VLLM_BIN | Path to the vllm CLI the served-backend vllm engine launches (vllm serve; src/skulk/worker/runner/vllm/runner.py). When set to an existing executable and a GPU backend is declared, the node advertises the vllm engine (+ vllm-cuda/vllm-rocm) via _probe_vllm_backends and becomes a placement candidate for vLLM cards; unset permits a verified managed cache or an eligible first-use runtime, honoring offline/opt-out/management policy. |
SKULK_VLLM_BACKENDS | Compute backends the vLLM install targets (comma-separated). vLLM is GPU-only in scope, so only cuda/rocm are honored (metal/vulkan/cpu are ignored). Unset falls back to the node's SKULK_LLAMA_SERVER_BACKENDS then SKULK_LLAMA_CPP_BACKENDS declaration; with no declaration anywhere in the chain, derivation (#614) infers from observed GPU hardware (NVIDIA -> cuda, AMD -> rocm). There is deliberately no cpu floor: a vLLM node with no GPU backend is not a useful placement target and advertises nothing (with a loud conflict when SKULK_VLLM_BIN is set anyway). |
SKULK_VLLM_GPU_MEMORY_UTILIZATION | Pins the fraction of GPU memory vllm serve may use (--gpu-memory-utilization; src/skulk/worker/runner/vllm/runner.py). Unset, resolve_gpu_memory_utilization sizes it to the instance's placement footprint: estimate_shard_footprint at the served window over the CUDA-visible device total (cuDeviceTotalMem through the driver API, which follows CUDA_VISIBLE_DEVICES and MIG and opens no context; NVML device 0, or host MemTotal on a GB10, when the driver cannot be read), rounded up to a ten-thousandth, capped at 0.90, and never below weights plus the window's KV cache at the artifact's own geometry (artifact_kv_bytes_per_token over config.json: every layer at its widest head and KV-head count, an upper bound) plus the shared VLLM_RUNTIME_ALLOWANCE (a 3 GiB minimum for runtime and cold compilation, also reserved by placement and worker admission). An artifact config without that geometry or an unreadable device total keeps 0.90, logged as a warning. An unparseable or out-of-(0, 1] value is ignored. Node-local serving setting. |
SKULK_VLLM_MAX_CONCURRENT_REQUESTS | Upper bound on concurrent in-flight generations the vLLM runner streams to one vllm serve at once (the dispatch ThreadPoolExecutor width; src/skulk/worker/runner/vllm/runner.py). Default 32; an unparseable or below-1 value falls back to the default. A client-side admission bound (an N-permit semaphore caps submitted jobs, so excess load backpressures the task receiver rather than piling up an unbounded in-process queue), and also the server's --max-num-seqs, so vLLM never reserves sequence state the runner cannot use (vLLM 0.31 refuses to start a hybrid Mamba-cache model whose cap exceeds its Mamba cache blocks). |
SKULK_RPC_SERVER_BIN | Optional path to the ggml-rpc-server binary an RPC memory-donor runner launches (#328 multi-node GGUF pooling; src/skulk/worker/runner/rpc_donor/runner.py). Unset, the donor looks for ggml-rpc-server next to SKULK_LLAMA_SERVER_BIN (both build from one llama.cpp tree with -DGGML_RPC=ON; the upstream target was renamed from rpc-server). Neither present means a donor runner fails loudly at spawn. |
SKULK_ENGINE_PACKAGES_DISABLE | 1 makes this node ignore engine packages at launch, whatever engines.packages_enabled says: it offers none, installs none and loads no model on one. Packages on disk stay there (src/skulk/shared/backends.py). The SKULK_ENGINE_ID, _LANE, _BUILD_DIGEST, _GENERATION, _EXECUTABLE, _STATE and _REQUIREMENTS names are not settings: Skulk sets them for an adapter it starts. |
SKULK_NO_ENGINE_AUTOPROVISION | 1 disables engine auto-provisioning on this node (src/skulk/provisioning/llama_server.py). By default a Linux node with no SKULK_LLAMA_SERVER_BIN override downloads the pinned, checksum-verified upstream llama-server build at startup (Vulkan variant when an NVIDIA/AMD GPU is visible, else CPU) and exports SKULK_LLAMA_SERVER_BIN for the process. Node-local launch policy; explicit binary overrides always win regardless of this flag, and an invalid override is never masked by a managed binary. Managed builds install under the SKULK_ENGINES_DIR constant (SKULK_DATA_HOME/engines, so SKULK_HOME relocates it; not an env var of its own), keyed as engines/llama-server/<pin>/<variant>/. |
SKULK_MODEL_REGISTRY_ENABLED | Enables the signed external model-card registry (default true; tests and SKULK_OFFLINE=true suppress network access). Complete installed-card sidecars load first and remain active without the registry cache age limit. When no verified remote or cached catalog is available, the catalog is installed plus custom cards (Skulk ships none); custom cards still load last. |
SKULK_MODEL_REGISTRY_URL | Public TUF repository base URL. Default https://registry.foxlight.ai/; no administrative API is exposed there. |
SKULK_MODEL_REGISTRY_CACHE_DIR | Override for trusted TUF metadata, targets, and the hash-bound last-known-good catalog. Default SKULK_CACHE_HOME/model_registry. |
SKULK_MODEL_REGISTRY_REFRESH_SECONDS | Minimum catalog refresh interval, default 60. Must be greater than zero. |
SKULK_MODEL_REGISTRY_TIMEOUT_SECONDS | Per-socket registry fetch timeout, default 5. |
SKULK_MODEL_REGISTRY_MAX_STALE_DAYS | Maximum age of a previously TUF-verified last-known-good catalog during an outage, default 30; 0 disables stale fallback. |
SKULK_EXACT_CARD_QUALIFICATION_TOKEN | Optional high-entropy bearer (minimum 32 characters) shared only with a trusted registry Scout. It authorizes POST /models/add-card and DELETE /models/custom/{model_id} for the temporary unsigned pre-publication qualification lifecycle; it grants no other API scope and is compared in constant time. Configure the same value as Scout's Skulk API credential on every API node reachable by the qualification URL. |
SKULK_LLAMA_SERVER_FORCE_NO_SPEC | When truthy (1/true/yes/on), the served runner (_force_no_spec) ignores a card's served_spec_type and launches llama-server without any --spec-type / --model-draft flags, so the same GGUF serves in plain decode. This is the apples-to-apples MTP off baseline for an on-vs-off served throughput comparison (identical weights, speculation disabled), and a debug lever for a misbehaving spec pairing. Node-level, read at runner launch; unset in normal operation. |
SKULK_LLAMA_CPP_LOGITS_ALL_N_CTX | Context-length cap (tokens, default 8192) applied only when SKULK_LLAMA_CPP_LOGITS_ALL=1 (_logits_all_n_ctx). Bounds the logits_all buffer (n_ctx * vocab * 4) so opting into logprobs does not blow up memory: at an ~150k vocab, 8192 is ~5 GiB. It is operator policy, so raising it far above the default reintroduces the large allocation it guards against. When logits_all is off the served context is the instance's admission ceiling (_serving_n_ctx), not the model's full trained context. |
SKULK_ZENOH_DATA_PLANE | Zenoh is the shipping default. Resolved by _resolve_zenoh_enabled in Node.create (src/skulk/main.py): truthy (1/true/yes/on) forces the Zenoh DATA plane on, falsy (0/false/no/off) forces gossipsub, and unset selects Zenoh, including on a bare install. When on, the node-addressed data families ride an Eclipse Zenoh peer session; all other planes stay on libp2p. Wired in Router (uses_zenoh). Security (#308, network v0.0.3): the session is scoped and authenticated by the libp2p pre-shared key: key-derived multicast scouting port, mutual TLS 1.3 chained to a key-derived authority, and a default-deny access-control policy on the key-derived member name (see "Zenoh data-plane transport"). Keys are additionally prefixed by a segment that is a collision-resistant SHA-256 hash of the exact token libp2p isolates on (since #659: NETWORK_VERSION ALWAYS contributes and SKULK_LIBP2P_NAMESPACE layers on top when present, so a wire-version bump re-keys BOTH transports on every deployment shape; mirrors swarm.rs with a lockstep test parsing the Rust constants, not the legacy EXO_LIBP2P_NAMESPACE). Neither the raw token nor anything routing-relevant derived from it is logged or served: startup logs and GET /v1/diagnostics/node report only namespace_fingerprint (the domain-separated digest also used by GET /v1/plugins/host-network). Membership is only as private as the namespace: on the default namespace, or a blank one, the key is public, so links are encrypted but any Skulk node can join, and the startup log warns. |
SKULK_ZENOH_LISTEN | Optional Zenoh listen override. When unset, Skulk binds tls/<best-trusted-fabric-ip>:7447: a private-LAN address first, then CGNAT/Tailscale, with virtual, loopback, link-local, unspecified, and public addresses excluded from automatic binding. Offline or public-only hosts fall back to loopback. Set a specific address when the automatic choice is not the intended fabric; public and 0.0.0.0 listeners must be explicit, and 0.0.0.0 emits a warning. Values are tls/HOST:PORT; a legacy tcp/ value is rewritten to tls/ with a warning, and any other protocol is refused at startup. |
SKULK_ZENOH_CONNECT | Comma-separated explicit Zenoh peer endpoints, e.g. tls/192.168.0.117:7447,tls/192.168.0.122:7447 (legacy tcp/ entries are rewritten to tls/ with a warning; other protocols are refused). When set, multicast scouting stays off and the supplied endpoints define the routed/Tailscale mesh. When empty, local multicast scouting is on, on the port derived from the cluster key, so fresh-install LAN peers of the same cluster can discover each other. Per-node. |
SKULK_DATA_REORDER_BUFFER | Explicit override for the data-plane reorder buffer (#279 Phase 3). Unset (default): the buffer follows the DATA transport - ON for gossipsub (it reorders; the #301 fix), OFF for Zenoh (per-publisher FIFO, so arrival order is generation order; validated 20/20 on a 3-node sampled-MTP matrix). Set 1/0 to force it on/off regardless of transport (testing / belt-and-suspenders). Read in API.__init__ (_reorder_buffer_enabled), with the transport signalled by data_plane_zenoh from Node.create. |
SKULK_SKIP_LLM_WARMUP | Skip warmup synthesis (single-node debug only) |
SKULK_IMAGE_TRANSPORT_DEBUG | Verbose logging in image-transport pipeline |
SKULK_VISION_DEBUG_SAVE_DIR | Save debug image artifacts |
SKULK_NATIVE_VISION_REFERENCE_PATH | Force the native mlx-vlm reference generation path for native-vision requests. Skulk selects this path automatically for single-node bundled vision placements; the variable remains an explicit diagnostic override for other placement shapes. |
SKULK_NODE_NAME | Node display-name override used ahead of the hostname/Computer Name fallback. Node-local launch config for machines whose hostname is meaningless: containers and rented GPU pods get runtime-random hostnames (a21147cd1ae7) and an unprivileged container cannot call sethostname (#555) |
SKULK_OFFLINE | Run without internet checks (no model fetching) |
SKULK_PRESERVE_VENV_EXTRAS | 1 makes the supervised startup wrapper (deployment/install/skulk-startup.sh) run uv sync --inexact instead of an exact sync at service start, preserving packages installed outside the locked resolution — separately installed skulk.extensions plugins in particular, which an exact sync would silently prune (and with them the node's loaded extensions) on every restart. Same preservation rationale as the wrapper's existing source-built GPU llama.cpp wheel handling. Off by default: exact sync remains the norm so ordinary nodes keep a reproducible environment. |
SKULK_HEADLESS | Explicit API-only deploy knob read by deployment/install/skulk-startup.sh (the LaunchAgent/systemd entrypoint). 1 skips the dashboard build and its otherwise-fatal dashboard-react/dist missing check, and the node runs with DASHBOARD_DIR unset (#333). Normal macOS and Linux installs use Skulk's pinned bundled Node.js runtime during both installation and supervised boot-time updates, so a host without system Node/npm is not implicitly headless. Default 0 preserves the shipped dashboard and fails loudly when no usable build exists. |
SKULK_CORS_ALLOWED_ORIGINS | Optional comma-separated list of exact extra browser origins (e.g. https://studio.my-tailnet.ts.net) added to the API's CORSMiddleware alongside the built-in loopback, RFC 1918, Tailscale CGNAT IP (100.64.0.0/10), and .local regex (allow_credentials=False). Same-origin MagicDNS dashboard requests do not need CORS; *.ts.net is deliberately not wildcarded because Tailscale Funnel exposes public third-party sites under *.ts.net. |
VITE_TOLGEE_CDN_PREFIX | Dashboard build-time env var. CDN/static prefix for Tolgee JSON bundles, default /i18n; Tolgee fetches namespaced bundles as {prefix}/{namespace}/{language}.json, and the dashboard uses the skulk namespace. |
VITE_TOLGEE_AVAILABLE_LANGUAGES | Dashboard build-time env var. Comma-separated language tags available from the Tolgee CDN/static prefix; en is always included and bundled as the fallback namespace. |
VITE_NIGHT_SKY | Dashboard build-time env var. 1 crowns the dark palette with the brand valley's star-field scene (top of the viewport, dissolving by half the viewport height) plus occasional shooting-star animation, and retires the abstract background mesh for that palette. Default builds ship dark mode as a CSS-only night gradient with the mesh. Decided once in dashboard-react/src/theme/theme.ts via the scene color token; scene-dependent layers (SceneBackdrop, ShootingStars, mesh suppression) all key off that token rather than the theme name. |
SKULK_TEST_DISTRIBUTED_MODEL | Tests only: force the distributed/prefix-cache slow-test model (gpt-oss-20b or llama-3.2-1b); default auto-selects by Metal working-set size |
MLX_METAL_FAST_SYNCH | Set by Skulk based on resolved card preference; not for direct operator use |
MLX_HOSTFILE, MLX_RANK, MLX_RING_VERBOSE, MLX_IBV_DEVICES, MLX_JACCL_COORDINATOR | MLX upstream env vars; auto-set by Skulk during distributed init. Ring hostfile addresses are chosen per neighbor pair from OBSERVED libp2p connections, ranked thunderbolt > maybe_ethernet > ethernet > wifi > unknown > VPN/overlay. Tailscale CGNAT (100.64/10, fd7a:115c:a1e0::/48) addresses are detected by ADDRESS (utun types don't gossip) and rank strictly last: the overlay exists for external reachability and may be DERP-relayed, so it is only used when a pair has no local candidate (#265). Selection lives in _find_ip_prioritised / get_mlx_ring_hosts_by_node (src/skulk/master/placement_utils.py) |
SKULK_COMFY_BIN / SKULK_COMFY_ROOT | Interpreter (<venv>/bin/python) and checkout of a hand-built ComfyUI for the comfy video engine; both required. Absent, a Linux NVIDIA or Strix Halo node installs the pinned managed install the first time a video model is placed on it (or on skulk doctor --fix) under SKULK_ENGINES_DIR/comfy/<pin>/<variant>-<wheel-set digest> (cu130 torch wheels from the PyTorch index, or AMD's stable ROCm 10.0.0 channel for gfx1151; the ROCm lane launches ComfyUI with --bf16-vae --cache-ram N (N = 40% of host RAM in GiB), --use-split-cross-attention for LTX-2.5 prompt subject adherence, and --disable-mmap only for a weight file above 64 GiB, the CUDA lane with --disable-cuda-malloc and, for LTX-2.5 only, --fast-disk disk-backed dynamic weight loading) |
SKULK_ENABLE_IMAGE_MODELS / SKULK_ENABLE_VIDEO_MODELS | Catalog switches for image and video model cards; both default to shown, and false, 0, no, or off hides that family on the node (card_visible_in_catalog). A node with video models hidden never advertises the video engine as installable |
SKULK_COMFY_BACKENDS | Compute backends the ComfyUI install targets (cuda, rocm); unset falls back to the vLLM and llama declaration chain, then to the observed GPU vendor |
SKULK_TEST_VIDEO_ENGINE | Truthy value advertises the deterministic test video engine (test_video / test_video-cpu) on this node; serves only the bundled foxlight/test-video card. Test instrument only |
SKULK_TEST_VIDEO_STEP_SECONDS | Simulated wall time per sampling step in the test video engine (default 0.02) |
SKULK_VIDEO_STORE_MAX_BYTES | Ceiling on committed plus in-flight video artifacts one API node keeps under its video store (default 32 GiB); the store evicts the oldest completed jobs to fit a new artifact |
CLI flags
| Flag | What |
|---|---|
-v / -vv / -vvv | Increase log verbosity |
-q | Decrease verbosity |
--force-master / -m | Force this node into master role; also lets a management node win an election against inference nodes |
--api-port | Override default 52415 |
--no-api | Disable API server |
--no-batch | Disable continuous batching |
--fast-synch / --no-fast-synch | Force MLX_METAL_FAST_SYNCH on/off |
--offline | Offline mode: the same as SKULK_OFFLINE=true (constants.offline_mode()); no registry, engine, or model downloads |
--bootstrap-peers | Comma-separated libp2p multiaddrs |
--libp2p-port | Fixed TCP port for libp2p |
Diagnostic mechanisms
Flight recorder
- Lives at:
src/skulk/worker/runner/runner_supervisor.py(the bounded buffer); emit helpers atsrc/skulk/worker/runner/diagnostics.py - Capacity: last 128 entries per runner
- Always-on; local-only. Not gossiped, but exposed via
/v1/diagnostics/* - Emission helpers:
record_runner_phase(phase, event=..., detail=..., attrs=..., include_memory=False): fire one entryrunner_phase(phase, detail=...): context manager: enter / exit pair
Trace sessions
- Lives at:
src/skulk/shared/tracing.py - API:
begin_trace_session(task_id, rank, node_id, model_id, task_kind, tags): createrecord_trace_marker(name, rank, task_id, attrs): emit one eventtrace(category, name, ...): context manager / decoratorpop_trace_session(task_id): collect + removeclear_trace_session(task_id): remove without collecting
- Storage: module-level dict
_trace_sessions: dict[str, TraceSession] - Cluster path: runner emits
TracesCollectedIPC per rank → runner supervisor sends one owner-addressedTRACE_DATApacket → owning API assembles the expected ranks and persists Chrome-trace JSON to disk
MLX memory snapshot
- Lives at:
src/skulk/worker/runner/diagnostics.py::capture_mlx_memory_snapshot - Returns:
MlxMemorySnapshot { active, cache, peak, wiredLimit, source } - Best-effort: returns None if MLX isn't loaded or the snapshot fails
Process sampling (macOS only)
- Lives at:
src/skulk/api/main.py::_collect_process_samples - Wraps:
sample <pid> <duration>,vmmap -summary <pid>,footprint -p <pid> - Per-command timeout: ~5-8s
- Returns:
list[DiagnosticProcessSample]withok,stdout,stderr,error
Per-eval timeout
- Lives at:
src/skulk/worker/engines/mlx/auto_parallel.py::eval_with_timeout - Wraps: any
mx.eval(...)call with a daemon-thread watchdog - Default timeout: 60s (
pipeline_eval_timeout_seconds(), configurable viaSKULK_PIPELINE_EVAL_TIMEOUT_SECONDS) - On timeout: emits
pipeline_eval_timeoutflight-recorder event, thenos._exit(1) - Used at: every
mx.evalinPipelineFirstLayer,PipelineLastLayer,mx_barrier
Parent-pid watchdog
- Lives at:
src/skulk/worker/runner/bootstrap.py::_install_parent_death_watchdog - Mechanism: daemon thread inside runner that polls
os.getppid(); on reparenting, callsmx.clear_cache()+gc.collect()+os._exit(1) - Why: SIGKILL of the agent leaves daemon
mp.Processrunners orphaned holding GPU memory. The watchdog detects the reparent and self-exits
Centralized observability stack
Exception tracebacks: skulk.__init__ forces LOGURU_DIAGNOSE=False before
Loguru import; node sinks explicitly disable diagnostics. Variable-value
annotations are omitted in node, CLI, plugin and spawned-process sinks.
Local Vector → VictoriaLogs → Grafana. Configuration:
src/skulk/shared/logging.py: loguru JSON sink to stdoutdeployment/logging/vector.yaml: Vector pipeline (stdin → VictoriaLogs)deployment/logging/docker-compose.yml: VictoriaLogs + Grafana stackskulk.yamllogging.enabled+logging.ingest_url: opt-in; cluster-synced
File map quick reference
src/skulk/
├── api/ # FastAPI app + adapters
│ ├── main.py # routes, app construction, fan-out helpers
│ ├── adapters/ # OpenAI, Ollama, Claude, Responses, Skulk-native
│ └── types/ # API-facing Pydantic types
├── master/main.py # event indexing, placement
├── worker/
│ ├── main.py # worker loop
│ ├── plan.py # task dispatch decisions
│ ├── runner/
│ │ ├── bootstrap.py # subprocess entrypoint
│ │ ├── runner_supervisor.py # parent-side lifecycle
│ │ ├── diagnostics.py # flight recorder, MLX memory snapshot
│ │ ├── llm_inference/runner.py # text generation
│ │ ├── embeddings/runner.py # embeddings
│ │ ├── engine_package/runner.py # any installed engine package
│ │ └── image_models/runner.py # image generation
│ └── engines/mlx/
│ ├── auto_parallel.py # sharding strategies + dispatch
│ ├── generator/generate.py # prefill + decode hot path
│ ├── vision.py # vision processing
│ ├── utils_mlx.py # large utility module (decomposition tracked under #130 Phase 6)
│ ├── cache.py # KV cache factory
│ └── gemma4_prompt.py # Gemma 4 prompt renderer
├── engines/ # engine packages: launch, protocol, inventory, changes, orders, CLI
├── provisioning/ # managed engines; engine package manifest, trust, index, install
├── routing/ # libp2p topics, event router, peer discovery
├── shared/
│ ├── types/ # State, events, commands, tasks, chunks, diagnostics
│ ├── models/ # ModelCard, capabilities resolver
│ ├── apply.py # State + IndexedEvent → State
│ ├── election.py # bully algorithm
│ └── tracing.py # trace sessions
├── store/ # config, model store, custom card management
├── utils/ # disk_event_log, channels, helpers
└── main.py # CLI entrypoint
dashboard-react/ # operator UI
deployment/ # observability stack docker-compose
bench/ # benchmark + repro harnesses
docs/ # operator guides (this file in website/docs/)
website/ # Docusaurus site
src/skulk/resources/model_registry/ # embedded TUF root for the signed card registry
src/skulk/resources/speech_reference_voices/ # packaged reference voice profiles (no model cards ship)
src/skulk/shared/tests/fixtures/model_cards/ # copies of registry cards, for tests only
# curated model cards live in the foxlight-model-registry repo, seed/cards/
src/skulk/worker/runner/test_video/foxlight--test-video.toml # the test engine's card; never in the registry
rust/ # libp2p (networking), PyO3 bindings, system_custodian
Isolated operator qualification fixture
- Entry:
bench/operator_workload_fixture.py; opt-in, no Node/discovery/inference. - Real auth/gateway: generated encrypted authority, signed version-two connector, TLS 1.3, scoped canonical authorization; no production configuration accepted.
- Generated API:
bench/operator_fixture_app.py; bounded input, fixed reads/SSE/PCM. - Public rehearsal: explicit
PublicFixtureIngressonisolated_fixtureonly; run-bound WSS hostname, at most one hour, mutually exclusive with private ingress. Controller must enforce bounded exposure, independent expiry and verified cleanup; naming validation does not attest effects. No CLI opt-in or production target. Public-only route readiness: at most 120 seconds and remaining fixture lease; local/private retries unchanged. Pairing exposure also requires controller-side public readiness after the carrier starts. - Local relay lifetime:
bench/operator_fixture_lease.py; independent expiry and parent-EOF watchdog; normal runner teardown removes temporary authority/QR files. - Schema validation:
bench/validate_operator_fixture.cjs; exact app source commit and matching installed schema dependency versions, not physical-device evidence. - Aggregate observation:
bench/observe_operator_workload.py; bounded opaque TCP bridge + ASGI categories/lengths; verified-copy local recorder subprocess. Gateway-boundary, unattested aggregate only; no content, traces, or app-wire change. - Contract and limits: operator-workload-fixture.
Maintenance discipline
This file is intentionally dense. If you find a stale fact, fix it inline rather than working around it.
Engine pin advancement (deliberate, never automatic)
The ComfyUI engine has its own pin: COMFY_PIN (a release commit) and
COMFY_TORCH_WHEELS (exact torch, torchvision, and torchaudio wheels per
machine and variant with their index digests) in provisioning/manifest.py.
Advancing either means re-recording the wheel digests (the PyTorch index
publishes them as link fragments; AMD's stable channel publishes none, so
each artifact is downloaded once and hashed, and the rocm runtime
packages advance together with torch since the channel versions them as
one release), bumping the pin when ComfyUI moves, provisioning a fresh
install on each target lane, and rerunning the video engine battery before
merge. The lanes need not share a torch release: the CUDA lane follows the
PyTorch index and the ROCm lane follows AMD's channel. The managed install
directory is keyed by pin, variant, and the wheel set's digest, so an
advanced pin or a changed wheel set provisions beside the old install rather
than over it and an existing install is reused only when both match; the
superseded install stays on disk until an operator removes it, so a node that
follows several advances should prune old entries under
SKULK_ENGINES_DIR/comfy/.
The managed llama-server engine is pinned (LLAMA_SERVER_PIN in
src/skulk/provisioning/manifest.py, currently b11669) so upstream churn is
a discrete validated event, not a continuous silent risk (the same
source_revision doctrine model cards apply to Hugging Face artifacts).
Advancing the pin is a checklist, and skipping steps is how a silent behavior
change ships:
- Bump
LLAMA_SERVER_PINand re-record every artifact sha256 inLLAMA_SERVER_ARTIFACTSfrom the new release's asset digests (gh api repos/ggml-org/llama.cpp/releases/tags/<tag>). - Revisit
LLAMA_SERVER_CUDA_MIN_REVISIONfor the new pin and validate its packaging floor; both the installer and runtime reject older CUDA revisions. Bump both wheel versions inpackaging/skulk-llama-server-{cuda,vulkan}(scheme0.<build>.<rev>) and the engine workflow pin; theengine-wheelguard fails if either package, the workflow, the manifest, or the installer's derived-version wiring disagrees. - Rebuild the Vulkan wheel and both CUDA platform wheels (x86_64 and aarch64)
and publish them together (
engine-wheelworkflow, dispatch withpublish=true). When the CUDA pod image pin also changes, rebuild it from the same source tag so its server and RPC donor cannot drift. - Diagnose the new pin on a clean ephemeral NVIDIA target, then run the full
public-harness fresh-install candidate qualification before it reaches
main: installer path, doctor verdicts, GPU-speed serving, the physical fleet battery, and mandatory RunPod teardown. - Check upstream release notes for served-API/flag behavior changes (the harness #69 keepalive change is the canonical example of what a pin bump can smuggle in) and update runner/proxy assumptions if needed.
The AGENTS.md "Documentation" section requires updates here when architectural shape changes:
- New component → add to "Components"
- New pubsub topic → add to "Pubsub topics"
- New event / command type → add to "Events" / "Commands"
- New state field → update "State" Pydantic model section
- New major API endpoint → add to the right "API endpoints" sub-table
- New family adapter → update "Family-specific code locations"
- New environment variable → add to "Configuration knobs"
Keep entries terse. Narrative belongs in Architecture.
The trusted steward extension facet reads the current intelligent-fabric mode and global
SKULK_FABRIC_CAPABILITIES_DISABLE kill switch through ExtensionContext.steward_actions_allowed. Proposal
collection and dispatch recheck it; private approved-action adapters must also
recheck it on every dispatch or retry. The callback supplies no approval evidence
or signing authority, and omitted callbacks fail closed.
Advisory model requirements
GET /models/requirements reads the same effective catalog and installed-card
precedence as /models. It binds complete card contents with
authorized_model_card_digest (all JSON-mode fields except the publication
snapshot) and uses estimate_shard_footprint for whole-model text memory at the
requested context. Unknown KV geometry produces a null estimate. The response
also exposes declared storage, backend evidence and core working-set fractions;
it performs no placement, download, reservation or external-provider action.
External controllers must revalidate identity and live admission before execution.
See API contract.
The requirements response exports required_capabilities from the same pure
get_model_required_capabilities resolver used by signed engine admission.
External planners must cover its entire nonempty set, exact engine build and
hardware restrictions. Launchable placement previews expose the same complete
card_digest for binding approved requirements to the submitted instance;
the API/master card checks and resource-derived context ceiling still apply.
Exact-instance creation does not atomically revalidate topology or backend/build
support, so controllers must check live node support before and after submission.
-
Local transport renewal:
managed_attachment.pyshares an API-lifetimeattachment.lockacross configured managed owners. Protected local records bind a generated profile ID and exact manager installation path; legacy records remain manual. InternalAttachmentRequestsupplies the actual transport ID and live measured core digest. The manager requires its exact profile/build and an active bridge fence, stops affected owners, and usesruntime_attachment.pyto journal old/new transport bindings under controller/service/child locks. Interrupted metadata writes recover before owner startup; selected runtimes, logical plugin IDs, settings, receipts and spending reservations are preserved. This is not cleanup enrollment and is not a remote management verb. -
Serve address:
AttachmentRequest.serve_host(omitted when absent, so its bytes are unchanged without Tailscale) carries the node's Tailscale address.ManagedAttachmentreadsquery_tailscale_status()in a background task at most everySERVE_ADDRESS_REFRESH_SECONDS(60 s) and keeps the latest valid address it has seen; a failed read never withdraws it. The manager treats an absent address as "keep". A different address stops the owners, thenpublish_serve_hostwritesServeBindingas owner-onlyserve.jsoninto each installation under the per-installation fences and last into the manager root, whose recordRuntimeManager.serve_hostreads at startup; the owners then restart, and the next attachment finishes an interrupted write._loadbrings each installation'sserve.jsonto the recorded address before its owner starts, so a new registration receives it and an interrupted write is repaired. The file is separate fromowner.json(owners parse it strictly) andhost.json(an older manager must still start). Plugin protocol 3 owners pass the address to children asStartup.serve_host. Extension tests report no Tailscale through an autouse fixture so a developer's tailnet never restarts test owners. -
Local plugin service setup:
service_setup.pyexposesskulk-plugin-service setup [--system]|statusand journals source identity, generated profile, staged runtime and installation progress.ServiceLayout.scopeisuser(default: root~/Library/Application Support/Skulk/plugin-serviceor$XDG_STATE_HOME/skulk/plugin-service, launchd agent~/Library/LaunchAgents/foundation.foxlight.skulk.plugins.plistbootstrapped intogui/<uid>or systemd user unitfoundation.foxlight.skulk.plugins.servicewanted bydefault.target, registered byservice_registration.register_useras the owner with no elevation) orsystem(the sudo helper below).connected_scope()keeps the scopemanaged-service/connection.jsonalready names.service_autosetup.ServiceSetupRunnerruns one user-scope setup at a time inside the API:GET /v1/plugins/managed/service(PluginServiceStatus: absent, setting_up, ready, unavailable, failed, unsupported; additivepurposesetup|updatewhile setting_up or failed) and owner-only bodylessPOST /v1/plugins/managed/service/setup; a host connected to a system service is never re-registered by the node. The status also readsManagedServices.runtime_update()(memory only, never waiting on a copy): from the firstmanager_build_differsuntil the manager attaches on this build it reportssetting_up/update(refresh attempt running, or waiting up to_UPDATE_REPORT_SECONDS= 600 s from the first mismatch, an attempt begun inside it followed to its end plus_UPDATE_SETTLE_SECONDS= 180 s), then a latchedfailed/updatenaming the cause (staging_failed,refused,other_interpreter,not_restarted) that a later setup supersedes; no setup (owner retry or silent-service repair) starts while a refresh attempt runs (RuntimeUpdate.refresh_running, a background retry under a kept failure included), and the first read after start waits up to 15 s for the first observation. DashboardPluginServiceSetupgates the Plugins page on that status and starts setup once for a direct owner. Repeated setup reuses completed staging; source core/Python/dependency changes create a new operation, retaining any interrupted predecessor.service_registration.pyis a standalone standard-library-only sudo helper with prepare/stop/install actions for the current account's fixed nonroot service. It walks root-owned parent directories without following links, refuses foreign unit definitions, and installs system LaunchDaemons or systemd multi-user services. No HTTP request can supply commands, paths or unit bytes. State lives in the scope's fixed service root (the owner's own directories for user scope, root-owned parents for system scope), and API connection metadata is generated under the existing Skulk configuration. One profile per account is supported. Physical reboot gates remain outstanding. Setup reaches the registration only throughservice_registration.owner_layout(scope)(the layout for the account running the process) andregistered_for(layout, base)(whether the registered definition is exactly the one that startsbase), and takes the base interpreter fromservice_bootstrap.current_base().connected_scope()asksowner_layout()before it reads the connection, so a host that cannot register readsunsupportedfrom the start and notabsent. Readiness is_serves(root, snapshot): the inventory reply'sruntimemust equal{generation, manifest_sha256}of the expected snapshot, on a first setup, on an unchanged service and after a reload; a bare answer never suffices and there is no fallback for a manager that reports none.RuntimeManagertakes that identity at construction fromservice_bootstrap.started_from(root), which requiressys.prefixto be<root>/core-runtimes/<generation>/runtimeand hashes that generation's ownsnapshot.json; it never readscore-runtime.json, so a manager that has selected its successor still reports the copy it runs. The reply field is additive and present only when known;ManagedInventory.runtimeis its optional typed form. On Windows the registration is one Task Scheduler task per account, namedfoundation.foxlight.skulk.plugins.<SID>(_service_registration_windows.py, definition inWindowsServiceLayout): user scope only (registrable_scopes()), registered throughschtasks.exewith no elevation, principal the account's SID with an interactive token and ordinary rights, one trigger repeating every minute withIgnoreNew, command the basepythonw.exewith the same fixed arguments, service rootSkulk\pluginsin the account's local data folder.registered_for()reads Task Scheduler's own copy with the console code page set to UTF-8 and comparestask_fields(); a task that is switched off is not registered. An existing task is replaced only after it was read and verified as local setup's own. Stop: disable the task, createservice-stop, wait up to 180 seconds forbootstrap.lockandmanager.lockto be free, then end the task and wait 15 seconds more.service-stopstays until the next install removes it, after its task is registered; a start that finds it ends at once.runtime_artifacts.current_platform()and its standalone mirrorservice_registration.service_platform()name a Windows hostwindows-x86_64orwindows-aarch64, taken from what the interpreter was built for (sysconfig.get_platform()win-amd64orwin-arm64;platform.machine()is not used on Windows because it is empty for an ordinary account in a process with a fixed environment, such as the manager), so a Windows node that was never set up readsabsentand local setup runs there. The name is a measurement only:platform_matches()compares system and machine as before,_ReleaseFields.platformsadmitsdarwinandlinux, and a release for either is refused on a Windows host with the existing compatibility refusal. Only x86_64 has been run.
Skulk wheels and source distributions include declarative resources under
skulk/resources. Discovery prefers the imported package and retains legacy
service-copy and frozen bundle layouts. Explicit local setup with changed source
may supersede failed setup while preserving prior operations/profile and staging
before service stop. Linux registration uses a literal WorkingDirectory path;
the exact old quoted unit remains recognizable for repair. Stop verifies inactive
or failed status with no main process before proceeding. The source-tree resources symlink points
to src/skulk/resources, preserving existing tools without duplicate payloads.
Managed capability nodes may expose the optional NodePreflightProvider facet.
The generic /v1/plugins/{plugin_id}/nodes/{node_id}/preflight read returns
bounded prerequisite results and observed revision metadata independently of
child readiness. Skulk owns authorization and response bounds; the plugin owns
provider-specific checks and fresh enable/restart enforcement. Dashboard setup
checks do not grant acquisition or spending authority.
Public setup files use the optional NodeSetupProvider facet in
extensions/setup.py and the read-scoped
/v1/plugins/{plugin_id}/nodes/{node_id}/setup route. The management provider owns
initial identity generation; the read returns only bounded public text artifacts
and observed revisions. Disabled children retain this facet. The dashboard uses
explicit downloads without changing credentials or granting lifecycle/spending
authority. Private values remain in the write-only credential path.
- Installed local plugin setup:
extensions/local_setup.pybacksskulk-plugin-service setup-plugin <managed-id> -- <setup-fields>. It resolves the protected local profile and installation, requires retained release/trust history, verifies the selected complete runtime, and execs only the signed setup launcher: the archive's__setup__.pyor a signed wheel'ssetupentry underskulk.capability_runtime. The installer lock is inherited until exit; disabled selections are allowed. No provider SDK enters Skulk and no HTTP route launches this path. Plugin setup owns prompts and explicit local registration, never remote grants.
Nonbillable setup actions use the optional NodeSetupActionsProvider facet in
extensions/setup_actions.py. Installed nodes advertise setup_actions_available;
core exposes fixed form/start/observation/resume routes under /v1/plugins with
separate read/manage authorization. Actions declaring requires_approval also
require plugins:approve; resume preserves the original requirement even if the
current action changes. This permits protected setup, never paid proposal approval.
The managed adapter dispatches to the private
owner, which owns durable intent, reconciliation and background execution outside
the unary child slot. Dashboard reconnect only observes retained progress. Ordinary
forms cannot contain credential fields, and setup completion does not imply
preflight, enablement or paid approval. Public setup-file reads remain separate.
Guided release installation uses terminal_install.TerminalInstaller through
skulk-plugin-service install-plugin [MANAGED_ID]. It generates identities before
effects and composes existing typed manager requests with separate publisher trust,
download and activation consent. Feed credentials use hidden terminal input.
Resume reads retained operations; download recovery requires explicit consent,
and failed or unrelated lifecycle transitions are never replaced automatically.
No provider policy, node enablement or paid approval is added to core.
Installed plugin terminal management uses skulk-plugin-service manage-plugin
and either the archive's optional __manage__.py or the manage launcher a signed
wheel declares under skulk.capability_runtime. extensions/local_setup.py
shares verification and inherited generation ownership with setup-plugin, while
keeping entrypoints distinct. The plugin derives durable coordinates and owns its
fixed CLI verbs; core accepts no executable/module selector and adds no HTTP exec
route. Terminal commands run as the existing nonroot owner and cannot self-approve
paid effects. The independent manager remains available for owner/runtime recovery.
The dashboard's auth/operatorSession.ts implements the existing Ed25519 pairing
and rotating-token protocol for a browser on a protected gateway URL. Its access
panel reviews cluster identity, retains credentials only in module memory, serializes
refresh and injects bearer headers below RTK Query request metadata. It never replays
an API mutation after authentication failure. Session changes clear caches and plugin
drafts; explicit direct-host selection is required after a paired session ends.
Plugin grant administration refuses a presented paired bearer even on the direct
listener. Native relay inner TLS remains a separate transport, not a browser shim.
Managed owner proposal observations may include separate receipt reconciliation
(ProposalReconciliation): lifecycle state, journal read time, stale health/access
and a safe code. The provider owns exact receipt correlation; core only authorizes
read access and transports bounded metadata. Later confirmed absence never rewrites
submission uncertainty. Dashboard and terminal show the same facts without retrying
an effect or claiming inference readiness from resource state.
Managed proposal phase acknowledged records durable asynchronous controller
acceptance, before any claim of provider completion. The private owner validates
request correlation, preserves acknowledgement across restart and reconciles later
receipt state without replay. Core and dashboard transport/display this bounded
phase alongside independent cleanup observations.
- Selected but stopped plugins:
LifecycleRequest.action=selectuses the same revision, trust, compatibility and permission checks as activation but publishesRuntimeSelection.enabled=false. Terminal and dashboard clients share the operation; a later explicitactivatepermits owner startup. Local signed setup/management entrypoints can use the selected runtime before owner identity initialization. Interrupted selection journals retainverify_runtime=trueand revalidate trust/artifacts; ordinary disable preserves invalid-trust withdrawal. Selection performs no plugin state migration or paid operation.
Managed-plugin uninstall is a retained-state withdrawal through the existing
RuntimeController, using the same owner stop and selection journal as disable.
The selected lifecycle operation determines inventory's uninstalled flag, separately
from pending-operation progress. No extra supervisor or provider call is added.
Configuration, credentials, receipts and runtime generations remain available;
independent cleanup continues. A verified select or activate reinstalls explicitly.
An explicit purge (InstallationRequest(action="purge"), DELETE /v1/plugins/managed/installations/{plugin_id}, skulk-plugin-service purge-plugin,
the card's "Remove uninstalled plugin…" or the drawer's "Remove everything") is the end of that retention: an
installation that is uninstalled, or that never selected a release, leaves the
inventory and its directory goes; a live installation or one with work under way
is refused unchanged. The dashboard classes an uninstalled installation as
uninstalled even though its stopped service is never observed and so reads stale.
Dashboard presentation ownership
Ordinary Chat also pins asynchronous user and assistant writes to their originating history. Managed runtime cards retain release-installation and activation submission IDs outside the detail drawer, so dismissing or reopening it cannot erase an uncertain-operation fence.
dashboard-react/src/theme/theme.ts: Night (dark) / Noon Ridge (light); Instrument Sans and JetBrains Mono. Components consume semantic tokens without theme-name branches.dashboard-react/src/components/pages/StewardChatView.tsx: app-scopedStewardControllerProviderowns per-conversation transient drafts, generation cancellation, speech and proposals across drawer/page/virtual-model presentations. Messages use the existing Redux Chat history andskulk-chatpersistence key. Async replies target the originating conversation; changing/deleting its Steward history selection cancels generation. Drawer sends preserve ordinary Chat selection.dashboard-react/src/hooks/useModalFocus.ts: one modal owner, Tab containment, Escape dismissal and focus return.dashboard-react/src/components/layout/SettingsPanel.tsx: unsaved configuration and theme drafts survive Devices navigation; Save is the commit boundary.DevicesPanelinvokes immediate independent inventory/revocation and invitation operations. QR secrets stay inPairingSettingscomponent state.src/skulk/api/operator_auth.py: device GET/DELETE retain scoped bearer access and additionally accept the existing trusted direct-dashboard authority check with the dashboard pairing header. Invalid bearer credentials never fall back to direct authority. Relay restrictions remain in force.- Integration setup remains configuration guidance, not observed connectivity. Runtime health uses existing runtime/node/operation evidence. No device-presence or request-observation service is introduced.
Installed capability declarations
extensions/capabilities.py: boundedInstalledCapabilityRegistrationsummaries bind declared operation purpose, id/version, descriptor revision, I/O mode and runtime prerequisites. They contain no credential values or configuration.runtime_manager.installed_releaseprojects selected staged metadata; unreadable optional registration never hides installed identity. Aggregate inventory sheds optional registration before exceeding its frame budget.extensions/installed_capabilities.py:InstalledCapabilitiescombines current local manager selections with separate owner reachability and exact live contract readiness. Readiness requires the selected bundle/version/digest-compatible descriptor and current manager/child admission. A ready provisioner does not prove acquired inference capacity.GET /v1/plugins/managed/capabilitiesreads only this API host's configured manager.GET /v1/plugins/managed/{plugin_id}/capabilities/{qualified_id}?revision=<digest>reads one exact selected full descriptor, bounded to 256 KiB. Both require direct owner authority orplugins:read; neither attaches, repairs setup, enables children or invokes providers. Unknown metadata and retained uninstalled selections remain distinct from usable capacity.- Steward exposes
get_installed_capabilitiesonly through a request-bound authorized reader that checksplugins:readagain on every invocation. No-argument reads give bounded installed summaries; an exact plugin/id@version/revision selection reads its schema. Oversized model results disclose omission and retain the authorized full-detail endpoint. Ordinary general Steward access grants no installation-read permission.
Native image engine
stable_diffusion_cpp serves typed image model profiles through one resident,
headless, authenticated loopback subprocess per single-host, single-GPU instance.
Its compute lanes are metal, cuda, vulkan, and rocm; CPU-only serving is
excluded. SDXL's image.unet_structure describes nonuniform input, middle
and output module channels and first/final convolution channels. Its generic
layer count is the module sum and hidden width is the maximum module output
width; these fields do not imply text KV geometry or image splitting.
/v1/models.image.unetStructure exposes that intrinsic structure; signed
publication rejects provisional or inconsistent SDXL dimensions. Complete immutable component files are verified before load. Model
placement can schedule an InstallEngine task for an exact published package;
browsing does not acquire packages. NodeResources.installable_engine_builds
records those candidates separately from measured engine_builds.
Existing placements retain their resolved_engine_build across upgrades.
Retained immutable package descriptors preserve each build's source-specific
cache path and verified identity. Each native instance waits for its own exact
InstallEngine preparation, even when another default build is installed; the
runner prefers that exact cache over its inherited default. Preparing a retained
build does not change the default for new placements. Known pre-FLUX.3 builds
remain eligible for older families but cannot serve FLUX.3 profiles.
Explicit operator builds retain the previously accepted source/probe contract;
their measured executable/runtime identity must still match the stamped build.
Native package descriptors and build manifests additionally declare compiled
CPU helper instructions. Package discovery also matches the interpreter's
standard wheel-platform tags, rejecting older glibc, musl and older macOS before
acquisition. Package discovery refuses incompatible hosts, and
managed-binary probing checks these prerequisites before execution.
Declared engine compatibility, actual package ABI/compiled targets, implemented
runner operations and live resource fit govern placement. Exact build identity
verifies the selected executable. Empirical qualification is scoped reporting
evidence and never a hardware permission list. A source build alone does not
prove installed or ready runtime capacity.
Image downloads select every pinned file in the owning card's repository/revision
group, including a same-repository VAE. External groups retain the durable
image_component artifact role and the complete owning card; store approval
checks that exact source group. Store transfers verify declared sizes and object
identities, recover missing component files from partial caches, and exclude
unrelated quants/projectors. Direct-Hub fallback carries the same exact file
bundle, so store unavailability does not widen the download.
The runner serializes image work with bounded admission, forwards previews and
final PNG/JPEG/WebP through the existing image chunks, and cancels/deletes owned
native jobs. The native watchdog exits on owner death. SKULK_STABLE_DIFFUSION_CPP_BIN
selects a preprepared binary; package preparation obeys offline mode and
SKULK_NO_ENGINE_AUTOPROVISION. Ordered reference edits use slot-indexed
VISION_MEDIA frames and worker-local media, never replicated input bytes.
FLUX.3 Klein and Klein Base have distinct flux_3_klein and
flux_3_klein_base image profiles. Their pinned diffusion transformer,
Qwen3-VL-4B text encoder and FLUX.2 VAE use the existing native runner;
ordered edits accept up to ten references. Checkpoint cards carry their own
sampling defaults. The API forwards captions literally, including textual
bounding-box instructions, and does not silently invoke a prompt upsampler.
Model users can prepare full scene captions using any suitable language model.
MOSS Base and SFT use the moss_image profile with a pinned Qwen3.5-9B
text encoder, external tokenizer component and FLUX.2 VAE. Both expose image
generation with 50-step Euler/CFG 3 defaults and 16-pixel alignment; prompts,
including JSON layout descriptions, are forwarded literally. These checkpoints
do not advertise reference-image editing.
Native components may declare tensor_format and parameter_count to identify
serialized packing and logical weight geometry. FLUX.3 BF16 native weights load
directly. flux3_diffusers preparation verifies the complete shard index and
copies dense tensor bytes into a native-name cache. modelopt_fp8 preserves its
per-output-channel scaling and reserves conservative 16-bit fallback residency.
modelopt_nvfp4 preparation expands verified block-16 E2M1 weights and E4M3/FP32
scales to BF16; it does not provide an FP4 execution kernel. Original downloads
remain immutable. Derived caches use bounded reads/arrays, a disk-space check,
per-artifact locks, atomic receipts and output hashes checked on reuse. Placement
and worker guards budget effective precision rather than compressed download size.
NodeResources.native_image_families binds implemented families to measured
native build identities. Legacy probes inherit their recognized source's
implementations; custom backports may report a bounded model_families array in
--skulk-probe. Master placement, worker fallback and the runner apply this
implementation evidence independently of hardware qualification. Retained builds
remain eligible for families they implement, and compatible untested GPUs remain
eligible.
Qwen Image 2.1 and Turbo CUDA/Vulkan instances enable Flash Attention at load time to reduce attention memory pressure at the default 2048-square canvas. ROCm instances also enable it to avoid observed native kernel-launch failures at that canvas. SDXL Metal loads disable batched classifier-free guidance to avoid blank outputs and enable Flash Attention at the default 1024-square canvas. Native shutdown retains process ownership through a bounded 30-second graceful wait and 15-second forced reap. Its supervisor allows 50 seconds for this cleanup, including large BF16 GPU contexts; failed reaping remains a visible failure.
The native image candidate build workflow covers Metal ARM64, CUDA ARM64/x86_64,
Vulkan x86_64 and ROCm x86_64. Linux compiler images are digest-pinned; CUDA
embeds runtime/BLAS with an external driver, Vulkan bundles its loader, and the
ROCm candidate records runtime libraries plus gfx942 code objects. Builds retain
component notices and nested payload hashes and remain unqualified until exact
hardware/model, loader and lifecycle gates pass. See
packaging/skulk-stable-diffusion-cpp/README.md.
Qwen Image 2.1 Vulkan loads also select 512-pixel VAE tiles with 25% overlap. This avoids the tested device single-buffer limit at 2K and its expensive CPU decode retry. Native teardown checks for an already-reaped process before signalling its former group; the runner retains ownership until exit is confirmed.
Native image runners revalidate the exact installed package at model load when their inherited environment predates installation. This cache lookup never downloads and keeps model/engine preparation parallel while preventing a first-use runner crash. Explicit binary overrides still take precedence.
Managed native image build identities include the executable and bundled runtime file digests. Probes verify these bytes before execution and select the managed library/code-object paths rather than inherited SDK overrides. Wheel descriptors carry exact archive and expanded sizes, bounded at 3 GiB and 8 GiB respectively; installation checks staging space for both plus a 1 GiB reserve. Legacy candidate packages retain the earlier executable identity and conservative size defaults.
Metal native image instances keep parameters on their verified GPU to avoid duplicated residency in unified memory. CUDA/Vulkan/ROCm retain CPU parameter offload. Metal SDXL and Z-Image Turbo additionally use Flash Attention and 512-pixel VAE tiles with 25% overlap; SDXL uses separate guidance passes. The tested Q8 SDXL and Z-Image default workflows stayed below kernel warning pressure on a 16 GiB Apple host.
Apple hardware inventory retains the generic apple:apple-gpu class and adds
the passively observed chip class (for example apple:apple-m4) when macOS
reports it. Missing chip observations add no exact class. Native image package
eligibility and signed support claims can therefore select measured Apple
hardware without broadening qualification to every Metal device.
Native image placement requires one pipeline rank and one observed GPU; tensor sharding or ambiguous multi-device install offers are rejected before preparation. Base image downloads select every pinned primary-repository component, including its VAE/encoders, while companions in other repositories use their own pinned transactions. Dashboard native image requests own SSE responses so Stop closes the stream and cancels the underlying command rather than only aborting an unobserved non-streaming fetch.
- Exact image generation:
POST /v1/instances/{instance_id}/images/generations, JSON image parameters plusallowed_node_install_ids.ImageGeneration.target_instance_idpins master admission; terminal or missing targets fail without fallback. Both JSON/SSE carryX-Skulk-Instance-Id; the selected card supplies capability and canvas validation.
Managed vLLM first-use runtime
provisioning/vllm_runtime.py consumes three SHA-256-pinned runtime recipe wheels
(CUDA 12.9 x86_64/aarch64, ROCm 7.2.3 x86_64). They bind upstream vLLM 0.32.0,
complete hashed binary dependencies, and managed Python 3.12.13. The upstream
vLLM wheels are mirrored without modification. Runtime environments stay separate
from Skulk and model weights, keyed by the complete recipe digest.
Node facts expose vllm_installable_builds; the observed
vllm_managed_variant binds installed tags to the verified recipe even on a
mixed-vendor host. Explicit backend selection chooses the corresponding
visible GPU variant. Backend derivation marks installable tags
on demand, separately from installed backends. Existing NodeResources.engineBuilds
and onDemandBackends carry installed identities and readiness;
installableEngineBuilds separately binds recipes available for first use.
InstallEngine serializes and shares installation, holds load until completion,
publishes fresh resources, and gives every waiter a named failure on error.
Cross-process file locks, staged adoption, hash/version/GPU checks and cancellable
subprocess groups protect first use. The child runner resolves completed cache
paths independently because it may start before the worker installs the engine.
Startup only wires a completed cache, including offline restarts. Explicit
SKULK_VLLM_BIN runtimes win; offline, opt-out and management policy prevent new
downloads. install.sh --with-vllm eagerly invokes the same provisioner. Build and
exact-byte promotion live in .github/workflows/vllm-runtime-wheel.yml; source
recipes and lockfiles live in packaging/skulk-vllm-runtime/. Publication is
append-only and qualification never becomes a tested-hardware allowlist. The
runner's --kv-cache-dtype auto keeps the full-precision shared estimate; new
compressed cache modes need explicit runner and admission support. A shared
3 GiB minimum runtime reserve covers cold compilation in placement, worker
admission, context sizing and server memory allocation. Native MTP adds a
geometry/concurrency/depth workspace estimate independent of weight precision;
EngineMemorySettings.vllm_max_concurrent_requests binds node advertisement,
placement and worker admission to the same sequence cap as the runner. The
text runner disables unused encoders with --language-model-only without
shrinking model modality truth. See
the vLLM runtime guide for user setup and prerequisites.
Native MLX video engine
- Backend:
mlx_video-metal, GPU-only, single host per job. Engine build identity binds the complete owned wheel payload. - Packaging:
packaging/skulk-mlx-video,scripts/build_mlx_video_wheel.py,.github/workflows/mlx-video-wheel.yml; promotion verifies selected attested bytes without rebuilding. - Provisioning:
provisioning/mlx_video.py; locked offline dependencies, cancellable download/commands, cross-process lock, integrity checks, atomic promotion, offline reuse and restart Metal probe. Integrity hashing uses bounded chunks/digest storage and temporary files for nested ZIP seeks, preserving parent memory headroom. Only published descriptors establish installable capacity. - Facts: installed build proof and installable builds are separate. No benchmark/GPU-name allowlist; actual OS, ARM64, CPython ABI, Metal and memory requirements apply.
- Runner:
worker/runner/mlx_video/{plan,process,runner}.py; common serial dispatch, bounded JSON progress, process-group cancellation and parent-death reaping. Uses existing video references/output media/retention. - Process ownership: native rendering and media preparation share
utils/process_groups.py;waitid(..., WNOWAIT)observes exit while reserving the leader PID until TERM/KILL reaches remaining descendants. Darwin EPERM is ignored only for groups with no live member. Real cleanup failures propagate; private protocol files are removed independently of cleanup success. - Model pack: exact local Gemma 4 and projections, transformer, VAEs, upscaler, tokenizer and quantization configuration. Independent downloads and older-model fallback are refused. Native HQ uses Res2s; DFR remains unavailable without an exact supported detailing adapter.
- Admission:
shared/models/video_memory.pyderives staged working weights from the selected native pack, preserving overhead and full-artifact fallback for unknown layouts. Master and worker share the same estimate. Optionalruntime.video_memory_budget_bytesraises, never reduces, the reservation. - Request resources:
worker/runner/mlx_video/memory.pyreads bounded safetensors headers, accounts two streamed blocks/non-block weights and conservative geometry/joint-audio/input workspace, and checks current GPU-wireable memory. It supplies the ownedLTX2_VAE_DECODE_BUDGET_GBvalue only after environment sanitization and refuses an over-budget minimum conv tile before GPU load. Live host-pressure/RSS refusal and over-reservation result peaks fail the job with process-group cleanup. This is estimate/pressure admission, not a hard Metal allocation limit or hardware benchmark gate.
LTX advanced requests carry explicit source-audio, retake/extension and timed-local-prompt controls. shared/models/video_support.py filters request placement by the exact installed engine protocol without requiring hardware qualification. worker/runner/video_input.py is the standalone bounded PyAV preparation source bundled in the owned native wheel and executed by the selected Comfy interpreter; video_input_process.py owns deadline, cancellation and descendant cleanup. Normalized source audio is frozen in both sampling stages and its waveform supplies audible output. Native timeline operations bind upstream probing to fully decoded worker facts, so no host ffprobe is required. New controls remain absent on baseline JSON jobs for immutable v0.1.0 compatibility; advanced support is bound to published wheel features. Published Comfy extension features retake and extend enable source-bound temporal video/audio masks. Retake and Dev extension use one full-resolution pass; distilled extension uses two passes and restores full-resolution source latent context before refinement. Each VAE uses its own causal clock. The owned nodes restore unchanged decoded source frames and normalized PCM before lossy container encoding; they never mutate cached input tensors. The worker verifies the complete source and bounds both source and output decoded pixel volumes to 2 GiB. Exact instance-build checks and startup node-schema checks keep older sampler-only extensions from offering editing.
Model metadata projects Union preprocessing under union_guides, separate from ordinary ControlNet guides; each offer binds to its explicit request contract.
LTX Union control uses the selected union_control IC-LoRA only in the distilled base stage. VideoUnionControl separates prepared guides from native Comfy Canny, SDPose/RT-DETR and DA3 preprocessing; preprocessor weights remain selected companions. The worker fully decodes and bounds an exactly aligned control video before the graph loads it. Output dimensions use a 128-pixel grid because the half-resolution stage carries a half-size reference. The owned SkulkLTXUnionGuide validates the actual loaded adapter metadata and delegates dilation, masks, causal positions and attention entries to pinned Comfy. Guide tokens are cropped before upscaling; the original transformer performs refinement. Union capability derives from the selected LoRA companion without a redundant persisted card flag. Card truth, issued feature builds and hardware qualification remain separate; unpublished candidates and old instances add no Union execution eligibility.
Comfy timed scene prompts require an exact issued extension declaring prompt_relay. The encoder measures text columns using the placed Gemma4 tokenizer, encodes the combined global and local text once, and retains a positive-only constant through conditioning. Video text attention applies the fixed native-compatible soft Gaussian profile on actual surviving query coordinates; start tokens, global text, connector registers and appended guide rows remain free. Audio uses the complete prompt without temporal routing. Each base, spatial-refinement and temporal-refinement stage binds its own actual grid. Query chunks bound temporary bias storage to 32 MiB while retaining Comfy's original projections, all-head normalization, position handling, gating and selected attention kernel. Cloned object patches and forward-scoped context restore original methods and clear job tensors after success, failure or cancellation. Each query chunk honors Comfy's normal interrupt flag, including its BaseException cancellation path. Candidate source alone creates no installation offer or hardware qualification.
- Comfy source audio: the owned editing bridge uses a shallow audio-VAE view with
crop_input=False, preserving complete normalized PCM through the pinned wrapper's generic encoder. Shares weights and managed placement without changing the cached VAE. Causal tail tokens remain on the source encoder's clock; valid retakes cannot depend on an incidental 4096-sample crop boundary. - Native v0.2.1 decode observation: standalone
worker/runner/video_observability.py, bundled asskulk_mlx_video.telemetry; hooks actual decode/save, forwards every latent/rate/seed/keyframe, propagates errors and disables the upstream verbose-only allocator reset. Final Metal peak covers all render stages.
Model preservation host jobs
-
store/preservation_io.py: two effect slots and an isolated availability pool (up to sixteen private roots plus publisher), reused bounded probes, retained setup cancellation and descriptor leases; shutdown drains actual calls before journal release. -
store/preservation_host.py:ModelStoreServer-owned controller (normally on demand; configured mirror startup also binds it) around the existingModelStore; private built-in archive enrollment, exact plans, private Preserve/Check and worker ownership.ModelStore.preservation_lease()uses the actual download/import/eviction fence. No new store-file-listener admin routes. -
store/preservation_folders.py: explicit operator-only folder review/enrollment, pinned parent/root identity, one private leaf, public trust snapshot and retained default. Incomplete setup is unavailable to byte work; missing mounts never fall back. -
store/preservation_journal.py: owner-only SQLite WAL/FULL journal, exclusive process owner, immutable plans and request reservations, retained copy receipts, bounded control pages; restart interrupts uncertain work without replay. -
store/preservation_worker.py: known subprocess entry, pinned archive descriptor, process-local cwd, private snapshot staging with separate filesystem capacity observations (combined on a shared device), safe bounded progress and expected manifest acknowledgement before signed publication. Parent EOF exits the worker. -
api/preservation.py: operator-gated/preservation/library,/setup/device,/plans,/jobs,/jobs/{job_id}and/jobs/{job_id}/cancel. Folder setup adds/setup/folder/review,/setup/folderand/setup/default; only folder review accepts a trusted operator host path. Ordinary copy controls accept opaque handles, never key paths; stale configured owner refuses. See API guide for methods. -
This host surface supports private Preserve/Check, portable kit export and whole-closure live-store recovery. Public mirror/BitTorrent tools and native fresh-home recovery remain separate; no public capability distribution is implied.
Library recovery kits
The existing PreservationHost also owns portable kit export and whole-closure
restore. preservation_uploads.py separates bounded resumable binary ingress
from JSON controls. preservation_live.py coordinates the known byte worker’s
verified isolated home with the actual ModelStore owner; one nested generation
and one durable index commit precede receiver custom-card admission. Explicit
retry verifies an already committed exact closure; existing aliases and deletion
tombstones remain protected. preservation_provenance.py retains matching offline
registry evidence and reuses recovered original cards without rewriting signed
bytes. Installed-card discovery follows indexed nested generations, while hidden
unindexed staging remains ineligible. /preservation/kit-uploads and /kits/{job_id}
provide operator-gated byte transfer, separate from SDK envelopes. The 24-hour
active-worker watchdog kills only the owned process; EOF, cancellation and
uncertainty retain the journal’s established semantics. Public sharing and public
capability distribution remain separate component surfaces.
The normal base, model-companion and sidecar path resolvers consult the committed local recovery index before legacy directory names. They verify the indexed installed record without constructing a second store owner; hidden unindexed staging never becomes a loader candidate.
Preservation public data workers
store/preservation_sharing.py: public-only exact bundle import, HTTP mirror, native seed-only BitTorrent; no runtime-card parsing or model admission.PreservationHost: one byte queue and two distinct serving slots; explicit immutable consent/limits, owned subprocess lifecycle, restart stops sharing.SharingPolicy/SharingStatus: loopback by default; public discovery requires explicit participation; aggregate accounting only, no peer/request history.- Operator artifacts:
/preservation/torrents/{job_id}and/preservation/public-copies/{copy_id}/trust; no arbitrary host paths. - HTTP accounting reserves full response allowance; torrent accounting observes payload and may overshoot. No network-overhead or anonymity guarantee.
preservation_delivery.py adds exact public publication and receive-only invitation
workers. Publisher custody is separate from private Preserve storage. Metadata-only
plans authenticate the original source and bind all terms/notices, public identity
and distinct key. Full byte checks and durable parent intent precede atomic public
copy publication; no listener or runtime admission starts. Output parents are
pinned and checked against recorded device/inode custody.
GET /preservation/public-copies/{copy_id}/review is an operator-only,
48,000-JSON-byte all-or-nothing metadata view. PublicCopyReview binds the exact
accepted public handle, enrolled signed identity and original archive format to
every member's terms/notices, file count and declared size. Public copies bypass
private-capture bookkeeping filters. Supported PMF also authenticates the original
source profile. No weight hashing, network, conversion, trust enrollment, sharing,
deletion or byte-check timestamp update occurs. The adapter does not add public
PMF transport, infer current byte health or grant redistribution rights.
Invitations retain the original signed public manifest, candidate keys and bounded HTTP(S) hints. Offline inspection never enrolls keys or contacts a supplier. Explicitly selected fingerprints/threshold and finite policy precede receiving. Restart stops work. A specialized fresh-review resume action retains the original job/plan, staging inode and cumulative transfer allowance with permanent replay reservations; generic Start cannot consume a resume plan. Completed local objects can finish offline after rehashing. Accounting stays in private work rather than the immutable public copy. Whole-closure restore/code consent remains separate. Binary ingress purposes separate kit transfers from 8-MiB publication/invitation metadata; no weights enter SDK controls. Public reachability, independent custody, anonymity and frozen distribution remain separately qualified.
Stopped public-import, publication, receiving and sharing jobs expose an explicit temporary-work inspection
and cleanup path (preservation_work.py). The host excludes queued tasks and
owned processes, pins private directory descriptors and checks durable device/inode
custody before bounded logical-size inspection. Removal quarantines the exact
directory before symlink-safe deletion and remains retryable after a crash.
Legacy work needs its matching host-authored request. Cleanup drains despite
caller cancellation; history retirement retains jobs until their work is gone.
It retains all archives, installed models, signing keys,
kits and torrent artifacts; it never replays participation.
Comfy LTX detailing
External companion loading: graph.companion_file() binds the graph name to
runner._companion_search_roots(). Each ComfyModelSearchRoot exposes one
declared loader folder. Conventional external paths strip that folder and map
its staged subdirectory; flat/nested external paths retain their full name and
map the staged repository root. Signed paths and revisions remain unchanged;
same-repository bundle files retain the standard folder contract. Missing or
wrong-revision files are refused before server startup. YAML paths are quoted.
LTX-2.5 Comfy DFR uses the selected pixel-spatial IC-LoRA with generated
keyframe carry between base and spatial refinement. An explicit optional temporal
x2 pass requires its pinned latent upscaler, doubles frame density and conditioning
FPS together, and freezes the existing audio. Request admission checks selected
companions and modes independently of hardware qualification. Image-conditioned
DFR retains the stock-node path. Text-only DFR requires a placed issued extension
advertising dfr; unknown/base-only builds are refused before dispatch. The owned
SkulkLTXAddGeneratedKeyframes bridge supplies a compact float32 five-dimensional
sampling mask after upsampling removes it, preserves existing image/guide masks,
and delegates token/conditioning creation to the pinned stock node. If anchors
occupy every default detailing candidate, it selects one interior pixel in the
largest free gap (earliest on ties); a fully occupied canvas is refused. Samples
and metadata remain intact, and input masks are cloned. Schema readiness and
archive-member checks require the bridge for a build advertising that feature.
Candidate source alone creates no issued build or installation offer.
Comfy extension build binding
provisioning/comfy_extension.py: issued wheel descriptors retain Comfy/LTX source pins; immutable archive/member hashes, interpreter binding, cancellable lock, atomic install, offline reuse and actual GPU/float64 probe.NodeFacts.comfy_extension_installable_buildsandcomfy_extension_installed_buildsseparate an upgrade offer from an installed base;NodeResources.installable_engine_buildscarries the former. Installed backend tags remain installed during an extension upgrade.- New LTX placements bind
comfy@<source>/torch@<version>/extension@sha256:<payload>on both placement paths. Existing stamped instances retain their build; base-only families do not acquire the LTX wheel. InstallEnginejobs separate backend/build identities. Exact extension preparation precedesLoadModeleven when the base engine is installed. Preview and task download sizes distinguish the small wheel from a missing base runtime.- Comfy launcher: verified wheel path, isolated interpreter, no bytecode, sole trusted custom search root plus fixed folder whitelist; all unrelated custom/API nodes remain disabled. Node-schema failure tears down the child before readiness.
comfy-ltx-wheel.ymlbuilds candidate bytes twice, checks types and pinned solver numerics, and attests the artifact. Explicit promotion verifies the successful source run and attestation and publishes those bytes without rebuilding. Only issued, owned-URL-verified descriptors create offers.- Build capability, family graph implementation, selected artifact completeness and empirical qualification remain separate. CPU tensors in numerical checks are not CPU model serving.
Comfy Motion Track media
Motion Track is a distinct single-stage LTX workflow. shared/types/video_motion.py
validates bounded version-one trajectory media and strength-only task controls.
Coordinates use application/json data references on the existing verified
reference-media plane; replicated state and events contain only media metadata.
Both API and worker check the complete requested timeline. The exact selected
adapter and issued engine feature are required independently of qualification.
The managed wheel draws the pinned BGR trail format one high-resolution frame
at a time, with cancellation between frames and a bounded retained guide. The
full-resolution base applies its opening image and half-grid IC-LoRA guide, then
crops guide tokens before ordinary tiled decoding; it has no spatial refiner.
Existing Union/H3 and retained older engine builds keep their own contracts.
Motion Track admission resolves canvas defaults before dispatch, independently of opening-image delivery. The Core and independent wheel retain byte-identical pure geometry policy, checked by the package tests. Retained guide pixels and transient trained-resolution raster/overlap/resize workspace have separate bounds. Single-stage offers publish their own frame mode and eight-step defaults, and do not require an unused spatial upscaler.
Masked inpainting uses strict VideoInpainting source placement, distinct from
temporal editing. Source dimensions belong to decoded worker facts; requests
carry only nonnegative offsets on an explicit bounded canvas. Intrinsic pack
support derives from the named inpaint LoRA without a persisted duplicate flag.
Capability projection and placement require an exact issued inpaint engine
feature; a candidate alone supplies no execution authority. Hardware qualification
remains separate from this code compatibility check.
Native runners refuse this unavailable workflow before reading weights, and
Comfy planning repeats the issued-build guard before constructing a graph.
Inpainting preflight uses the selected interpreter's bounded media helper to measure complete source/mask geometry and verify their native frame clock. Still masks alone broadcast; video masks are complete, silent timelines. The worker checks offsets and a combined 16-GiB cached pixel/audio/latent plus framewise pyramid reservation before Comfy constructs full image batches. This bound is separate from model weights and sampling memory, with no hardware allowlist. Legacy helper requests retain their exact reply shape; only inpainting reports new private measured dimensions.
The issued extension supplies strict source placement, area-mask preparation, framewise native Laplacian blending, actual factor-one adapter metadata checks, and frozen causal reference audio. The eight-interval base appends its guide, crops it before tiled decode and blends at half resolution. Lanczos pixels are re-encoded for the two-interval Euler refiner, which shares the LoRA and frozen audio but does not append another source guide. Both stage contexts use the native SDR green cue. A full-canvas opening uses JPEG18/strength0.7 at base and uncompressed strength1 at refinement. Normal output, progress and cancellation lifecycles apply; startup verifies all advertised node output contracts.
Native preservation jobs write draft PMF 0.1 via store/preservation_pmf.py.
Metadata, full-byte verification and restored evidence dispatch on explicit
signing domains; existing v1 copies/kits remain readable. The optional source
profile retains the exact original signed capture and cards. Both source and
PMF signatures must satisfy enrolled archive trust; registry proof and code
consent remain independent. Live publication rechecks the retained PMF/source
projection. Public publication explicitly converts a private PMF to its original
v1 selection in private staging, then applies the existing terms/sanitization and
separate publisher signature. This starts no serving. PMF kit v2 remains usable
through standalone tools without Core; generic profiles do not imply Skulk
runtime support. Automatic Library restore currently supports the lossless
preservation profile signed by the enrolled source keys.
Preservation's I2P HTTP pilot uses the same known metadata/byte worker and durable
journal. I2PSourcePolicy binds an operator-selected numeric loopback proxy and
I2P-only metadata locators to the original source identity; it stays private and
is persisted before membership. Every protected job rechecks that exact policy
and grants no direct/peer fallback. Exact receiving plans retain the proxy and
finite byte/deadline controls across explicit resume. Network locations are
unsigned hints; original cards, envelopes, TUF/model/registry/code authorities and
complete companions stay unchanged. Installing/opening Core starts no I2P router
or sharing. External proxy software remains operator-trusted; schema availability
and source integration are not anonymity, full UI delivery or broad qualification.
Core also owns followed source discovery through store/discovery_host.py and
api/discovery.py. Stock TUF-authenticated listings, source-root history and
last-good evidence stay in the preservation owner's protected local cache.
Search is local, off the event loop, and does not expose queries or inventory to
suppliers. The typed metadata-job table shares the existing exclusive journal
owner, while retaining a separate client namespace and four-slot metadata queue.
store/discovery_worker.py runs through the known source/frozen preservation
entry, with no archive/signing-key placeholders, model-store mutation or serving.
The parent retains serialization through actual worker stop, limits output and
deadline, and drains local IO before releasing journal ownership. Parent EOF
ends the child; restart records interruption without network replay.
DiscoveryHost._run returns an immutable pending outcome after its owned cleanup
scope. _execute releases the source queue, then synchronously records the final
receipt without an intervening await. Thus terminal observation permits immediate
source withdrawal; failed cleanup cannot leave a successful terminal receipt.
First-contact source-file trust authorizes discovery only. Selecting exact source/entry/manifest and explicitly accepting that source's model-reference keys can create a validated metadata-only invitation upload. The ordinary receiving and Restore paths still own weight verification, complete companions, original cards/proofs, registry assurance and code consent. Metadata permissions do not become model-supplier/download grants. Source listings and private queries are not replicated on cluster topics or treated as runtime model cards. Standalone source following/cache interchange/search remain usable without Skulk.
Optional preservation peer owner
store/peer_install_host.py/peer_install_contracts.py: separately consented, exact-plan native acquisition, bounded permanent replay receipts and the shared native lifetime gate. Restart interrupts without replay; client closure retains the job. No API-selected paths, download origins, hashes or executables.store/peer_install_worker.py: known/frozen acquisition family, fixed public installer pins, private atomic generations and immediate exit on parent EOF. Parent verifies actual managed bytes; downloaded software/scripts never run during acquisition. Setup changes neither peer grants nor model trust.store/peer_host.py: explicit local setup, qualified installed Kubo detection, serialized finite receiving leases and actual process-group drain. Retain an unreapedPopensession leader through descendant signals using the shared process-group helper; then reap it.store/peer_worker.py: known/frozen native-worker request; parent EOF cancels and drains Kubo. No API-selected executable, fabric listener or daemon adoption.store/preservation_references.py: strict HTTP/peer portable reference dispatch, independent exact-copy key acceptance and unchanged registry/code authority.api/discovery.py: operator-gated offline peer settings/status and explicit peer source/model-metadata jobs. Receive/Restore retain the existing owner, journal, filesystem publication fence, budget and companion/provenance checks.store/preservation_journal.py: atomically reserve each explicit peer resume with a separate reviewed connection binding. Original execution plan, signed inputs, private-address scope, stage and cumulative allowance stay fixed.- No implicit serving, provider advertisement, HTTP fallback, network replay on restart, mandatory Foxlight service or anonymity guarantee. Native cache/wire overhead remains separate from exported object-byte accounting.
Portable handoff sharing
peer_share: fresh job-owned mirror profile underPeerHost's existing native gate;PeerWorkerRequestseparately records public participation and finite native-wire threshold. Its process group remains owned through drain.preservation_sharing.serve_public_peer: verifies/pins a complete public closure under that independently monitored lease, writes one bounded.foxhandoff, and reports only its SHA-256 plus aggregate wire observations. The byte worker does not own or certify native shutdown./preservation/public-copies/{copy_id}/handoff: HTTP wrapper or exact retained peer-job output, hash/signature/selection checked offline. No arbitrary paths, model/registry/code grants or reachability claim.preservation_references/DiscoveryHost: unwrap unchanged signed references; expose unsigned contacts as drafts, preserve inner source identities and TUF floors, and leave local network/private scope independently selected.- Terminal stop follows actual native drain. Restart never replays serving. Native job cache survives stop and uses explicit existing temporary cleanup; source copies and handoff artifacts remain. No automatic eviction/deletion.
The retained receiving invitation preview projects its original local
receiving policy, including the exact numeric I2P proxy and limits. This is
read-only control metadata, omitted from fresh invitation inspection; it does
not enter signed portable evidence or renew the explicit Resume grant.
Persistent public mirror owner
store/mirror_contracts.py: strict separateMirrorRequest,MirrorJob,MirrorPageand bounded job/model pages. Opaque public-copy/manifest handles; no operator paths, executable selection or signer enrollment. Existing finite job enums/pages and SDK contracts stay unchanged.store/preservation_journal.py: separatemirror_jobstable under the same exclusive WAL/FULL owner. Immutable owner/operation reservation, 4,096 retained receipts, two active slots, cancellation/terminal fences and restart interruption. Original decisions never replay or regain historical live ports.store/mirror_host.py: one managed mirror, qualified native runtime selection, pinned accepted public-copy lease, explicit resource/transports and per-member terms, durable jobs, live activity, Stop and exact pin/block/prune controls. Bounded metadata probes share a state snapshot then project each requested cursor, rather than reusing a different page's response. Exact selection lookup and complete, all-member review survive original import loss and do not read weights.prepare_kitmay coexist with the controller within two active jobs; permanent replay never regenerates an artifact.recoveris exclusive stopped-controller offline completion verification over standalone 0.19. Exact model/policy and every actual object verify before promotion; original local intents retain wrapper bytes. Host restart intent clears before work, while block/pin/accounting and recipient/registry trust stay separate. Lost clients observe the original durable job; restart never retries a recovery or deletes partial data. Sovereign sharing decisions:intake(coreIntakePolicy, fenced, refused beside a controller),follow_withdrawals(operator-only configuration, off by default) and modelacknowledge/withhold/release. Nullable upload caps; announcements map to coreAnnouncePolicyonly with a recorded disclosure.offer_public_copy(called when a publish/receive/import completes) runs stop, covered retain (admitted_by: intake) and resume under the unchanged grant, abortable by an operator Stop and never replayed after restart.check_addressis a bounded best-effort fetch of the owner's own address.store/preservation_terms.py: receive-planmember_termsand the pinned core'sterms_review; exactaccepted_termsare checked and a coreTermsAcceptanceis recorded in the reservation transaction before download.store/mirror_kits.py: enrolled private preparation directories, durable intent/seal/removal receipts and fixed-name artifacts. Completed digest and descriptor fingerprint gate download; unexpected entries or changed identities refuse deletion. No startup cleanup or automatic artifact replacement.api/mirror_kits.py: operator-gated prepared GET/HEAD and single-range streaming with strong digest ETag, unchanged-file checks and bounded reads. Active leases drain before storage closes; no full-byte hash on GET and no recipient trust grant. Explicit confirmed removal affects only the stopped preparation.store/mirror_worker.py: knownpreservation-mirrorsource/frozen family; standalone retention/controller/grant/deletion primitives and original signed evidence. Expected policy is rechecked inside the controller's service lock. Parent EOF cooperatively drains; source directory replacement cannot change its inherited accepted descriptor. No runtime card parser participates. The fixed direct native adapter keeps daemons/commands in the outer owner's group; source/frozen execution needs no nested Python module launch.store/mirror_process.py: bounded JSON pipe, unreaped leader ownership, cooperative stop then process-group drain on a bounded per-worker control executor, independent of saturated filesystem effect slots. Requests/descriptors and terminal receipts remain owned until actual effects finish; no arbitrary process adoption. Group-member confirmation precedes leader reap; a real drain timeout retains ownership. Successful Stop retry reconciles retained task/request ownership before freeing the role. Failed close tasks can be retried after recovery; successful close is idempotent. The outer preservation host begins finite-job, mirror, discovery and native-peer withdrawal concurrently; all drain outcomes precede storage/journal release. Complete host close is shielded through release and retryable after failure. Every mirror-worker withdrawal starts before awaiting any drain; a preparation admitted before its controller cannot prevent that controller from stopping. Failures propagate after other withdrawals finish and retain their owner for retry. Normal exit/Stop/close share drained-owner cleanup, including completed failed workers; shutdown-only retry preserves approved standing intent.store/peer_host.py: selected qualified runtime and exact reviewed contacts for independent mirror custody; receive-only Core peer sessions are not converted into publishers. Runtime bytes are pinned/rechecked in mirror policy.api/mirrors.py: same operator boundary as private Library; dedicated/preservation/mirrorand/mirror/jobscontrols. No store-file-listener admin endpoints, private paths/key material, automatic source/model trust or serving.ModelStoreServer.start(): sole startup hook. Requires original running intent plus Core-approved exact unexpired standing grant; no resume on GET/constructor, grant alone or finite run. Core close retains only prior approved intent. User Stop clears it before signalling and persists pause after drain; unavailable disks do not erase Core's Stop fence. No automatic retained-model deletion. Controller drain precedes waits for unrelated cancelled model cleanup.Node.run(): the outer store lifetime closes the current server after node tasks exit, with shielded drain under signal and parent-scope cancellation. Event-loop teardown cannot substitute for this owner shutdown.
Direct public PMF transport, public replica health and native desktop distribution are not implied by these controls. Standalone core use remains independent of Skulk; existing PMF kit/recovery and model/registry/code authority stay separate.
Managed declaration metadata bounds
extensions/managed_limits.py separates rich declaration metadata from ordinary
calls: one managed application may declare sixteen capabilities, descriptions
and exact selected contract reads use 512 KiB response envelopes, and an
individual selected descriptor is bounded to 256 KiB. Signed runtime metadata
uses a separate 512 KiB bound consistently through download, review, staging,
recovery and installed inventory. Catalog and registration summaries accept
sixteen declared operations. Ordinary invocation frames, settings, credentials,
manager requests and binary media retain their own existing limits.
One owner may report at most sixteen application nodes and 128 total capability contracts, within the discovery byte bound. Refresh refuses an oversized aggregate before reporting availability and withdraws readiness until a valid inventory returns. Discovery, dynamic dispatch and host callbacks share this aggregate bound, preventing a ready owner whose contracts cannot be dispatched.
Expanded SDK manifests require a compatible Skulk 2.0.3 reader. Deploy readers before publishing larger signed records; declared contracts and successful metadata verification do not establish live provider readiness or authorize execution. Legacy descriptor revisions and signed identities remain unchanged.
Catalog protocol 3 carries the expanded identifier count at the separate
catalog/catalog-v3.json address. Protocols 1 and 2 keep their original eight
identifiers, and the publisher maintains a signed legacy catalog/catalog.json
projection. Version filtering follows whole-catalog validation, so a release's
version requirement cannot protect an older catalog parser. Updated built-in
Store readers prefer v3 and fall back only on an initial 404 before accepting
it. Invalid signatures, malformed data and other failures never downgrade.
Acceptance atomically switches the source and retains both histories; a v3
revision below the accepted legacy revision is refused. Restart, a failed
retained-document write or returning from a private catalog cannot restore
legacy fallback. Introduce both catalogs using existing releases, deploy the
reader, then publish expanded releases.
Native ACE music metadata
- ROCm request admission returns the previous request's unused Torch allocator blocks after device synchronization; live weights and fixed memory limits are preserved. Native readiness/inference failures drain custody, then retain up to 4 KiB of escaped private stderr in local exception traceback notes. Shared startup state and public job errors remain path-free. Device-allocation refusals include measured/allowed byte counts; they never credit allocations back into free capacity.
ModelTask.MusicEditingaccompaniesTextToMusiconly on native ACE base cards.MusicCardConfig.native: variantbase, 48 kHz stereo, closed unique editing modes/part classes, pinned text-encoder/tokenizer and autoencoder bundles.- Primary bundle: config, safetensors, silence latent; complete three-component storage accounting, immutable objects and loader roots; no repository Python.
trust_remote_code=false; reviewed implementation belongs to the runtime.platform_compatible_backends(card_has_native_music_profile=True)excludes incompatible engines and selects only explicit native ACE CPU/Metal/CUDA/ROCm lanes. The master additionally requires current fixed payload/probe and full phase admission; worker bootstrap also refuses native startup explicitly instead of falling back to MLX./v1/models.music.native: intrinsic variant/modes/classes/sample rate/channels; does not assert a native runner or HTTP editing endpoint exists.- Absent native metadata is excluded from existing card/public serialization.
music.native.tensor_layouts: optional all-three-role exact prefix length/SHA and complete unique dtype/tensor/logical-element groups. Header plus scalar storage equals each selected safetensors object's size; no runtime memory or tested-hardware permissions.native_music_layout.pyperforms bounded strict projection; omitted defaults preserve old serialized identities.ModelCard.native_music_artifact_sources()/native_music_files_for_source(): exact sorted source groups across all three roles; overlapping role paths fail. Shared external sources use one requiredmusic_componenttransfer. Same-source primary components join the base selection; loader roots stay on the owner.- Store base completion waits for every source. Direct/store staging, installed records and offline completeness bind all selected files and immutable pins. Preservation maps the entire closure with no repository Python; recovery may add only the exact receiver-owned capture notice. Byte availability is distinct from engine readiness; native placement/startup guards remain.
- External native alias:
skulk-native/plus base32 SHA-256 of repository, immutable revision and grouped transfer bundle ID. This exact key is used in active-task deduplication, store/staging, peer validation and preservation. Primary transfer directory identity uses the complete native source bundle. music_componentcross-owner reuse requires equal complete source selections; it does not rewrite retained owner policy. Original object pins are checked before linking reusable data into independently deletable generations. Legacy aliases are exact-selection fallbacks, subject to deletion tombstones.- Coordinator native lookup and completion revalidation use worker threads for
filesystem reads. A cached completion cannot hide a lost required source.
Replacement failure/cancellation retains the previous registered generation.
Exact bundles take precedence over legacy
original/*andmetal/*exclusions. - Completed native store-cache admission verifies hashes and original pins off loop under the publication fence; in-progress deduplication stays selection-only. A historical native source owner's deletion does not remove independent data custody, including index recovery and peer reconciliation. Source-alias deletion remains authoritative; non-native companion deletion semantics are preserved. Cache verification waits for the publication fence and hashes outside the short download-admission lock, then rechecks the selected status before returning. Unrelated admission and active-transfer cancellation remain available. Cancelled verification drains its file thread before releasing that fence. Pinned existing files are checked against their original object identity during download reuse: online retries replace corrupt bytes; offline reuse refuses them. Capacity admission verifies selected immutable pins before treating a same-size target as complete. Zero-byte members require an existing regular file before hash verification; absent empty members are created by the normal downloader. HTTP metadata must explicitly declare a nonnegative length; zero-byte Git/SHA objects are valid, while missing or invalid size headers remain rejected. Repairs cannot credit blocks retained by other hardlinks. Cancelled capacity checks drain before the transfer fence is released. Verified shared native cache reuse restores missing adjacent installed-card records from the original indexed owner, including companions reached through a cached base.
Native music edit contracts and custody
- Native editing/separation failure ordering:
RunnerSupervisorretains the publicErrorChunkreason from the FIFO runner pipe for the active task. Its final failed status becomes one existingTaskFailedwith at most 1,024 diagnostic characters. Indexed control can settle correctly before DATA; cancellation, timeout and failures without a diagnostic keep existing handling. shared/types/music_edits.py: task-discriminatedMusicEditRequestwith separate Add a part/Repaint/Continue controls, measured source-clock ranges, integer floor/ceil conversion to 48 kHz, immutable once-resolved seed, card modes/part/lyrics/duration validation, and path-freeMusicEditingOutput.MusicEditingcommand/task: source identity/geometry and bounded chunk count, model, caption, lyrics, fixed seed and native extent; no audio or local paths.- Master native admission: complete one-host rank-zero shard, idle loaded runner, exact current backend/build match; generation/edit pending reservations remain occupied until indexed State echoes. Mere installability is insufficient.
api/media_job_storage.py::PrivateMediaJobFile: shared separation/edit file lifetime lock, bounded private reads and durable replacement. Uncertain writes fence further reads/writes until reopening.api/music_edit_jobs.py: four active/64 retained records, exact source/seed/ operation/result correlation, render + synced WAV + drained return ACK gate, restart interruption without replay; completed unexpired history stays retained.api/music_edit_media.py: private shared WAV assembler, 64 MiB/result, 24-hour retention, independent PCM24/stereo/48 kHz encoded-fact/peak checks, completed-only adoption, no implicit eviction, failed-delete capacity retention.worker/audio_source_types.py: read-only source task/params protocols forSeparationSourceStoreandSeparationSourceCustody; strict actual tasks remain in State. Four-original admission and inherited native reader fences stay shared. Inject result cleanup for ACE's exact owned layout.api/music_edit_api.py: six/v1/music/editsroutes before dynamic music IDs, existing authentication plus operator inference scope, 256 KiB closed JSON multipart metadata/64 MiB source/180-second upload bounds, persisted seed, 45-second placement/two-hour placed-job/five-minute post-render return deadlines, session interruption without replay. Expiry cancels the accepted task and drains partial copies without resubmission.NATIVE_MUSIC_RENDER_SECONDSkeeps the API, configured native cooperative timeout and runner hard render deadline at the same finite two-hour ceiling.audio_uploads.py/audio_source_delivery.py: shared native audio multipart closure and joined bounded addressed original delivery.AudioInputReceivershares the handshake with separate concrete task selectors and payload roles.MusicEditingChunk: DATA metadata only;VISION_MEDIA.music_edit_source/OUTPUT_MEDIA.music_edit: directed binary original/result transfer. API queue, failure/cancellation/session paths include edits. Reverse controls send outside the actor lock; source/control drains retain admission. Router subscription filters prevent same-node ACK echo deadlocks while preserving legacy traffic. Cancellation submission precedes stream finalization. Uncertain index writes fence reads, abort accepted native work and retire only the edit sweeper; requests return actionable 503 responses while unrelated host tasks continue. A separate bounded cleanup actor owns pending source/result removal and keeps admission until both stores drain, independent of terminal/deleted job state. It performs no index reads and can retry after a job-storage fence. Completed WAVs survive original-only cleanup; incomplete delete keeps metadata with 503. Known orphan media keeps its byte promise after registry eviction, and failed startup orphan purge cannot advertise a fresh uncharged media owner as ready.- Execution activation: resident/worker, live native placement and Studio edits still require complete native/installed acceptance.
Native ACE package/process definitions
packaging/skulk-ace-step/: independently installed Python 3.12 native family, with exact three-target CPU archive catalogs and pinned standalone interpreters.build_ace_step.py: clean committed sources, closed selected library/adapter inventories, explicit namespace override, runtime-owned model-code identities, streamed/rehashed objects, deterministic regular ZIP members and SHA descriptors. No model weights, publication or machine paths enter the sealed object.- Native ACE workflow: default current-source checks remain separate from
explicit
build-inventoryreproduction ofACE_STEP_ADAPTER_REVISIONand all six exact package pins. Adapter Git revision participates in payload identity. A separatepublish-inventoryrequires initiative-merged source, successful same-workflow/repository/source candidate, complete size/SHA-256 selection and hosted attestations, then uses the shared append-only R2 index publisher without rebuilding.verify_ace_step_promotion.pyrejects missing, extra, duplicate, linked or changed archives before uploads. Publication, verified device readiness and installed model/music acceptance stay distinct. provisioning/demucs_package.py: shared verification/bootstrap for exactly the built-in Demucs and ACE layouts. Source repository, namespace and metadata root must agree; the existing Demucs cache also enforces its own family ownership.- Native install guardians and resident Demucs/ACE process environments enforce
PYTHONDONTWRITEBYTECODE=1in addition to the explicit interpreter's-I -B. Console helpers that re-exec plain Python inherit bytecode suppression; sealed interpreter/import verification continues rejecting modified or injected files. shared/types/native_music.py: canonical strict private request/component/ precision/result/control contracts; copied into the native package as bytes. Frames are bounded to 256 KiB and carry no audio or public local-file choices.- Private CLI
--probe <lane>is mutually exclusive with--serve <config>; both require a dedicated session and actual parent PID.NativeMusicLibraryProbeis a weights-free payload/device/precision observation, not loaded-model readiness. CPU/ROCm use FP32, MPS additionally probes its FP16 VAE policy, CUDA uses native BF16 from SM8 and FP16 before it, independent of BF16 emulation. Explicit library/device mismatches fail without model acquisition. - Preparation:
provisioning/ace_step_runtime.py/ace_step_manager.pybind complete/payload pins, full interpreter/import-byte verification and an actual weights-free device/precision probe. Probe uses the install guardian's session, not a nested resident CLI. Verified observations alone enter manager resources. - Shared ownership:
demucs_runtime.py::SealedRuntimeCacheandnative_runtime_manager.py; short observation publication, serialized cache reservation, queue-inclusive deadlines, cancellation withdrawal, retained drain retry and immutable published generations. Demucs CPU/Metal semantics remain. - Native ACE/separator preparation maps
DemucsStorageErrorto a path-free public free-disk-space/remedy message. Failed ordered completion exposes no ready resources; arbitrary exception details remain in worker logs. Fresh request identities can retry on the same owner after capacity recovers. - Trusted storage profiles (package/installed GiB): CPU 1/4, CUDA 4/8, ROCm 3/10. GPU archive member limit 768 MiB; expanded member limit 1 GiB. Installed totals include nested archives plus expanded imports. Manifest cannot expand limits. Raw Linux ROCm target states no invented GPU-library libc floor; known Python 2.28 ABI still applies. Closed GPU inventories cover CUDA x86_64/ARM64 and ROCm x86_64. The pure ROCm metapackage records source/tool/epoch/target pins and its producer rebuilds twice against the exact expected binary and metadata digests. Its build-tool pin is independent of runtime Setuptools. Only the fixed ROCm producer traverses declared extras; every active child is verified against selected exact wheels. CPU/CUDA keep their refusal policy. Six native CI jobs build/compare/install/verify the three CPU, two CUDA and one ROCm profiles with matching explicit variant selection. Hosted GPU-package jobs run CPU boundary checks, not accelerator/model qualification. Package/model/loader/GPU qualification, publication and activation remain distinct.
- Pre-write ownership:
worker/runner/ace_step/workspace.pyjournals workspace, requests and loader inodes before spawn under an inheritable service fence. Native configuration carries all three identities; new loading requires an emptyworkspace/loader. Each request additionally supplies its Core-created, independently journaled empty result inode beneathworkspace/requests. Recover loader copies/caches only after actual group drain or exclusive fence acquisition. Validate all names/modes/inodes and bounds before deletion; preserve foreign entries, replacements, links and failed cleanup for retry. Loader recovery never walks or removes retained request output. Additional loader disk budget: fourteen exact selected files, three reviewed source copies bounded at 2 MiB each, 256 MiB dynamic cache, 4,096 total entries and cache depth 12. These are disk bounds, not peak-memory estimates. - Independent result verification:
ace_step/process.pychecks bounded private metadata/WAV files, request/model/payload/seed/execution, measured PCM24 digest/geometry/peak, unchanged original and complete aligned FLOAT conditioning. No truncation/repair; gain remains transformation provenance. Component verification does not itself activate Worker placement/execution. - Core resident supervisor:
ace_step/resident.py::ResidentMusictakes the prepared workspace, inherits service/source-reader fences into one private session, checks exact loaded model/payload/component readiness, serializes contiguous correlated requests and bounds frames to 256 KiB. Nonblocking control writes obey an absolute deadline; progress is coalesced, terminal capacity is separate and diagnostic stderr stays bounded/private. Recheck actual process/resource state during calls and idle liveness. Drain the complete native group and join pipe readers before reclaiming active partial output or loader data; retain ownership after failed drain/cleanup. Completed output/receipts survive close/restart and remain independent of model readiness or native completion. Worker/model/memory activation remains. - Independent native custody guardian: fork before Torch/thread startup, detach from the model group, retain inherited service/source locks and drain actual live group members after Core or native-leader loss. An unreaped anchor pins the original numeric group identity. Core waits for private drain-pipe EOF before recovery; timeout retains the pipe, locks and loading for close retry, including a retry after the original leader was already reaped.
shared/models/native_music_runtime.py: pure complete three-role data identity excluding aliases/metadata/runtime/hardware; actual library-probed component device/dtype policy, payload, two threads and duration ceiling. Floating state projection is not peak memory; unknown buffer/packed semantics remain unknown.ace_step/artifacts.py: exact source-root map; bounded complete SHA-256/Git-blob hashing, no-follow relative ancestors/final files, regular-file/stat checks, cancellation/deadline checkpoints, then independent bounded tensor projection. Preserve ordinary store hard links; do not copy or import native dependencies.ace_step/model.py::NativeMusicModel: complete single-host rank-zero binding;BaseShardMetadata.native_music_policycompared against prepared build/probe, actual complete objects/headers and loaded model receipt. One actor serializes inspection/pre-write result custody/inference; close stops and drains it so no late child can escape shutdown. Verified headers may refine optional unknown geometry without changing admission; declared facts still must match. A short readiness handover joins idle polling before submission; active polls return cached observations without competing with the resident request actor. Closed generation/edit translation preserves fixed seed, creator text, measured source and exact native frame coordinates. Independent completed output survives close; failed unsubmitted cleanup retains exact parent/child retry ownership, fences admission and preserves replacement directories/content. Failed pre-write preparation reclaims only its own empty result/receipt. This is not Worker activation or shared peak-memory admission. Retain empty-result fallback custody until successful resident completion; early resident refusal cannot orphan a prepared directory/receipt. Drain the resident before reclaiming that fallback.ace_step/runner.py::Runner: shared bounded dispatcher, one active generation or edit, four admitted waiters, actual load/warmup/liveness readiness. Cancel or failure drains the retired model before a fresh unloaded lifetime for the same placement; failed replacement withdraws readiness after task terminal. Verify completion task/operation/seed/model/payload correlation; emit typed metadata only and preserve independently owned completed WAVs on close. Worker placement does not yet supply its private context; no resource advertisement or support claim is granted.- Native resident: complete data/code verification, explicit runtime math probe, observed per-component loaded precision, exact canonical source-tensor equality, one active request, contiguous sequence/correlation checks, 0600 PCM24/result files and fsynced completion. Continue repaints only the zero-padded tail.
- Edit geometry: zero-tail conditioning alignment to the pinned 1,920-sample
codec grid, with
conditioning_padding_framesseparate from Continue's requested extension; original samples and edit ranges remain unchanged. Validate the entire decoder tensor before removing only the exact aligned tail or 128-latent/245,760-sample minimum. Recordpadding_frames_removed, preserve the requested frame count, reject all other mismatches. - Source encoding: after initialization and before readiness, a typed
per-handler
tiled_encodebinding caps windows at 720,000 samples / 15s (480,000 samples / 10s for explicit ROCm policy) with the pinned 96,000-sample / 2s overlap-discard default. Preserve shorter explicit chunks, codec computation and full context clock. Do not select workspace from total device capacity or patch a global upstream class. The smaller ROCm window preserves margin for repeated maximum-duration edits without relaxing the admitted device ceiling. The same handler's typedtiled_decodebinding caps windows at 256 latent frames / 10.24s. Re-evaluate native automatic sizing per decode, preserving low-memory/failed-query 128-frame choices and shorter explicit windows, native overlap/discard, offload selection, CPU fallback and stricter MPS clamping. Global free GPU memory cannot enlarge this instance's workspace. The complete output clock and live guard stay unchanged; exact-payload memory/fidelity qualification remains required. - ROCm encoding cache: before readiness, register a public
forward_pre_hookon the one loaded VAE encoder. Before each original window, synchronize device zero and release only unused Torch allocations. Keep request-entry reclamation as well: it cannot release blocks produced later in the request. Preserve input tensors, parameters, codec math, windows, overlap and fixed allocation ceilings. Failure propagates to normal resident retirement. CPU/CUDA/Metal handlers do not install this per-instance hook. Exact sealed package repetition and maximum-duration acceptance remain separate gates. - Package revisions: the native ACE reader pins ROCm build5 and retains all
five CPU/Metal/CUDA build3 objects and their original producer revision.
The ROCm producer uses build tag
5and matchingBuild: 5WHEEL metadata for request-boundary and per-window cache release and 10-second encoding. The reader accepts only the original untagged and build1 through build5 forms; fixed inventory hashes select bytes independently. A producer revision does not publish or qualify a package.ace_step_package_revisionresolves provenance only for an exact fixed package record; ROCm can advance while the five CPU/Metal/CUDA objects and their producer revision stay intact. Inventory CI selects each profile's producer separately and verifies its descriptor against that same record. Workflow consumes descriptor filenames and runs on inventory updates. Existing objects must never be overwritten. - Native failure: permanent model retirement, bounded terminal frame, dedicated group kill even after BrokenPipe, parent-death guardian, cleanup only after owner drain. Module observations do not establish every operator's precision; native decode can temporarily use CPU and restore original placement.
producer_tests/: normal Core/build Python 3.13 checks.runtime_checks/: explicit native Python 3.12 checks via installed-onlyverify_runtime.py. Three-target CI compares independent builds and performs fresh offline execution; it does not load music models, grant model qualification or register Core capacity.- Native placement/startup guards remain until worker integration exists. Model byte custody follows the complete source-group lifecycle above. No editing route is introduced by these package/process definitions.
ace_step/context.py::NativeMusicRunnerContext: prepared private spawn data, inherited reader custody and required live resource guard. Resolve complete installed source groups only at LoadModel, with exact primary-card identity and one resolution/load deadline. Native leader/guardian retain the existing reader lock independently of Core. Close retires the wrapper permanently; failed drain remains owned for retry, and replacement uses a new wrapper. Bootstrap accepts the explicit context only for native music. The supervisor retains its reader through process exit, includes MusicEditing in generation lifecycle bookkeeping, and routes complete edit metadata through DATA and an addressed-media callback. Native creation requires both generation and edit delivery callbacks. Worker preparation and capacity publication remain gated.worker/native_runtime_preparation.py: shared asynchronous preparation lifetime for built-in ACE/Demucs facades; bounded requests/replay fence, absolute queue/work deadline, cancellation join and retained failed close. ACE manager/controllerlibrary_probes()publishes only current path-free library math observations and withdraws them on revalidation/shutdown.NodeResources.native_music_probes: additive per-lane device/precision receipts; each must match its ready backend and exact engine payload. Omit the field when empty for older strict telemetry readers. No loaded-model or peak-memory admission follows from these facts alone; Worker publication and the native placement guard remain unconnected.shared/models/native_music_memory.py: version-one complete-component phase projection, pure host/device/unified fit and committed/pending reservations. Include actual casts, FP32 load copies, bounded media, libraries and temporary CPU VAE fallback. Forward allowance: unqualified minimum 2 GiB, scaling to 8 GiB at 120 seconds; explicit unknown-layout upper bounds can be reassessed. Unified peak is the maximum of simultaneous phase sums. Reserve every committed instance's still-unallocated peak against observed free memory, including idle models' future workspace.NativeMusicMemoryReservationcredits only verified exclusive allocations in that exact capacity snapshot; missing/stale allocation facts credit zero. Shared credit is unique physical storage. Total commitments additionally cap each domain. CPU cannot borrow VRAM; GPU also needs host capacity. Native model start rechecks all observed phase costs before workspace/native allocation. Policy bindsmemory_policy_version = 1.NativeMusicMemoryCapacity: canonical independent native contract; collection time, host and actual logical device zero, explicit discrete/unified topology and shared physical pool. Packagememory_probeuses native CUDA/HIP device-zero free/total and driver topology, or MPS working-set/physical-host readings. Cache rejects missing/unsampled observations. Shared fit requires age at most 120 seconds and forward clock skew at most 30 seconds. No aggregate GPU capacity or tested-device allowlist. Worker/placement wiring remains.NativeMusicMemoryBudget/native_music_memory_budget_error: portable admitted phase ceilings and the same Core/native pre-load fit. Normalize pressure headroom once before reservations withnative_music_admission_capacity: host/shared up to 512 MiB, device up to 256 MiB, each capped at 5% of small totals.- Native
live_resource_guard: required cache feature. Before load and every 0.5 seconds, sample own RSS, CUDA Torch reserved/MPS driver allocation, ROCm process-owned DRM requested-buffer totals, and actual host/device/shared availability. ROCm maps actual HIP device zero through its already loaded runtime to PCI/client identity; count all memory regions, deduplicate alias descriptors by conservative regional maxima, and fail closed on incomplete identity/accounting. Avoid the inference allocator-statistics mutex without changing ceilings or heartbeat deadlines. Enforce allocation ceilings and pressure; do not double-charge resident workspace or credit RSS as exclusive pages. Unified RSS uses simultaneous phase ceiling; unique physical peaks require qualification. Sensing/egress failure retires the private native group even with closed stderr. The independent guardian retains source/service locks. - Private
NativeMusicMemoryFrame: latest-value local control only; no media, State or event log. Core binds PID/payload/device/contiguous sequence, requires a sample before ready, and rechecks after blocking dequeue. Freshness at most 5 seconds; first-sample startup grace 30 seconds. Serialized native control egress has a 2-second drain deadline. Inventory requires memory-probe and live-resource-guard features; older candidates without them cannot activate. Current Worker preparation and native placement use these same contracts. worker/native_music_media.py::NativeMusicMediaOwneris wired to Worker task, snapshot, input/output and shutdown lifecycles. It captures only complete local native assignments with their stamped policy/build. Generation reserves a durable writer intent without inventing an original WAV; editing requires the verifiedmusic_edit_sourcehandshake. The planner gates both on actual media readiness. Source and result-only jobs share four serialized journal slots. Recovery fails uncertain local work and retains files until the inherited reader fence drains; it does not replay a native edit.worker/native_music_output.py::NativeMusicOutputProducer: verify PCM24 stereo 48 kHz WAVs against completion facts, stream bounded addressedmusicormusic_editframes, correlate exact reverse ACKs only after emitted terminals, and join the sender before ownership-checked reclamation. Failed cleanup keeps its reservation. Native completion, media custody and task state are separate. Once a valid result is registered, ordinary execution-task removal after terminal DATA cannot cancel its bounded delivery. Explicit failure/cancellation and correlated reverse control still abort it; ACK and sender join precede cleanup. Existing audio.cpp output, speech and separation paths retain their contracts.routing/output_media.pyfiltersmusicandmusic_editby receiver role: APIs receive WAV frames, Workers receiveaccepted/cancelledcontrols, and both receive transport failures. Neither role waits for the other's unrelated rendezvous subscription. Video/thumbnail subscriptions remain unchanged.ace_step/resources.py::NativeMusicHostGuard: immutable, picklable outer process callback; checks its actual child, current host capacity/pressure and RSS without capturing Worker State or importing Torch. The private native observer independently owns device sensing and heartbeat freshness. Core and native usenative_music_host_available_bytesfor consistent macOS Mach wired/anonymous/compressor accounting with bounded one-secondvm_stateffects and actual psutil fallback. No RSS allocation credit is inferred.PrepareAceStep/AceStepPreparationRequestedbind one complete-package digest, owner, selected worker and explicit CPU/Metal/CUDA/ROCm device. The master supplies a thirty-minute absolute deadline. Worker preparation runs off-loop through the existing persistent ACE controller/cache; offline mode cannot download.AceStepPreparationCompletedreturns the same identities and either verified resources or a bounded failure diagnostic. Success needs the actual executed lane probe; the master additionally checks the fixed package/payload before refreshing its live view. Periodic Worker resources derive native build IDs and probes from one locked snapshot and preserve other engines. Package inventory alone is never a ready backend. Shutdown drains both native audio preparation owners.- Worker
_restore_cached_native_runtimesruns once in its owned task group.NativePreparationController.restore_cachedowns one bounded 120-second attempt per engine, joins discovery/preparation on cancellation and forces offline verification even when the Worker is online. Managercached_lanesreads only eligible fixed-inventory original archive paths; hints never publish readiness or authorize downloads. Shared CPU/Metal archives probe CPU last. Fresh resources are published after each engine recheck for ordinary restart placement; bad/missing/incompatible/capacity-blocked cache stays unready with diagnostics. Empty base installations remain engine-free. ace_step/workspace.pypermits only the pinned timing-cache path.cache/acestep/progress_estimates.json(1 MiB cap, counted in the shared 256 MiB loader cache bound). Unknown sibling files/directories still refuse the whole cleanup before deletion; inherited fences, private inode checks and independent retained-result custody are unchanged.- Native platform filtering and actual API/Worker/Master activation are connected on this initiative. Signed distribution and installed platform/ music acceptance remain distinct requirements.
api/ace_step_preparation.py::AceStepMountPreparer: actual public ordinary/ exact mount barrier; fixed advertised OS/CPU/profile and generic hardware candidates, maximum four pending API requests, one absolute thirty-minute budget across all candidate attempts/send/queue/work, complete request/API/ worker/digest/device correlation, then shared actual native phase admission. Scoped ordered resources reach Master admission despite stale telemetry.master/main.py::ace_step_preparation_eventrefuses expired, departed and unknown-profile requests and preserves the earlier deadline; long direct requests are additionally capped at thirty minutes. Offline remains verified cache reuse only. Transport loss returns actionable 503 and releases waiters.model_engine_requirementsderives intrinsicace_stepfrom the validated native artifact profile without changing signed card bytes. EngineType knows exactly CPU/Metal/CUDA/ROCm native lanes; expansion never invents Vulkan. Non-native cards cannot select native ACE. Exact-build native qualification lanes report evidence only, independently of placement eligibility.shared/models/native_music_admission.py: pure current-package/library/math assessment from actual timestamped device-zero observations and deduplicated placement commitments. One physical pressure floor, full idle native phase costs, ordinary concrete-shard footprints, shared GPU storage charged to CPU targets, and zero attribution credit for loaded status. Unknown topology is conservative; unrepresented RPC partitions refuse admission. Worker exclusion requires its exact unchanged authoritative instance. Raw physical capacity and reserved remaining capacity remain distinct. Ordinary/exact Master placement calls it with raw native facts and complete deduplicated pending, Steward and indexed commitments. Exact callers cannot invent cheaper math or partial shards. Generic reservations hold native idle future phase peaks, discrete GPU host costs and shared physical costs. Missing restored policy refuses the affected pools; native GPU coexistence is capped by actual device zero, never largest-GPU or additive-carve telemetry.- Worker
_complete_native_music_runner_creation: explicit current package/ device refresh through the off-loop controller, native media reader fence, staging-locked placement/trust/runtime/policy/full-memory recheck, exact self exclusion, then supervisor custody of lazyNativeMusicRunnerContextwith immutableNativeMusicHostGuard. First-mount sources remain unresolved until normal DownloadModel/LoadModel. Failure/cancellation closes untransferred custody. Indexed owner removal or snapshot replacement cancels its preparation request. Source integration does not establish distribution or qualification. Worker LoadModel preflight resolves the exact recorded native primary off-loop through the same resolver as deferred binding, including indexed installed generations without generic aliases. Missing/stale primaries refuse dispatch; the deferred model still verifies every selected source before native loading. - Resident
_read_outputforwards validated native memory frames throughrecord_native_music_memoryand bounded non-blocking diagnostic IPC. Supervisor ownership/context/payload/device/native/local freshness and process liveness checks retain one transient sample; no phase/history/event entry. Worker resource gathering overlays current free capacity only for the exact authoritative owner, verified library and unchanged physical totals/topology. RSS/allocator facts earn no credit. Dead/stale/foreign/withdrawn owners cannot restore resources. Cold/expired repair returns actionable preparation pending; installable-only metadata never becomes ready. No sealed adapter or portable native protocol change is required for this Core-side observation forwarding.
Native separator fixed-inventory promotion
The separation package workflow distinguishes current-source verification from
explicit fixed-inventory reproduction and same-source promotion. Only the latter
builds DEMUCS_ADAPTER_REVISION, verifies all three original CPU archive/payload
pins and emits hosted provenance after the existing offline/cache/model/resident
checks. Separate producer and current-controller checkouts preserve immutable
package identity while exercising the current installation and execution seam. A separately dispatched publisher requires successful same-workflow,
same-repository, same-source candidates from initiative-merged reviewed source.
The shared bounded archive selector checks every fixed filename, size and digest;
the Demucs CLI selects three profiles and the ACE CLI retains six. Hosted
workflow/source attestations precede the serialized append-only engine index
writer. Publication never rebuilds bytes and still requires complete public
readback and the private ledger. Model weights stay separate, and package
availability is not loaded readiness or empirical hardware/music qualification.
Explicit node-download retry
The operator-authorized POST /download/start dispatches RetryDownload on
DOWNLOAD_COMMANDS after validating exact catalog truth. This distinct typed
variant preserves the existing StartDownload wire shape and automatic planner
semantics. DownloadCoordinator consumes only a same-artifact terminal failure
for an explicit retry, clears that attempt's progress throttle and starts a new
attempt identity through the normal verifier/offline/capacity path. A retry
arriving during failure publication suppresses old callbacks and waits on the
existing cleanup-to-queued-start handoff; it does not overlap owners or delete
files. One admission lock orders the entire handoff preflight and registration
with targeted start, cancel and delete commands, so a second request cannot
create a competing owner. Unscoped cancellation also withdraws a queued retry;
an old attempt-scoped cancellation cannot withdraw that new intent.
Active/completed starts remain idempotent. Deploy compatible target
readers before using the new command. This does not reset coordinator state for
master-generated DownloadPending placement recovery; that cross-component
recovery remains a separate contract and test obligation.
Installed native read host
api/native_calls.py: production direct-owner/v1/native-capabilitiesdirectory, GET/PUT revision-fenced policy and raw JSON unary call routes. Authentication usesauthenticate_capability_ownerand the actual API node.extensions/native_calls.py: current service profile, signed installed contract matching, exact local read enrollments, host-minted root contexts, bounded active scopes and independent compiled delegation recomputation. Discovery uses the shared512KiB envelope bound, per-installation coalesced connections and at most64 concurrent owner probes per host. Each directory has one3second observation deadline, then bounded RPC cancellation cleanup; per-owner probe admission precedes shared slots, preventing duplicate waiters from consuming other owners' capacity. Threaded metadata verification retains one separately owned task per installation, at most64 per host, and its installer fence until actual completion; cancelled observers cannot spawn duplicate workers. Completed results are not cached; shutdown drains workers. Owner startup waits up to30seconds for the installer fence before execution, avoiding crash backoff for brief metadata contention; selection and stop intent are rechecked before launch, without replaying interrupted calls. Completed signed results preserve path order without stale-capacity caching.extensions/native_host_binding.py: normal stopped-owner provisioning; profile signing key outside author startup, per-installation runtime/transport/ service-lifetime attachment and fresh server-proof secret. Key creation uses the manager's privatenative-host-key.lockfence.extensions/native_host_protocol.pyandnative_host_rpc.py: mirrored private Core/owner protocol; fresh mutual role admission, directional authenticated frames, sequence/correlation fencing, bounded request tasks and cancellation. Independent32 ordinary,32describe_inferencemetadata and96 stream-operation request slots reserve readiness, input and output progress while control roots remain pending; both directions retain shared byte/frame accounting. Queued response cancellation withdraws application custody and retains leases through an unknown-outcome acknowledgment. Partial-write cancellation fences the peer; no frame sequence is reused or uncertain request replayed. Role authentication does not authenticate the original caller.extensions/native_host_budget.py: event-loop-owned raw byte/frame leases; reservations survive delivery/backpressure and are released on terminal cleanup. Stream readiness/input/output RPC cancellation uses the selected signed cleanup grace. Owner authority withdrawal cancels the captured root even after its execution scope finishes, releasing pending terminal/end media independently of sibling calls.native-read-policy.json: disabled by default; exact installation, runtime, capability/version and full descriptor revision grants with explicit local processing enrollment.native-policy.lockexcludes updates during the final owner policy read/native write, and is released before transport drain.- Compatible installed owners preserve imported native context root/parent/ caller/issuer/ancestry and exact raw body hashes, then bind calls to an actual hello-admitted child incarnation. One reader handles health/results/delegates; one unary root is admitted per child. Early parent completion is uncertain.
- No raw body or completed-call ledger is replicated into State/events. Unknown outcomes are never replayed. Controlled caller retirement preserves genuine crash recovery; malformed protocol/output remains a failure.
- Scope: trusted same-account, local unary reads under one direct-owner realm. Separate gates remain for remote Fabric, paired-client native grants, streaming, governed effects and inference/router composition. No OS sandbox is claimed. Issued native/legacy profile and signature meanings remain unchanged.
Inference caller authority uses the stable core-profile:<profile_id> issuer
namespace. The current transport and owner-process lifetime are authenticated
separately. Normal journaled Core reattachment preserves enrolled bearers,
credential lifetimes, revocations and exact grants; stale transport attachments
still refuse. Authority records share an explicit 128 KiB protected-storage
bound, independent of author wire-frame limits.
Native inference WebSocket: sole receive/disconnect task starts after the initial JSON; queue8 plus in-flight input uses shared byte leases, saturation cancels the root, and trusted liveness guards persist across dispatch/delegation.
Invocation-scoped discovery: describe_inference with query_kind="directory"
uses only the actual role peer and live parent_call_id, matching its scope and
input hash. Core intersects fresh listings with that parent's exact allowed
addresses/domains and current original caller grants. Executor/ancestor identity
is (node_id, capability_id) across versions; depth8 yields no destinations.
A separate positive u64 query sequence refuses replay without consuming the
parent's effect sequence. One pending query is parent-owned through Reply release;
its physical-write guard rechecks credential/policy, owner, parent and expiry.
No completed/uncertain/delegating source can query. Atomic results are bounded to
4096 offers/8MiB and return metadata only. No bearer, permission grant, routing,
retry or authority cache is supplied by discovery.
-
Scoped discovery generation filtering: current exact caller grants, including runtime digest and I/O mode, filter observations before serialization; upgraded unenrolled generations are omitted without suppressing other permitted destinations. Final delivery repeats authorization and parent custody checks. No eligible destinations yields an empty directory.
-
Native management UI: the owner projects compiled native surface health against signed declarations and actual child lifetime. A ready proxy has an isolated owner-local loopback facade; its private upstream port stays private. Core
managed.summaries_foradmits only an uncredentialed IPv4 loopback facade URL and projects the existing topology opening link. Application scripts never share Core's dashboard origin. Host/Origin checks, child listener custody, application cookie/CSRF policy, bounded HTTP/WS forwarding and lifecycle drain belong to the owner. Opening the UI grants no inference or remote authority.
Delegated native streaming (SDK 1 candidate)
NativeInferenceCalls._handle_delegationseparates read-only exact-targetdescribe_inference,delegate_inference_stream, and reverse media operations from the existing unary delegation path. Parent lookup uses the actual role peer and call ID; public context metadata grants no caller authority.- Child media uses the admitted scope ID without rewriting packet bytes. Collision checks precede dispatch. Each readiness/input/output operation repeats original-caller and current target authority; leases survive physical response delivery, and failed delivery withdraws the parent.
- Finite caller or signed target ceilings narrow the compiled child context and monotonic timer; null introduces no generation deadline. Terminal delivery requires target end/control/cleanup and exact child completion. Repeated cancellation cannot detach target retirement or release the root early.
- Requires the matching owner candidate. This adds no HTTP endpoint and changes no issued native contract digest, signature domain, or provider custody.
Native unified chat adapter (experimental)
api/native_chat_catalog.py reads only this authenticated caller's metadata,
chat and optional continuation grants. Explicit application-envelope annotations
pair same-plugin/runtime/child/incarnation declarations without deriving an
application proof revision from a native digest. api/native_chat.py composes
those entries into the no-store model endpoints and prepares exact Chat/API
requests. api/native_chat_stream.py owns HTTP writes inside the revocable
native invocation, retaining output leases through delivery and requiring
native end/control/descendant completion. Valid semantic refusals also drain terminal/end/control completion before their safe error is delivered. Trusted final delivery runs after
retirement drains, with original-caller/disconnect custody still active and
completed execution unable to delegate. A failed already-started collected
response aborts its transport instead of acknowledging a successful JSON body. Receipt recovery selects transport
with native_model; its independent application proof target is unchanged.
The dashboard authenticates catalog reads, withdraws choices on operator
identity changes and keeps receipt recovery on the saved conversation's native
address. Provider account/session/catalog behavior remains capability-owned.
This is explicit destination dispatch; it implements no task routing policy.
Native catalog distribution
Native-aware catalogs use protocol 4 at catalog/catalog-v4.json, signed over
skulk.catalog/4\0 followed by canonical catalog claims. Native entries retain
runtime protocol 5, release protocol 3, the full managed/2 manifest revision,
the exact kernel source/version and profile cohort, and all declared processing
domains (local, private_site, external). Installation compares these
facts and the callable and management summaries against the independently
verified runtime. An older listing cannot describe a runtime-five application.
These facts establish discovery and consent, never caller or execution authority.
The same authenticated binding is retained in release reviews for recovery,
so catalog, retry/finish, direct-source and terminal consent can present the
processing locations and full declaration and ABI identities before acceptance.
The built-in reader probes v4, then v3, then the original catalog within one
bounded request. Only a genuine 404 before accepting a version allows fallback.
Accepted version and revision floors survive restart, failed document retention
and private-source switches. Existing catalog schemas and signatures are unchanged.
Native music preparation and restart overlap
- Worker
_native_music_preparation_scopeserializes ACE cached restore, explicit prepare and verification-to-supervisor handoff. Four admitted owners maximum, including lock waiters; queue/work share the original finite deadline. Cancellation/expiry/failure releases both slot and lock. Library identity, source-reader custody, current placement/trust and memory admission stay checked. Placement withdrawal/snapshot replacement cancels queued creation owners and joins active native drain before releasing ownership; unchanged snapshots retain their live owners. - Master restart recovery rechecks late indexed and ordered pending placements while information is missing. A private accounted-instance set prevents double-crediting earlier restorations and preserves recorded model-copy counts. Dying instances cannot satisfy intents; advancing the head renews only the next intent's existing information-wait budget. No new wire or State surface.
Signed runtime version pairs
Runtime envelope versions are interpreted with their signed release version.
The application-root pair (3, 1) keeps legacy manifests, plain canonical
signature bytes and its original digest. Native pairs (3, 2), (4, 2) and
(5, 3) retain their domain-separated signatures and exact profile cohorts.
The host chooses one signing scheme from the declared pair before verifying;
it never retries a failed signature under another scheme. Strict record readers
refuse mixed application-root/native claims. Selection, retained-state identity,
management summaries and installation use the same distinction.