Skip to content

Latest commit

 

History

History
352 lines (315 loc) · 23 KB

architecture.md

File metadata and controls

352 lines (315 loc) · 23 KB

Architecture

Spool is a ComfyUI extension with three parts: a Python backend that owns projects and execution, the studio (a browser app served at /spool/), and a small Comfy page extension. Vocabulary is defined in the glossary.

ComfyUI page (web/*)  ── BroadcastChannel bridge ──  Studio (ui/*)
        │                                               │
        └──────────── HTTP /spool/api/* ────────────────┘
                              │
                     Python backend (spool/*)
              project folders · SQLite · execution targets

Backend (spool/)

__init__.py registers the routes on ComfyUI's server and starts the local executor. __main__.py runs the same routes standalone (python -m spool).

  • HTTP surface: routes.py (every /spool/api route and the local-control guard), editor.py (serves the studio), cli.py (thin HTTP client).
  • Projects: projects.py (folders, local working SQLite, snapshot publication under a lock), store.py (the only module that knows the tables: editing changes a document at a revision, named reads and writes do the rest), ledger.py (authored document, take ownership, generated-take projection), notes.py, maintenance.py (prune and reclaim).
  • Commands and operations: commands.py holds typed agent commands with scope, budgets and operation replay. operations.py holds the project operations both routes and commands perform (take choice and trim refit, workflow assignment, Use take and Apply to clip with their take.json ordering). Scoped Use take uses the same capture operation inside the command transaction; its receipt retains an ordered sidecar-delivery plan for hash-checked retry after commit.
  • Requests and attempts: requests.py freezes a generation request independently of a running Comfy. attempts.py is the Attempt module: statuses, allowed transitions, Cancel policy and target_of, the one rule for where an attempt computes. ownership.py gives one process the dispatch role.
  • Execution targets: execution_targets.py defines one ExecutionAdapter contract and the local, Deadline and Cloud adapters, selected by attempts.target_of. prepare, submit, observe, cancel and recover return dictionaries with submission material, acknowledgments, observations or decisions; adapters never write the project store. Cancellation separates the ownership check, transactional plan and external send so an unconfirmed delivery stays retryable. Recovery never resubmits uncertain work. execution.py owns local/Deadline claims, executor identity, host hooks and validation, the frozen-prompt semantic check and guarded status transitions. farm.py applies Deadline observations and verifies/accepts worker receipts; it holds every deadlinecommand call. deadline_job.py, deadline_task.py and farm_protocol.py are the submission, worker script and receipt protocol. cloud.py drives the same adapter contract through comfy-sdk in its own loop, because it needs no local Comfy; it persists job IDs and accepts downloaded receipts through the shared collector. commands.py applies adapter cancellation and recovery decisions under the existing scope, replay and delivery guards.
  • Results: receipts.py (atomic, versioned receipts), collection.py (recovery without Comfy's queue), folder_takes.py (external takes in clip folders), sidecars.py (take.json workflows), take_files.py (permanent deletion), take_workflow.py (continue from a take).
  • Workflows: workflows.py, workflow_inputs.py (loader addresses, and optional and grouped media inputs: what blocks a request and what it leaves out), graph_inputs.py, templates.py (built-ins: Spool's own workflow files in builtin_workflows/ and curated Comfy templates), cloud_templates.json.
  • Media: media.py (probing, proxies, staging, playback copies), playback.py (one host-wide background encoder and source-job deduplication), timing.py (source-frame clocks), cuts.py (hard-cut detection), export.py (MP4), interchange.py (OpenTimelineIO JSON, written without the OTIO package).
  • Host: launcher.py (starts a configured ComfyUI), system.py (what differs between Windows, macOS and Linux: finding ffmpeg and deadlinecommand, showing files in the file manager), credentials.py (Cloud key), requirements.py (reported requirements), wire.py (exact integers).

Storage and project-folder work runs off ComfyUI's event loop through asyncio.to_thread. Live SQLite and playback copies stay on the local disk; project folders hold the published snapshot, import proxies and other referenced media. Playback cache keys include source path/size/mtime, project size/FPS and the cache format version. The preview route enqueues work and returns preparing until its local file is ready. Launcher probes, status and startup use cancellation-draining workers for their SQLite and filesystem work, including process creation. Startup reservation and spawn stay in one worker. Status/error writers replace only the launch state they observed, so a delayed worker cannot overwrite a newer reservation.

Cancellation preflight reads the acknowledgement through the immutable read generation. Planning and recording delivery still use their writer transactions. FFmpeg text diagnostics use UTF-8 with replacement for invalid bytes, independent of the host locale; subprocess failure types and timeouts remain unchanged. Comparison sheets extract frames in a private temporary directory and retain only the returned sheet. Explicit frame exports remain durable user outputs.

Project format

A project folder has a project.spool SQLite snapshot and a small project.json manifest: format: "spool-project", formatVersion (the SQLite user_version), projectId and writtenBy (the Spool version). There is one format number; currently it is 7. Opening reads the manifest first and refuses a newer format before opening SQLite. Older folders without a manifest acquire it on their next published write. JSON exports use their separate spoolVersion: 1 envelope; imports reject unknown export versions before creating a destination.

store.py owns ordered, numbered migration steps. Each commits its data and version together, version last; a failed step rolls back and can run again. Completed earlier steps remain committed in that database; a project folder publishes its upgraded working copy only after every step succeeds, so a failure leaves the published snapshot at its old version. Released steps are frozen: changes require a new number. Before upgrading a folder, Spool copies its last published snapshot to .spool/backups/project-schema<old>-<UTC timestamp>.spool. Schema 6 packs existing evidence, then compacts through the existing local-cache path after commit. Newer SQLite versions are refused even without a manifest.

Schema 6 keeps immutable JSON in blobs(hash TEXT PRIMARY KEY, data TEXT NOT NULL). The hash is SHA-256 of store.encode's canonical UTF-8 JSON; a reference is {"__spool_blob__": "<hash>"}. Recipe captures share their workflow and prompt blobs; attempt requests refer to the same captures. API nodes, editor nodes and subgraph definitions also share blobs, so changing a seed does not copy the whole graph. Authored document captures and imported workflow records use the same packing boundary. Scalars used by SQL remain directly accessible. Attempt results and execution receipts refer to one receipt blob. Receipts name primaryArtifactId instead of duplicating the primary artifact. Storage markers restore the original receipt envelope, including whether it exposed that ID.

A media file owns its embedded workflow and prompt. Artifact fields and separated media evidence use {"__spool_media__": "<original path>", "key": "workflow" | "prompt", "graph": true | false} instead of storing those values. Identical members of prepared workflowData use the same references; distinct sidecar/prepared values remain stored. During migration paths come from authored records, collected artifacts or the original probe filename. Probes retain their streams and format fields except format.tags, extracting the metadata before dropping those tags. One editor graph remains available per recipe capture.

Routine project, attempt and receipt reads expose evidence / embeddedGraph markers for file-owned fields. The evidence routes, continuation, sidecar creation and portable export resolve them from the original file (PNG tags or video probe) on demand. Resolution is cached only within a read; a missing original reports Source media is missing or unsupported. SQLite does not substitute a stale graph. The history prompt tuple keeps the exact API prompt, number, prompt ID, outputs, status, messages and other metadata. Its editor graph uses a file reference when it equals an artifact's embedded graph; other graphs share stored blobs, including with dispatch metadata.

Projection passes decoded requests/results directly to the ledger, avoiding a JSON encode/decode round trip. Identical decoded blobs share objects within that response, whose captures are treated as immutable by readers; later reads are independent. The bounded process cache holds only JSON text, so caller mutations cannot corrupt later reads.

Schema 7 persists terminal finished_at on attempts, backfilled from events (or creation time when no terminal event survives). Routine editor generated takes carry only EDITOR_TAKE_FIELDS: identity, number, revision, seed, generated flag, media, a batch summary and a recipe-graph marker. Their summary keeps the attempt ID, workflow version, input values and binding labels/seed roles; the graph and full request/result are fetched through the project-scoped /takes/{take} route. Current clip recipes and imported workflow records remain in the editor response. The ordinary automation project response and scoped commands retain full requests.

Project reads pin a separate immutable local SQLite snapshot under a local file lock. Only a changed published signature refreshes it under the share lock; writers serialize working-copy refresh/replacement with a different local lock. A writer can publish while an existing reader finishes its older generation.

Each newly published snapshot contains an additive spool_publication table with a fresh publication UUID. The marker is written into the copied database before it is fsynced and atomically replaces project.spool; it travels with the snapshot even if manifest publication is interrupted. Change detection combines the marker with timestamp, size and file identity. Unchanged high-resolution file identities cache the marker; coarse timestamps re-read it. Legacy snapshots without the table remain readable and gain it on their next new-version save. Marker reads hold the project lock until their SQLite handle closes, so they cannot obstruct a concurrent snapshot replacement on Windows. An unreadable identity fails the operation instead of authorizing reuse of an older runtime. The manifest, document, API and SQLite schema-version number are unchanged. Older writers preserve the marker but do not refresh it; mixed-version detection then relies on the replacement file's identity. Failed project imports clean their exclusively created destination and new local working cache. Cleanup preserves pre-existing caches and refuses redirected or uninspectable paths; a denied cleanup retains the original import failure.

Receipt scans visit pending attempts every two seconds and settled history every five minutes (also on collector startup). Folder scans cache projection/inventory at a revision/event cursor and recheck both inside the save transaction. Collected outputs are recognized by exact artifact paths; pending attempts also reserve files whose stems contain their take ID's first eight characters until they settle. external_file_index stores path, take/media IDs, file identity, size, modification/change times and SHA-256. Same-directory renames preserve identity only with the same nonzero device/inode and bytes and a missing old path. Copies and cross-directory moves become new takes. Changed bytes at an indexed path create a new take; the old record points to a missing source instead of silently playing the replacement. Renames/replacements discard old file-owned evidence.

Manual reconciliation, local result observation and Cloud receipt ingestion use the same collector's per-project thread lock as periodic scans. File collection for one project cannot reuse another worker's partial files; other projects have independent locks. Cancellation drains these storage workers before their executor lock or lifecycle ownership is released, including repeated cancellation. Local, Deadline and Cloud artifact copies use unique sibling temporary files, including when independent workspaces collect into the same project. Publication uses the common replacement retry; cleanup removes only the operation's own temporary file and retains an original failure if cleanup is denied. This file ownership does not serialize separate collectors' receipt or ledger decisions.

Deadline's 30-second missing-acknowledgment grace starts when collection first observes the durable submitting.json marker written immediately before the external call. Queued time, validation and staging do not consume it. Restarting the collector grants fresh grace. An observed marker remains evidence if share files disappear; a never-observed missing marker stays pending conservatively. Recovery does not automatically submit another job.

Once daily, collection expires events and operation/result payloads older than 30 days, retaining each project's latest event cursor and cancellation effects whose delivery is unconfirmed or whose attempt is still active. Operation ID/project/digest tombstones live forever: expired retries return an operation conflict and never execute again. Attempt ownership rows expire with old terminal attempts. Attempts, dispatches and execution receipts remain evidence for recovery and deduplication; they are not diagnostic logs. No Python/JavaScript authored document fields or wire versions change. Maintenance reports scan immutable read-only snapshots in private temporary directories, removed after the report. They do not migrate, create project directories, refresh the workspace cache or recover take files. Copying holds an existing project lock until the source handle closes; SQLite then opens only the private copy, letting writers publish during long scans on Windows. Read-only inspection never creates a lock. A legacy folder without one can still briefly obstruct Windows replacement while the source is being copied.

durable.py owns unique temporary files, flush/fsync, atomic replacement with SMB retry, and failure cleanup for JSON receipts, take sidecars, farm JSON and manifests. ownership.atomic_replace reexports the same replacement primitive. OTIO exports use the same replacement retry and exclusively created pending files, cleaning only their own unfinished file after a failure. Deadline submissions copy the stdlib-only helper beside their worker protocol. Local receipt.json writes use schema 2 and primaryArtifactId; collection still verifies schema 1 from older executions. Farm protocol 2 already uses that representation and retains its exact-prompt verification.

Studio (ui/)

editor.html loads bootstrap.js, which owns the loading barrier and imports editor.js, the composition/startup runtime. See editor.md. Focused modules hold the contracts that have tests of their own:

  • timeline-renderer.js and timeline-pointer.js: timeline DOM reuse and pointer gesture lifetimes, separate from pure timeline edits.
  • inspector-renderer.js, library-renderer.js, workflow-coordinator.js: selected clip controls, media cards and workflow-library coordination.
  • timeline.js: pure timeline operations (timeline.md).
  • project-edit.js: draft, revision, save, poll and capture ownership (project-edit.md).
  • ledger.js: authored projection and take arrivals, mirroring spool/ledger.py; the document field registry is pinned by tests/fixtures/document_fields.json.
  • api.js: the one HTTP client for /spool/api (error mapping, processing labels, background rules, recipe attachment on save).
  • queue-submission.js and input-actions.js: asynchronous submission and input replacement ownership with explicit editor adapters.
  • dialogs.js and action-menu.js: modal and menu lifetimes and focus.
  • viewer.js: viewer presentation, media pools, seeking, preview preparation and playback/audio ownership on top of picture, preview and take-review.
  • picture.js: what the viewer shows at a frame or in Source, apart from playback.
  • pointer.js: cancels every pointer gesture when the window loses focus or the tab is hidden.
  • edit-actions.js: history restoration, deletion and workflow assignment with input-replacement invalidation.
  • edit-session.js: applies an authored edit (undo step, change, repaint scope, save); pointer gestures record their own step on release.
  • input-groups.js: optional and grouped media inputs, mirroring spool/workflow_inputs.py.
  • history.js (undo and redo), generation.js (attempt status table and seeds), workflow-setup.js (capture decisions), profile.js (input profiles), take-review.js, take-seen.js, preview.js, thumbnails.js, notes.js, diagnostics.js, topbar.js, workflow-library.js, template-browser.js, shortcuts.js, bridge.js, wire.js.
  • Feature owners cover take rendering/actions, audio editing, clip selection/tools/ badges, track layout, drops, trim previews, layout controls, import/export, project dialogs, Renders, Comfy connection and workflow registry/controls/dialogs; see editor.md for the full owner map.
  • studio.css: the one stylesheet, with semantic colour tokens on .editor.
  • builtin-captures.json: generated by tests/build_builtin_captures.py.

Comfy page extension (web/)

spool.js adds Open Spool ↗ to ComfyUI's top action bar and serves the bridge. workflow-link.js owns linked graph tabs and Apply to clip; graph-capture.js and graph-inputs.js resolve widget addresses the way Comfy serializes them; template-prepare.js and template-browser.js prepare and show Comfy templates without touching the user's graph.

Contracts shared across languages

Contract Python JavaScript Pinned by
Exact integers spool/wire.py ui/wire.js tests/fixtures/wire_cases.json
Attempt statuses spool/attempts.py ui/generation.js tests/fixtures/attempt_statuses.json
Document fields spool/ledger.py ui/ledger.js tests/fixtures/document_fields.json
Take ownership spool/ledger.py ui/ledger.js tests/fixtures/ledger_cases.json
Optional and grouped inputs spool/workflow_inputs.py ui/input-groups.js tests/fixtures/optional_inputs.json
API version spool/protocol.py ui/protocol.js tests/fixtures/protocol_versions.json
Project push hints spool/projects.py, spool/routes.py ui/project-sync.js tests/fixtures/project_updates.json
Bridge messages — ui/bridge.js tests/bridge_checks.mjs
Neighbour inputs spool/requests.py ui/direction.js tests/fixtures/neighbours.json
Cast mentions spool/cast.py ui/cast.js tests/fixtures/cast_mentions.json
Directed take start spool/operations.py ui/timeline.js tests/fixtures/directed_takes.json

Directing tools

Transitions and extensions are ordinary clips with built-in workflows, so execution, takes and Edit in Comfy need no new paths. What they add is resolved when a request is frozen, never stored as baked files: neighbour inputs read the clips beside the shot, cast mentions fill reference inputs, and draft quality lowers resolution. A draft is offered only where the workflow can finish it from the draft take itself (a draft video input feeding an Open-H3-Regenerate style refine behind a lazy switch): rendering again at another resolution with the same seed gives a different video, so a draft that cannot be refined is a preview of nothing. Joining footage is anchored as a short clip (a video binding's span) rather than a frame where the workflow allows, because one frame restarts any movement under way at the cut. A request records what each resolved to (shotInputs[].clipId, castMentions, quality, finishes), so a take stays explainable after the edit changes. The command API exposes the same pieces on existing clips (set_shot_inputs, set_cast, draft variants); creating the clips stays a studio action, as other clip creation is. A technique that needs no place on the timeline, such as Recast, is a built-in workflow only, with no dialog of its own.

One output is baked: an extension's joined copy (spool/joins.py). The take re-renders the shot frames it was given, so a cut to it pops, it can slip a frame, and H3 dims its first new frames. When the result is collected (local, Cloud and Deadline alike), Spool writes a copy whose overlap is the frozen shot frames, dissolving into the render over BLEND frames, with the new frames measured into place and their brightness eased; it is recorded as the take media's join, and the render and its receipt stay as they were. Playing it in the edit is a rule, not an edit (ui/timeline.js:joinedTake): while the shot is still the take and trim the request froze and the extension starts where the copy's new frames do, the viewer, the MP4 export and the timeline export switch to the copy BLEND frames before the cut. Anything else is a plain cut to the take as rendered, so the document never changes on its own. The copy is made from the request alone, which is why it is baked at collection rather than mixed live: the two exports and the viewer then show the same frames.

Constraints

  • Ordinary workflows need no Spool nodes or graph rewrites.
  • Keep project state, UI, identity mapping and execution adapters in this extension; prefer narrow integration over changes to ComfyUI.
  • Generation never selects a take. Only an explicit choice changes the edit.
  • A request is frozen before dispatch, and nothing is resubmitted automatically when its outcome is uncertain.

API compatibility

spool/errors.py defines expected failures; the route middleware maps unexpected exceptions to a generic 500 and logs their traceback. ValueError messages remain user-facing 400s. Explicit missing resources use NotFound; ordinary KeyError and TypeError indicate bugs. ROUTE_AUDIENCES declares each route's audience.

The integer apiVersion is independent of package versions. Bump it for changes to the API or authored document that an older studio cannot safely write. Pin the Python and JS values in the protocol fixture. Versioned studio writes must match; versionless tools retain the public automation contract. The Comfy bridge has a separate bridgeVersion on ping; keep its literal names unchanged. See durable names before renaming persistent identifiers.