Hazel

The Companion

The companion is a second process the editor starts beside itself. It runs slow work (thumbnails, Rust script builds, virtual-geometry bakes, the project file index) and the profiler, so the editor's own frames go to the scene being edited. This page covers how it is built, how the two processes talk, and how to move a job into it.

Two companions

StandaloneEngine
Binaryrenzora-companion, package renzora_companion_serverrenzora --companion, the engine itself in companion mode
Bevynone, enforced by a build checkthe whole engine
Memory at resta few MBabout a gigabyte and a GPU device
Started whenrenzora-companion is beside the editor executablethe file is missing, or RENZORA_COMPANION_SERVER=0

The standalone one is the default. It exists because the engine companion carried the whole engine, and a GPU device, for work that is almost all file, CPU and network. The engine companion still runs kinds the standalone one does not yet have (model import, export, marketplace installs, store images, uploads); while the standalone one is in use, the editor does those itself, as it does with no companion at all.

Both speak the same protocol, and each announces the job kinds it runs, so the editor never sends a kind the connected companion cannot do. That is what lets a kind move from one companion to the other with no moment where nothing can run it.

The crates

CrateBevyWhat it holds
crates/renzora_companionyesThe editor side (CompanionHostPlugin: start, connect, restart, route jobs) and the engine companion's app (app/).
crates/renzora_companion_protonoWhat both ends share: the protocol, job argument types (job_args), the profiler's frame and wire formats, probe and timeline types, the project file list.
crates/renzora_companion_servernoThe standalone companion: job queue, project cache, profiler, render-worker manager, window.
crates/api/renzora_platform_api (companion module)yesThe editor-side API any crate uses to submit a job, without depending on the companion.

Keeping the standalone one Bevy-free

The standalone companion's graph stays Bevy-free only while nobody adds a bevy line, or a renzora_* crate that has one, and the first logging macro someone reaches for is exactly that. Nothing else would notice: it would build, run, and quietly weigh a gigabyte again. So:

  • cargo renzora check-bevy (run before every cargo renzora build, and in CI) also checks the packages in ENGINE_FREE (xtask/src/bevy_source.rs), and fails naming each Bevy crate and what pulled it in.
  • It is built in a cargo invocation of its own (build_companion in xtask/src/main.rs). Cargo resolves features once per invocation across every selected package, so inside a --workspace build the engine's use of a shared crate turns that crate's optional bevy feature back on and the companion links the engine it exists to leave out. The container build excludes it from the workspace build for the same reason.
  • That build is fatal, like the workspace build: a stale companion beside a new editor would speak an old protocol.

Lifecycle

CompanionHostPlugin (an editor plugin) starts the companion at launch:

  1. It opens a loopback listener and starts the companion with --companion-port <port>, --companion-token <token> and --profiling-key <key>.
  2. The companion connects and sends Hello { token, version, kinds }. A wrong token or a protocol version other than PROTOCOL_VERSION is refused. The token proves the connection comes from the process the editor started, not from anything else on the machine that found the port.
  3. The editor records the kinds (CompanionJobs::set_kinds) and sends an Echo job as a round trip; the Console logs Companion ready (round trip ... ms).

The companion's stdout and stderr are piped into the editor's Console under the Companion category. If it stops unexpectedly the editor starts it again after two seconds, at most three times a session (MAX_RESTARTS). It exits with the editor: the link closing ends it on every platform.

The standalone companion runs at below-normal priority (SetPriorityClass on Windows, a nice step elsewhere), so its work yields to the editor. On Windows it is a GUI-subsystem executable, so it opens no console window.

The spanner icon in the top bar is registered with register_shell_tool; pressing it sends Show, which opens the companion's window, or starts the companion again if it had stopped.

The protocol

renzora_companion_proto::protocol: one JSON object per line over the loopback TCP socket, tagged by type. Control traffic is small and rare, so a readable format costs nothing and makes a stuck job easy to diagnose. The profiler's frame stream is a separate binary channel (wire) and does not go through here.

