Exposing a tool to the scientific workbench¶
This is the contract for new GUI tools in GUI 0.8.0 and core 0.25.0. It is implemented by the host and the descriptors, docking, MD and OpenFE extensions. Use the compatible component versions in the documentation version matrix. The host owns shared setup, execution, progress and result interactions.
Ownership and registration¶
A tool continues to register its configuration, workflow, input ports and output ports
with caddforge.tools. Add a GuiToolSpec to the tools tuple on its existing GUI
extension, registered with caddforge.gui_extensions. Core owns the small, immutable
Python metadata classes; the GUI owns rendering and interaction. Core never imports
scientific packages to implement a GUI.
from caddforge.gui import GuiToolSpec, GuiFieldGroup, GuiResultView
class ExampleGuiExtension:
plugin_id = "example"
display_name = "Example methods"
api_version = "v1"
ui_compat_version = "1" # Existing extension-loader compatibility
nav_items = []
remote_modules = []
router = None
frontend_dir = None
remote_entry = None
tools = (
GuiToolSpec(
tool_id="example/calculation", # Exactly the installed section/name
title="Example calculation",
description="Describe the scientific purpose in one sentence.",
category="Example methods",
groups=(
GuiFieldGroup("Structures", ("molecules",), step="inputs"),
GuiFieldGroup("Protocol", ("temperature", "replicas")),
),
results=(GuiResultView("metrics"),),
),
)
[project.entry-points."caddforge.gui_extensions"]
example = "example_package.gui_extension:ExampleGuiExtension"
For a normal tool, no custom form, submit endpoint, job list, backend panel, log follower, molecular renderer, or React dependency is needed. Existing extension pages remain available through the legacy runtime; new tools use the host-owned flow.
Configuration and setup¶
Every tool uses Inputs → Method → Compute → Review. File inputs come from its
existing InputPort.config_field; nested paths use runtime_selector, including
selectors such as complexes[].protein_pdb. Artifact kinds drive the compatible
previous-job output picker. Exact paths remain visible. Files can also be uploaded
or selected by server path. Uploads are copied into the registered job before execution.
The host generates controls from config_cls.model_json_schema() and obtains actual
model defaults, including factories. Required fields without defaults stay empty.
Examples and CLI templates are not defaults. All fields remain accessible, including
inherited backend fields, nested objects, lists, dictionaries, nullable values, and
explicit false and 0. Free-form dictionaries use a JSON editor that blocks
continuation while its value is invalid. The server validates using the original
Pydantic model and returns field locations; client controls are presentation aids.
Preserve case-sensitive unit symbols in labels (ns, ps, fs, nm, kJ/mol,
mM). The shared renderer corrects title-cased autogenerated labels using original
field-name tokens, including nested fields and review summaries. Explicit schema
titles are retained as authored; supply their units with the correct capitalization.
Groups contain top-level config field names and must reference real fields. Use
step="inputs" to arrange input fields; advanced=True hides auxiliary inputs in an
expander. Unassigned method fields appear in advanced settings automatically. Do not
copy field definitions, validators, defaults, or Slurm settings into GUI metadata.
Workflow preparation should call the shared
caddforge.core.execution.default_run_directory(Path("runs"), job_id) helper when
config.run_directory is unset. Core scopes the caller's configured runs root during
preparation, so CLI and GUI jobs both use the real YYYY-MM-DD/<job-id> directory
without first writing to an unrelated default directory.
The host owns registry_path and run_directory; imported values cannot redirect
execution. Backend controls are shared across tools and use actual availability.
GPU/memory requests remain scheduler options, for example --gres=gpu:1 and
--mem=32G, rather than invented configuration fields. Browser drafts are isolated by
base path and tool; compute profiles are browser preferences. Draft submission keys
survive reloads. Repeated submission with the same key and configuration returns the
same job. Uncertain submissions are retained for reconciliation, not automatically
resubmitted. An edited configuration creates a new submission intent.
Structured protocol settings¶
For an existing dictionary of native-engine overrides, declare
GuiSettingsSpec(config_field, title, describe, managed_fields=()) in
GuiToolSpec.settings. The authenticated host endpoint
POST /api/v1/gui/tools/{section}/{name}/settings/{field} calls the pure provider
with the current config. Do not construct systems, execute engines, or access job
registries while describing settings. The host owns the searchable, grouped,
unit-aware controls, changed/default filters, resets and JSON escape hatch.
Use common only for a small set of essential controls with unambiguous labels.
The host displays these together and initially collapses all remaining protocol
settings, including search, lambda tables and JSON, under Advanced simulation settings.
Changed hidden values remain discoverable through a count and Review changes action;
search and changed-only filtering expand matching groups. Technical field paths and
default notes live in per-field details. Declared advanced method groups also start
collapsed and show changed-value counts. Do not promote arbitrary unassigned fields
when a tool already supplies structured settings, or render empty advanced panels.
Return engine_name, engine_version, source (installed or reference),
warnings, and fields: records with path, label, group, schema, unit,
value, default, changed, common and optional description. Each field schema
must include its referenced $defs. Preserve nullable/zero/false values and
quantity-array shapes. Scalar quantities use <number> <unit>; quantity arrays
use native-compatible {val: [...], unit: "..."} records. Units retain their case.
managed_fields hides redundant top-level scientific controls; it cannot hide
shared compute settings. Preserve imported override literals until edited.
Derive settings from the installed engine's model and the tool's existing default
builder. A versioned reference catalogue may be used only when the engine is absent;
broken installed dependencies must produce an actionable error. Disclose deferred
native validation for reference catalogues. Reuse the tool's original pure validators
and override precedence. Native validation on workers remains mandatory; record
reviewed versions in job.metadata.settings_versions and reject mismatches before
scientific preparation. Browser __gui_settings_versions is draft metadata, stripped
from scientific config. CLI/Python dictionaries and scientific defaults stay unchanged.
Optional schedules records have title, three ordered fields (electrostatics,
van der Waals, restraints), and count_field. The shared table/plot applies all
three columns and the replica count in one patch. Adding/removing windows is explicit;
never interpolate a scientific schedule automatically. Native coupled validation is
still required. Keep independent repeats distinct from lambda replicas.
Optional preparation tools¶
Declare optional upstream work through GuiToolSpec.preparations, using
GuiPreparationSpec. A preparation is an installed, independently usable tool with
its own validated configuration and artifact ports. The host renders its existing
schema inside Inputs, includes its compute policy in Compute and shows both stages
in Review. It is disabled by default. Configuration is carried separately from the
consumer's scientific model; never add GUI orchestration switches to that model.
from caddforge.gui import GuiPreparationSpec
# On the consumer's GuiToolSpec:
preparations = (
GuiPreparationSpec(
id="prepare-structure",
title="Prepare structure",
tool_id="example/prepare",
target_input="protein", # Consumer InputPort name
provider_input="structure", # Provider InputPort name
output_bindings={"prepared_structure": "protein"},
),
)
Bindings map provider OutputPort names to consumer InputPort names. Include every
coupled chemistry record, not just coordinates. Bound outputs are required by the
compiled preparation stage even when a provider declares them optional for standalone
use. Providers must verify applicable artifacts before reporting success and may
explain inapplicable outputs through Result.extra["unavailable_outputs"], mapping
result path keys to plain-text reasons. Core includes these reasons in missing-output
errors; it never substitutes fabricated artifacts or drops a coupled input. compatibility(raw_config) returns
explicit blockers and must tolerate incomplete drafts; defaults(raw_config) may
suggest actual compatible model settings. Both are pure, cheap presentation policies:
no engines, job submission or filesystem scans. Provider absence disables the option
without adding a hard dependency to the consumer package. Providers themselves must
not recursively enable preparation. The initial host supports one enabled preparation
per calculation, with ordinary schema controls rather than a bespoke editor.
Preparation inherits the calculation's complete compute settings, including GPU and
scheduler requests. The user can explicitly select a separate shared profile or
individual compute fields. Never silently downgrade resources. The host validates
both original models, retains inputs and custom assets before dispatch and compiles
prepare → calculate using core's registered pipeline/run coordinator. The
coordinator follows the pipeline orchestration policy; all-Slurm chains use a Slurm coordinator. It uses the
existing pipeline binder, registered child jobs and durable submission intents.
Scientific workers remain registry-disabled; only this explicitly marked local
coordinator may register stages. Do not implement per-tool background threads,
frontend submission chains or another registry.
Parent/child execution ownership differs from source_job_ids provenance. Nested
tool graphs must retain the preparation parent's link on their graph root. Reuse
shared nested cancellation, logs, deletion and parent-owned exports. Progress comes
from the native stages; the coordinator reports orchestration activity without
inventing percentages or an end-to-end ETA. The parent links to calculation results.
Native scientific failure must block downstream submission and preserve diagnostics.
Recovery is explicit and reviewed. A stopped coordinator can monitor known live
stages, reuse completed stages and invoke a native tool's checkpoint recovery through
its verified parent ownership. Unknown acknowledgements block recovery. Reuse is
bound to configuration, retained input and downstream artifact fingerprints; inspection
reads bounded metadata, while the coordinator verifies SHA256 before reuse. Tools
whose scientific dependencies extend beyond Path-valued input ports may expose
input_fingerprint(config) -> dict[str, str] on their tool plugin, returning absolute
file paths and SHA256 digests (for example custom force-field XML Include closures).
Do this in workers, not in GUI rendering. coordinator_only=True on ToolResumeSpec
is reserved for controllers that only monitor existing live descendants; it never
permits duplicate scientific submission. Preserve previous attempts and source files.
Fix Structure is the first provider. Plain MD, GaMD and OpenBPMD bind the repaired PDB and its paired protein-state/link records. Rigid PDB receptor docking binds its repaired receptor before the native converter. Checkpoint/Amber inputs, existing conflicting chemistry/mapping, custom OpenBPMD scripts and flexible or non-PDB docking are blocked. OpenFE integration is deferred. Side-chain protonation and terminal policy are separate choices, and force fields are required explicitly. Existing scientific defaults and engine invocation boundaries remain unchanged.
A standalone provider may offer Use in … result actions. They build reviewable drafts, never submit. Verify producer checksums for every bound artifact, preserve source provenance and retain independent copies at submission so later source-job deletion cannot break execution. Legacy outputs without verification remain manual inputs. Failed diagnostic views never offer successful-preparation reuse.
Specialized steps¶
Use GuiEditorSpec only for interactions that cannot be represented by a configuration
form, such as the RBFE network. Specialized editors extend the common flow between
Inputs and Method; they do not replace compute, review, validation, submission, or job
monitoring. Editor IDs cannot shadow standard steps. Modules are relative JavaScript
assets in the extension's frontend_dir.
GuiEditorSpec("network", "Network", "workbench_network.js",
config_fields=("existing_network_path",))
export function mount(host, context) {
// context.config: current draft
// context.onChange(patch): update and persist draft fields
// context.apiGet / apiPost: base-path-aware, authenticated services
// context.errors: model validation errors
// context.signal: aborted when this editor unmounts
// context.ui: shared plugin_uikit.js primitives
// context.setBusy(boolean): balance each asynchronous operation
// context.setDirty(boolean): reviewed editor changes require saving
return {
update(nextContext) { context = nextContext; },
dispose() { /* abort work, release listeners and owned resources */ },
};
}
Retain an unsaved editor draft locally if a user leaves the step. The reserved
__gui_editor_state draft field carries dirty flags; it is checked and stripped before
model validation and never reaches scientific configuration. Clear the flag only when
a validated scientific artifact has been saved and attached to the draft. Do not turn
pan/zoom or table selection into scientific config fields.
Editor contexts also supply draftId, a stable browser draft identity. Namespace
editor draft storage by this ID so importing or cloning another configuration cannot
restore an unrelated unsaved network.
Scientific planning, atom mapping, edge scoring and input preparation stay in the
plugin. RBFE reuses its existing planner and network serialization; the saved reviewed
network is the authoritative execution input. job_preparer(config, job) may retain
and rewrite scientific input references into the already registered job, before the
shared submission helper persists the final config. It must not submit jobs itself.
config_preparer(data, state_root=...) is an optional deterministic normalization hook;
it runs during validation and must not perform expensive science or submit work.
Source relationships are tool-authored provenance, independent of execution-graph
ownership. Submission must merge native source_job_ids with explicit browser-draft
source IDs, preserving both. A provenance link alone must not trigger copying large
scientific inputs; independent input retention is an explicit draft operation.
Prepared workflow results include analyses linked to their verified primary calculation
stage. Bounded controller maintenance can restore missing terminal source links from
explicit recorded source_job_ids and per-source source_job_id declarations, without
editing scientific configurations/results or inferring IDs from paths.
Results and molecular scenes¶
Static structure results use the shared molecular viewer, loaded on explicit request. They do not invent ligand/pose IDs. Publish input and output structures with distinct labels; exact input, normalized output and chemistry diagnostics stay available in Files. Build large diagnostic tables in workers and expose paginated indexed views. Do not flatten unbounded native records during a web request.
Write canonical Result objects and declare scientific artifacts through OutputPort
and Result.paths. A GuiResultView describes a capability: metrics, table, poses,
images, network, structure, timeseries, trajectory, or matrix. Tables and images can be rendered directly from a path_key, without an adapter.
Use columns=(GuiResultColumn("score", "Score", type="number", unit="kcal/mol"),)
on a table view to declare numeric meaning and units. Undeclared CSV columns are
rendered as strings; the host never guesses units or numerical semantics. A normalized
pose manifest can also be exposed directly this way. Network formats require a
scientific adapter to return the normalized topology described below.
A plugin may supply analysis_adapter(job, result) -> dict to
normalize its scientific output. It must read committed results; it must not start
analysis jobs or change execution status. The host checks commit evidence before
invoking adapters. Scalar metrics default to Result.metrics; missing or non-finite
measurements appear as unavailable, never zero.
Adapter source dictionary:
| Key | Contract |
|---|---|
kind |
metrics, table, poses, or network |
table_path |
CSV artifact within the recorded job directory |
columns |
List of {key, label, type: "string" or "number", unit?, ascending?} |
metrics |
Optional replacement metric dictionary |
warnings |
Actionable strings explaining incomplete or legacy data |
images |
{path, label} records for existing PNG/JPEG/WebP artifacts |
structures |
Up to ten {path, label, format: "pdb", "mmcif", or "sdf"} committed, job-owned structures; 32 MiB preview limit per file |
network |
Bounded {nodes: [{id, smiles, charge}], edges: [{id, source, target, kind, scores}]} |
The host indexes CSV rows in SQLite and pages, searches, and sorts them on the server.
Numeric columns must be declared numeric. Rows need stable unique pose_id values
(for generic tables the host can provide ordinal row IDs). Molecular manifests use:
| Field | Meaning |
|---|---|
pose_id |
Stable unique pose identity; selection is never a table row offset |
ligand_id, ligand |
Stable ligand identity and display label |
pose_rank |
Producer's rank within a ligand; never a global ranking |
pose_file |
Exact chemistry-preserving SDF artifact in the job |
source_record_index |
Exact one-based SDF record index |
receptor_file |
Exact corresponding receptor, including its flexible state |
complex_file |
Optional recorded assembled complex |
coordinate_frame |
Scientific coordinate provenance |
scene_error |
Why an exact scene or receptor is unavailable |
Pose-level values belong to the actual pose. A ligand's best score must not be copied
to every pose. Never pick the first SDF record, guess a receptor from filenames, assign
bonds from atom distances, or silently align a ligand. Flexible docking requires its
per-pose receptor; show a clearly labelled ligand-only view when it is unavailable.
Ambiguous legacy mappings remain unavailable. Docking's pose_manifest.py is the
reference producer and adapter. It is not imported into core or the GUI host.
The host serves job-scoped structure resources, selects the exact SDF record, handles authorization and base paths, and loads the locally bundled Mol* viewer. Scene changes are serialized and stale loads are masked. The original SDF chemistry and coordinates are preserved. Viewer measurements use Mol* controls. No invented contact annotations are displayed. Resource consumers must release viewers, observers and object URLs. The shared viewer combines ligand and matched receptor models for display so native ligand focus can show surrounding receptor residues. Preserve model identities, coordinates and bonds when combining; do not convert the SDF ligand to PDB or load unrelated receptor states. Viewer canvas and controls follow the host theme, with dark as the default and explicit light preferences retained.
Mandatory logging and progress reporting¶
Every GUI-exposed tool must use core JobReporting, worker_logging and
StageProgress; the same records must be available in the GUI and through
caddforge logs <job_id> (including --follow). Scientific protocols supply stages
and trustworthy counters; core owns formatting, heartbeat, persistence and discovery.
The canonical results/progress.json uses schema version 2: job/attempt/session and
stage-instance identity, UTC update/advancement timestamps, stage status and summary,
optional current/total/unit/percent, elapsed time, measured rate and stage-scoped ETA
or an explicit unavailable reason. A heartbeat indicates worker activity, not measured
scientific advancement. Unknown work is indeterminate. Never manufacture whole-job
percentages, estimate scheduler waits, equate stage completion with job completion,
or infer scientific progress from file sizes. Convergence-driven limits must label
ETAs to the maximum duration and retain actual counters when finishing early.
Discrete replica/edge outcomes may be published with reporter.tasks(counts, label=...)
and remain separate from stage counters. The GUI uses registered child jobs when
available, otherwise these recorded unit counts.
Use @reported_workflow(logger_name) on workflow execution methods and
current_reporter() to report stages/counters. The decorator reuses managed reporting
and supplies reporting for direct Python calls. For example:
from caddforge.core.reporting import reported_workflow, current_reporter
@reported_workflow("example_package")
def run(self, job, context=None):
reporter = current_reporter()
reporter.stage("preparation", summary="Preparing scientific inputs")
inputs = prepare_inputs()
reporter.stage("calculation", total=len(inputs), unit="input attempts")
for index, item in enumerate(inputs, 1):
calculate(item)
reporter.advance(index)
reporter.stage("publication", summary="Publishing verified results")
return publish_result(job)
Common runtime settings are progress_update_interval_seconds (5),
heartbeat_interval_seconds (30), and log_sync_interval_seconds (30). Report
stage entry/exit and failures immediately; rate-limit intermediate events. Defaults
and explicit inherited/tool settings must remain available in CLI templates and GUI
configuration. Work counters are monotonic within one stage instance; new stages and
resumed attempts reset timing without discarding retained scientific work.
Fixed-length production stages should provide measured ETAs when engine counters
are available. Prefer observational adapters that preserve integration call
boundaries, scientific settings, analysis cadence, stopping conditions and retry
policies. StageProgress.update(..., measured_elapsed_seconds=...) accepts an
engine's stage clock; initial excludes work from earlier attempts. Optional
measurement_timeout_seconds and measurement_age_seconds suppress ETAs after
engine measurements become old, independently of worker heartbeats. Duplicate
counters must not refresh freshness. Core EngineTelemetry/EngineProgressReader
support bounded invocation-scoped local sidecars, and run_streaming(on_poll=...)
can consume them without changing subprocess results. Keep opaque phases explicit.
A separate engine interpreter may use a staged observational bundle only after
checking its native launcher and observed capabilities. Engine versions alone
must not reject compatible observation. Use bounded isolated behavioral probes
with content-based cache invalidation and guarded runtime measurement validation. Verify staged
source hashes, preserve interpreter/arguments/cwd/environment/import behavior, and
fall back to original execution if observation is unavailable. Do not install
packages into the external environment or retry science after observer errors.
Qualify engine capabilities, delegate original calls exactly once,
and disable unsupported or failed observation without rerunning scientific work.
Use the existing schema-v2 fields and shared GUI renderer; do not add per-tool ETA
endpoints, components or background monitoring jobs.
Core activity events append to worker.log; original stdout/stderr and engine logs
remain available. Register additional persistent engine logs with
reporter.register_log(path, label=..., stream=...) before execution. Use the shared
streaming subprocess runner rather than buffering output until exit. Tool-specific
monitoring endpoints, file-name guessing, background monitoring jobs, and ad hoc
Slurm log followers are prohibited. Parent log discovery includes declared children;
submission-only parents do not terminate CLI following while their children run.
On allocated workers, write snapshots/events to local scratch and synchronize via
core LogSync. Atomic snapshots, retrying copy-back and retained scratch protect
against shared-filesystem outages. Complete final synchronization before reporting
success; preserve logs and failed-attempt evidence. Only committed execution evidence
authorizes terminal job success. Monitoring must never execute scientific analysis.
Continuously updated commit journals must not starve publication. Use core
enqueue_snapshot(..., preserve_pending=True) to keep a pending verified-publication
candidate and coalesce newer updates into one successor. Optional checkpoint cleanup
uses sync-worker maintenance, including idle and bounded final retries. Report cleanup
errors separately from missing scientific artifacts; a cleanup-only warning must not
invalidate safely persisted scientific results. Multi-job tools can opt into parent
metadata results_export_include_children: true, suppressing automatic child exports
and exporting declared child results/logs beneath one parent destination at completion.
Reuse core export locks, destination reservations, inventories and verified copies.
Optional exports are a separate publication state, never a scientific execution stage
that can invalidate or rerun completed science. Commit the execution attempt before
exporting. Use core ExportReport, export_status, request_export, export_results
and MaintenanceController. Durable job-side intents reserve one destination and
retain verified per-file progress. The shared controller adopts old partial exports,
indexes pending work, retries transient storage failures and continues other files
when one component fails. Slurm workers must not access SQLite. Unknown child state
keeps a family export incomplete; committed results and execution attempts take
precedence over stale metadata. Preserve foreign or modified destination files.
The common job export API and caddforge export ID --status expose publication
state independently of calculation status; retrying export never restarts science.
The manual export card is currently hidden in the workbench. Keep shared export
services and automatic/background recovery available; do not add per-tool export buttons.
Plugins replacing large artifacts must declare versioned coordinate/artifact sources,
precision and exact sample mappings. Verify replacements against original scientific
data, then use core plan_retirement/retire_artifacts: replacement files and manifests
must be durably verified before original files become eligible for deletion. Finish
producer scans first. Hash-guarded cleanup is optional, retryable maintenance; exports
omit authorized superseded files even while deletion is pending. Preserve incomplete
run recovery inputs and the storage policy of legacy/resumed jobs. Maintenance shares
resume/deletion locks and must stop when an execution becomes live or is deleted.
Every tool must report preparation, execution, analysis/postprocessing and publication as applicable. Count failed attempts separately from successful calculations and avoid double-counting retries. External engines without validated live counters still need a named stage, heartbeat, live logs and an explicit unavailable ETA. Test direct/API, local/Slurm worker paths, quiet work, failed units, retries/resume, parent/child logs, partial writes, copy-back outages, terminal cleanup, and CLI/GUI agreement.
Job behavior and verification¶
The common job workspace owns Overview, Results, Logs, Configuration and Files.
Interactive status refresh uses core reconciliation with
allow_legacy_finalizer=False; it must never run scientific analysis.
Cancellation uses verified core backend handles and cancels declared execution-graph
children. Logs discover declared child directories and use core LogCursor to handle
partial writes and copy-back replacements. SSE reconnects with a bounded replacement
tail. Retry creates a fresh job and copies old-run-bound inputs through shared core
restart helpers; the old evidence is retained.
Restart inputs use verified content copies for files and closed directory trees;
shared storage need not support timestamp or permission preservation. Core retains
pre-submission preparation errors as failed jobs with worker logs and canonical
results. The GUI records these intents as preparation_failed and returns an
actionable conflict response; the same intent may be retried after the input/storage
problem is fixed. This exception applies only to a confirmed failure before backend
submission. Lost acknowledgements and legacy unresolved intents remain uncertain
and require reconciliation, preventing duplicate live jobs.
Deletion is also host-owned: use core job_deletion for a terminal workflow and
its descendants, never a tool-specific filesystem remover. The confirmation keeps
files by default and explicitly lists directories when file removal is selected.
Active or uncertain tasks block deletion; child jobs are removed through their
parent. Core validates directory ownership, serializes against submission/resume,
checks records again atomically and prevents late status refreshes from recreating
deleted registry entries. Filesystem cleanup failures retain recovery paths.
Cancellation acknowledgement and verified worker exit are distinct. Terminal job
refresh must recheck stale monitoring uncertainty through the current native handle;
clear it only after a terminal backend observation. Deletion rechecks these stale
flags and stale submission phases too. Accepted Slurm jobs can remain recorded
as submitting if cancelled before their worker starts. A terminal observation of
the current acknowledged handle permits deletion; explicit status refresh closes
the cancelled attempt under the submission lock and retains its previous phase
and status in stop_verification. It never creates a scientific result. Missing
handles and unavailable/active execution remain blocked; an unavailable scheduler
is not evidence of absence. The explicit workflow reconciliation action includes terminal
children. Show cancellation actions using server-side status counts across every
descendant, including legacy declarations, independently of the visible task page.
Before adding a tool, verify discovery, schema completeness, defaults/required inputs,
nullable false/zero values, both backend configurations, field errors, retained uploads,
and repeated submission. Verify canonical result loading, numeric paging, duplicate
IDs, exact scene records, missing files, job-scope path checks, flexible receptors,
failed execution, and editor unmount cleanup. Run core tests, affected tool tests, GUI
tests, npm run typecheck, npm run test, and npm run build. Exercise light/dark,
keyboard focus and narrow layouts in a browser. Keep scientific-engine integration
checks separate from these lightweight contract checks.
Conditional groups and result actions¶
GuiFieldGroup.show_when is an optional mapping from top-level config fields to
required values. All entries must match for the host to show that group. Hidden
values remain in the draft and the original configuration model remains authoritative;
conditions never remove scientific settings or bypass validation. Use these groups
for preparation modes and membrane-only parameters instead of a custom form.
Declare a GuiResultActionSpec(id, title, target_tool_id, config_builder) in a tool's
result_actions tuple to continue from published results. The lightweight builder
receives (job, result) and returns target configuration, including exact artifact
pairings. It must not run science, submit jobs or modify source outputs. Validate
manifest versions, size and ownership before reading paths. The host requires a
committed successful result and an exposed target tool, strips inherited compute
and managed settings, and returns a draft. Users review it through the normal
setup flow and select compute resources; analysis should normally use a CPU profile.
The existing submission-intent protocol still owns idempotency.
Derived analyses are independent registered tools, available from the catalog, CLI
and Python API as well as source results. Record source_job_ids as provenance,
never as parent_job_id; cancelling or deleting a source must not cascade into
independent analyses. Related analyses use a bounded registry query (50 per source
result response), separate from execution-graph descendants. A failed repeat parent
can expose its completed children through Tasks; analyze a successfully committed
child rather than pretending the parent has one combined trajectory.
Time series and trajectory results¶
Declare GuiResultView("timeseries") / GuiResultView("trajectory") and provide a
lightweight analysis_adapter. HTTP handlers only read committed artifacts; streaming
analysis, fitting, periodic reconstruction and preview creation happen in a separate
worker job. The adapter may return:
{
"kind": "metrics",
"series": [{
"label": "Backbone RMSD", "x_label": "Time", "x_unit": "ns",
"y_label": "RMSD", "y_unit": "Å",
"points": [[0.0, 0.0, 0], [0.1, 0.7, 0]], # x, y, segment ID
"csv": "/job/results/analysis/rmsd.csv",
}],
"trajectories": [{
"label": "Replica 1",
"topology": "/job/results/analysis/preview.psf",
"coordinates": "/job/results/analysis/preview.xtc",
"atom_count": 1000, "coordinate_bytes": 24000,
"frames": [{"source_frame": 0, "time_ns": 0.0, "segment": 0},
{"source_frame": 10, "time_ns": 0.1, "segment": 0}],
}],
}
Current trajectory capability uses explicit PSF connectivity plus XTC coordinates. Preserve exact atom ordering and a published map back to source atoms. PSF does not encode chemical bond orders; label these as unspecified and retain the producer's original topology record. Never infer connectivity by atom distance or silently use an empty-bond fallback for periodic reconstruction. The shared pinned Mol* adapter retains declared PSF bonds across frames, with a real-bundle parser regression test; retest this adaptation when updating Mol*.
Across an analysis, previews share at most 500 frames. Raw float32 coordinate
bytes (atom_count × frame_count × 12) must not exceed 64 MiB. Server resources
remain job-scoped and authenticated; the client validates decoded frame/atom counts.
Raw full trajectories must never be loaded automatically in the browser. Reuse the
shared viewer loader, theme, resize handling, serialized updates and disposal.
Series may declare a group label (for example a replica ID); the host displays one
group at a time. Producers budget plotted points across sources as well as per series.
Series use finite numeric [x, y, segment] triples, explicit axis labels/units, at most
4,000 plotted points per series and a full-data CSV download. The host rejects larger
previews and invalid resources. This capability supports any numeric XY curve; x need
not represent time. Use the host's shared chart renderer rather than a per-tool plot
or tooltip implementation. The host provides nearest-sample hover inspection in card
and expanded views, touch inspection in the expanded view, and keyboard navigation
with Left/Right and Home/End. Tool metadata supplies all labels and units. Inspection
reports the supplied sample values without additional display rounding or interpolation,
and identifies separate segments with one-based display numbers (payload IDs remain
zero-based). It inspects only the bounded preview, not the full CSV, and never fetches
full scientific data implicitly. Overlapping segments and repeated or unsorted x-values
remain distinct; producers preserve sample order within each segment.
Producers downsample plots/previews independently from scientific analysis stride and never draw across restart boundaries. Source frame indices and physical time are required for playback. Publish full metrics, plots, selections, reference identity, units, source hashes and software versions separately. Do not automatically discard equilibration, join replicas/restarts or infer native thermodynamics from trajectory coordinates. Protein defaults must state both fit and measurement selections; nonprotein systems require explicit scientific selections.
Recorded matrix diagnostics¶
Workers may publish matrices in an indexed result payload: at most four records
per selected view with label, path, rows, columns and csv. The binary is
little-endian, row-major float64, exactly rows * columns * 8 bytes. Dimensions
are positive integers up to 10000. Paths resolve relative to the manifest and
must stay inside the registered job. No scientific engine imports occur in HTTP
requests. The host reads at most 64 by 64 values per matrix using
matrix_row_offset/matrix_column_offset; nonfinite values are unavailable.
The shared heatmap has exact hover/focus values, keyboard navigation, explicit
zero-based indices, tile-local colour scales and a full CSV download.
Scientific meaning and identities belong in worker manifests. For free energies, keep native overall estimates, between-repeat spread, per-leg MBAR errors and standard-state corrections distinct. Label recorded error bands by their actual meaning; do not invent confidence levels or recompute analysis in web requests. Never infer leg/repeat identities from directory names. Failed or prepared-only jobs must not imply a complete binding free energy; missing diagnostics remain explicit.
Guided inputs, indexed results and checkpoint resume¶
GuiInputChoiceSpec(id, title, alternatives) declares mutually exclusive input
alternatives using GuiFieldGroup records. The first field of each alternative is
its presence discriminator. Imported conflicting alternatives require explicit user
resolution. Inactive values are preserved only in browser __gui_input_choices
draft state, stripped before validation/submission; this does not change show_when
semantics or the original model's validators. All alternatives must use distinct,
nonempty field lists.
GuiToolSpec.fixed_fields may pin scientific compatibility fields for a GUI
operation (for example, separate simulation and analysis tools). The host hides
them from editable forms and rejects conflicting imports rather than silently
changing their meaning. The complete recorded schema/configuration stays visible.
Tools must not pin shared backend or job fields; CLI/Python behavior is unchanged.
GuiToolSpec.review_adapter(config) may return bounded rows and warnings from
an already validated configuration. It must not perform science, submit work or
estimate scheduler wait. Defaults still come from the actual configuration model.
Specialized editor contexts include toolId and
mountField(container, path, {getValue?, onChange?, title?}), returning update()
and dispose(). This mounts the host schema/file control, retaining shared uploads,
artifact selection, authorization and busy/error handling. Dispose controls and
abort requests with context.signal. Use the authenticated shared
POST /gui/tools/{section}/{name}/validate-field to validate one scientific model
field while the rest of the job draft is incomplete. Explicitly save validated
editor changes before clearing its dirty flag; never silently add scientific CVs
or histogram bins.
An analysis adapter may return view_index, an owned CSV with view_id,
group_id, label, manifest columns. Each selected manifest is at most 8 MiB,
declares version: 1 and uses the existing adapter payload; resource paths resolve relative to that
manifest and must remain inside the job. The host indexes descriptor rows and
serves only the selected payload through the common analysis endpoint's optional
view_id, group_id, group_offset parameters. Group pages contain at most 50
entries; indexes are limited to 64 MiB. This is for published descriptors, not
scientific computation in HTTP handlers.
XY series may add confidence_interval, a point-aligned list of finite
[lower, upper] pairs or null. The shared renderer includes bounds in its axes,
paints interval bands without bridging segments/missing intervals and exposes
recorded bounds in inspection. Existing triples and adapters remain compatible.
A selected response contains at most 20,000 preview points and each series at most
4,000. Unsupported scientific bins must be omitted and separated by segment IDs.
Two-dimensional profiles may use the common enlargeable image and paginated table
capabilities. Full CSV data remain separate downloads.
terminal_diagnostics=True explicitly permits committed failed/cancelled result
inspection; it does not imply scientific success. Result actions default to
successful sources and may opt into terminal statuses with source_statuses.
Partial ensembles must require explicit completed-replica selection and retain
selection provenance; never silently combine successful subsets.
Checkpoint resume is an optional core tool capability, ToolResumeSpec, from
caddforge.core.job_resume. Plugins provide bounded inspect(job, config) recovery
actions and prepare_config(job, config) scientific resume policy. Declare
execution_graph=True for tools using the shared graph scheduler. Core
plan_job_resume and resume_recorded_job own workspace ownership, native backend
stop checks, review fingerprints, original compute settings, durable idempotent
acknowledgements and attempt history. Graph submission rechecks the review inside
its existing submission lock. Flat tools use the same helpers; core never hardcodes
a method or checkpoint format.
The common authenticated GET /jobs/{id}/resume-plan pages 50 reviewed tasks;
POST /jobs/{id}/resume accepts an idempotency key and reviewed fingerprint.
Resume preserves the registered workflow identity and reuses completed tasks.
It is separate from Retry as new job. Changed attempts, active/uncertain execution
or lost acknowledgements require review/reconciliation, never duplicate submission.
Workers still verify binary checkpoint compatibility and scientific artifacts; no
fallback may silently change scientific behavior. The first GUI implementation
keeps original compute/scientific settings read-only. Slurm stop observations use
bounded scheduler batches, and shared Tasks rows show measured child progress.
Molecular alignment results¶
GuiResultView("alignments", path_key="alignment_manifest_csv") reuses the shared
indexed table and molecular viewer for exact candidate/reference pairs. A normalized
CSV declares unique alignment_id, candidate_id, candidate_file, reference_file,
positive one-based candidate_record_index and reference_record_index, and
coordinate_frame. Optional outcome/error columns describe failed candidates without
inventing structures or scores. Declare numeric score columns explicitly. The worker
must save both structures from the same alignment operation; a representative reference
from another pair is insufficient. The host serves the exact recorded SDF records,
uses candidate/reference labels and preserves coordinates without implicit alignment.
Missing pair evidence leaves the overlay unavailable; legacy tables remain usable.
Distributed tool execution (release candidate)¶
The host exposes BaseConfig.distribution in Compute only for tools declaring
applicable SplitContract.prepare and .collect policies. Review and persisted
configuration use the same Pydantic schema as CLI/Python. Validation selects an
explicit independent input contract; it never infers work from lists or their
lengths. Preparing/chunking libraries happens in the existing durable local
coordinator, outside HTTP requests. Allocated scientific workers stay
registry-disabled. Reuse shared family tasks, progress, logs, cancellation,
reviewed resume, deletion and exports. Large molecular resources may stay in child
directories; combined manifests must preserve exact pair identities and owned paths.
Distributed adapters declare verify(job, config, result) to validate committed
artifacts in workers before reuse. Declare retains_inputs=True only when the
prepared chunks and shared inputs are independent verified copies; recovery may
then proceed after original external sources disappear. Inspection stays bounded
and does not hash scientific files in HTTP requests.
Slurm execution independence (release candidate)¶
Standalone distributed Slurm jobs submit all chunk arrays (or individual jobs) and an all-done collector before reporting submission success. The collector uses the original parent identity and writes the canonical pooled result directly; there is no local pipeline wrapper or completion monitor. Input preparation can still take time before submission is acknowledged.
Pipelines select a Slurm coordinator when all scientific stages use Slurm. Mixed scientific backends are rejected. Generic built-ins run on the coordinator. The coordinator uses atomic execution-family declarations on shared storage, without accessing the central SQLite registry. CLI/GUI reconciliation imports owned child declarations; no status query performs science or advances the pipeline.
orchestration:
backend: auto
compute:
slurm_partition: coordinator
slurm_time: '2-00:00:00'
slurm_cpus_per_task: 1
sbatch_options: ['--mem=4G']
Coordinator defaults are one node/task/CPU, no inherited GPU requests, and the
scheduler's default memory and wall time. Partition, account and environment are
inherited from the first scientific stage; orchestration.compute overrides them.
Set a wall time covering the entire pipeline. Stage compute settings remain
independent. A foreground pipeline command waits for the remote coordinator;
--detach returns after coordinator acknowledgement. Disconnecting the caller
does not stop remote execution.
Compute nodes must provide Slurm client commands, the required plugin environment, and access to shared run/input paths. Missing prerequisites fail explicitly without falling back to the submitting machine. Interrupted or ambiguous submissions retain their evidence and require reconciliation before retrying. Existing recorded job hierarchies are not rewritten automatically.
GUI submission preparation runs in a short-lived local operation. A preparing
submission phase is not acknowledgement of the complete Slurm graph; the operation
exits after dispatch and never monitors scientific completion. Only acknowledged
submissions have the submitting-machine independence guarantee.