MessageDirectionMeaning
Hello { token, version, kinds }companion to editorAlways the first line.
Submit { id, job }editor to companionRun a job.
Progress { id, fraction, note }companion to editorfraction is 0 to 1, or None while the total is unknown.
Done { id, result }companion to editorResult<String, String>: usually a path or short summary, or a reason in words.
Showeditor to companionBring the window to the front.
Cancel { id }editor to companionStop a job if it is queued or running. Its Done still arrives, as Err("cancelled").
EditorState { playing, thumbnails }editor to companionWhat the editor is doing that work should keep out of the way of.

Job is Echo { text, millis } (the connect round trip) or Run { kind, payload, target }, where payload is the JSON of that kind's argument type and target is the label shown in job lists.

PROTOCOL_VERSION is 2 (version 2 added kinds to Hello). The two ends come from one build, so in practice they agree; the number is for a companion left running by an editor that crashed mid-rebuild, met by the next one. Bump it whenever a message changes shape.

Job kinds

What the standalone companion announces:

KindArguments (job_args)Where it runs
texture_thumbnailTextureThumbnail { source, cache, size }work.rs
rust_scriptRustScriptBuild { sdk_dir, project, source }work.rs; answers with the built library's path, which the editor loads itself
rvg_bakeRvgBake { model }work.rs
texture_bakesee job_argswork.rs; bakes an image into a mipmapped .rmip
rvg_migratesee job_argswork.rs
project_indexcache.rs; the project's file list, kept current by a watcher
profiler.record, profiler.status, profiler.summary, profiler.spikes, profiler.frameanalysis.rs; what the editor's MCP profiler tools ask
model_thumbnail, material_thumbnail, shape_thumbnailrender.rs, through the render worker; announced only when the renzora executable is beside the companion

Each module's KINDS constant is kept beside the match that handles it. A kind added to the match but not to KINDS is never announced, so it is never sent, and quietly runs in the editor instead.

Scheduling

  • Three worker threads (WORKERS) run jobs.
  • While a profile is recording, every job waits, so the profile measures only the game. Jobs that render also wait while the editor is in Play (EditorState::playing). The Jobs screen says what each job is waiting for, and Run anyway starts one regardless.
  • With the editor's thumbnail rendering turned off (EditorState::thumbnails == false), the companion drops its render-ahead backlog, fails thumbnail jobs, and stops its render worker.
  • The companion also renders thumbnails ahead of time for the project it is watching. Those jobs carry ids with OWN_JOB (bit 62) set, so they never collide with the editor's; remote submissions from a thread (below) use bit 63.

Submitting work from an editor crate

A crate asks for a job by kind through renzora_platform_api::companion, without depending on the companion. Call init_companion_jobs(app) from your plugin (it registers CompanionJobs and the two messages; adding it twice is harmless).

From a system:

use renzora_platform_api::{job_args, CompanionJobDone, CompanionJobs};

fn request_thumbnail(mut jobs: Option<ResMut<CompanionJobs>>, /* ... */) {
    let args = job_args::TextureThumbnail { source, cache, size: 256 };
    match jobs.as_deref_mut().and_then(|j| j.submit("texture_thumbnail", "grass.png", &args)) {
        Some(id) => { /* remember id; the answer arrives as CompanionJobDone */ }
        None => { /* no companion, or it cannot run this kind: do the work here */ }
    }
}

fn thumbnail_done(mut done: MessageReader<CompanionJobDone>) {
    for d in done.read() {
        // d.id, d.kind, d.result: Result<String, String>
    }
}

submit returns None when no companion is connected or the connected one did not list the kind, and the caller must then do the work itself. Moving a job to the companion must never make it impossible. Every submitter hears back exactly once: a job the companion lost (it crashed mid-job) arrives as Err. CompanionJobProgress { id, fraction, note } reports progress meanwhile. CompanionJobs::starting is set while a companion has been started but has not connected yet; work that can wait a few seconds (thumbnails nobody has asked to see) can wait for it rather than run in the editor during the frames a project is loading.

From a worker thread (import and export do their heavy work on threads of their own): clone CompanionJobs::remote() before starting the thread, then call CompanionRemote::run(kind, target, &args, &mut on_progress). It submits, blocks until the answer arrives, and returns None under the same conditions as submit. run_cancellable also takes an &AtomicBool; setting it cancels the job in the companion, and the answer still arrives once. run blocks the calling thread, so never call it from a system.

Adding a kind

  1. Define the argument type in renzora_companion_proto::job_args (both ends need one definition, and the companion links no Bevy), with a doc comment naming the kind string and what it answers.
  2. Handle it in the standalone companion: add an arm in the relevant module's run (work.rs for plain CPU and file work) and add the kind to that module's KINDS in the same change.
  3. Submit it from the editor crate with CompanionJobs::submit or CompanionRemote::run, keeping the in-editor fallback for None.
  4. Keep the handler free of Bevy. Code it shares with the engine goes in a crate whose bevy dependency is an optional feature, and check-bevy will tell you if it is not.

The render worker

Model, material and Shape Library thumbnails need the engine's renderer, which the standalone companion does not have. When there is one to render it starts a render worker: renzora --companion --render-worker, the engine companion's app with only its link, its queue and its capture code, so a thumbnail looks the same wherever it was made. The worker speaks the same protocol back to the companion: it says hello with the kinds it renders, and each job goes over as a Submit with an id of the worker's own, mapped back to the queue's id on the way in.

The worker is the expensive part (the engine's memory and a GPU device), so it lives only while it has work:

ConstantValueEffect
IDLE_EXIT30 sStopped after this long with nothing to render.
RECYCLE_AFTER50Replaced by a fresh worker after this many thumbnails, so memory stays bounded on a long backlog.
START_TIMEOUT90 sA worker that has not said hello by then counts as failed.

A job the worker cannot do fails, and the editor renders that thumbnail itself, as it does with no companion.

The window

The window is the same executable started with --window, as a child process, when the spanner asks for it, and it exits when closed. It is a process of its own because a GL driver stays loaded until its process exits: a window drawn inside the companion left about 90 MB behind, while a child gives all of it back. It is drawn with egui (the companion has no Bevy, so ember is not available to it).

It has six screens: Profiler, Render, Debug, Jobs, Cache and Games.

  • Games lists what can be profiled: the editor, a game started with Play, and exported games with profiling allowed anywhere on the network. Connecting starts a recording; the companion keeps up to MAX_FRAMES (7200) frames of spans, and the window keeps the last WINDOW_FRAMES (360) to draw from.
  • Profiler shows the frame graph, a per-thread timeline and a per-schedule breakdown with critical paths, from the spans the game streams. The breakdown also graphs the machine (CPU use by the game and by other programs, RAM, GPU memory, allocations a frame) and lists the focused frame's heaviest allocators; see Benchmarking. It also shows a picture of the window near the focused frame, the sampled functions and waits in view with a source view, and log lines marked on the timeline; see Call-stack sampling. The same analysis runs without a window as renzora-companion --analyze <capture>, which is how cargo renzora bench reads its runs.
  • Debug shows debug probes as cards: readouts gathered only while their card is ticked. The ticked set is remembered in ~/.renzora/companion_window.json. The editor's former debug panels live here as probes, because a panel that changes every frame cost the editor a full UI relayout every frame. To add one, see Debug Probes.
  • Jobs shows running, waiting (with the reason) and finished jobs, with cancel and Run anyway.
  • Cache shows the project's files and the thumbnail cache, with buttons to render missing thumbnails or clear the cache.

Profiling exported games

A game exported with profiling allowed announces itself on the network and only accepts a companion holding the editor machine's pairing key, which the editor passes as --profiling-key. The key is kept in ~/.renzora/profiling_key; deleting it makes a new one, and builds made with the old key can no longer pair. A game exported without profiling never announces itself or opens a port.

Environment variables

VariableEffect
RENZORA_NO_COMPANIONSet to anything: the editor starts no companion and does all work itself. For debugging the editor alone.
RENZORA_COMPANION_SERVER=0Start the engine companion instead of the standalone one.