Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Architecture

CyteArc uses concrete domain packages and a one-way module-load dependency structure. The public API is exposed through package facades, while reusable computation and storage mechanics live in focused implementation modules.

Dependency direction

Module-load dependencies point toward the earlier layers in this list:

  1. Foundation: storage, matrix, and utils

  2. Data model: metadata, assay, and graph

  3. Domain algorithms: neighbors, embeddings, clustering, trajectory, metrics, features, quality_control, mapping, regulons, perturbation, clones, repertoire, and variants

  4. Import and export: readers, writers, and merge

  5. Orchestration: datastore and datastore._operations

  6. Presentation: plotting

Root facade

The root cytearc package is a public import facade. It does not form another runtime layer and must not eagerly import the implementation graph. Only modules listed by that facade are available as lazy root attributes. Presentation and lower-level algorithm packages such as plotting, clustering, neighbors, and trajectory require explicit imports. This keeps the root surface small and avoids loading optional presentation code.

Plotting and local imports

plotting does not import datastore. Unified plotting consumes a narrow datastore adapter instead of resolving projection paths. Existing heatmap functions still read Zarr-backed values from their duck-typed store and assay inputs. Removing that remaining storage coupling is deferred.

Function-local imports may cross toward presentation when a public method explicitly requests a plot. Examples include RNA feature selection and datastore quality-control helpers. These calls do not create module-load cycles.

Package responsibilities

Foundation

Facade aliases do not change implementation ownership. cytearc.load_zarr is a facade alias for storage.stores.load_zarr.

Data model

Data-model modules may call domain algorithms from the method that needs them. They must not import those packages at module load time.

Domain algorithms

Domain algorithm packages must not import datastore, plotting, or general import/export packages at module load time. A domain that persists an artifact may use a narrow, named storage adapter.

Import and export

Readers parse, writers materialize, and merge combines. Format-specific code belongs in a module named for that format.

Orchestration

DataStore remains the primary workflow API. Its analysis namespaces bind the existing scoped operations in datastore._operations. DataStore.zw opens a workspace group once, as the root group is opened once: its members are read from the store on each access, and CyteArc writes the workspace attributes through it or, after writing them through another handle (a derived assay’s type, a discarded pending assay), opens it again. datastore.namespaces owns these small accessors, and datastore.artifact_accessor owns saved result access and discovery. Public names do not replace persisted operation names, parameters, or input keys. The namespace boundary does not change computation or artifact reuse. Its public class chain is kept for compatibility:

BaseDataStore
  -> GraphDataStore
    -> MappingDatastore
      -> DataStore

Method implementations are grouped by responsibility under datastore._operations:

graph
embeddings
clustering
trajectory
mapping
mapping_reference
quality_control
ambient
cell_calling
features
integration_metrics
presentation
regulons
perturbation_guides
perturbation_effects
perturbation_mixscape
perturbation_associations
perturbation_profiles
clones
lineage_barcodes
recorder_alleles
phylogeny
repertoire
variants

ambient binds the ambient RNA methods of ds.qc: it streams counts, persists soup profiles and contamination estimates, and writes corrected assays, while quality_control/ambient.py owns the computation, after SoupX (Young and Behjati, 2020).

Shared helpers under the same package include enrichment_store, paris_persistence, perturbation_store, which holds the label, read, reference, memory budget, and status helpers that the five perturbation_* operation modules share, cell_samples, which groups the selected cells into samples by their label in one cell column, charging the read to the caller’s memory ledger, for the perturbation operations and hashtag demultiplexing, record_tables, which stores a RecordTable of metadata/records.py under a prefix, such as the contigs and lineage barcode molecules of an artifact, and reads it back, statistical_store, which owns the layout, reuse check, writer, and reader of stored statistical-test results, and cell_barcodes, which every importer uses to join the barcodes of its files to cells: a file’s prefix, suffix and barcode pattern, the canonical order of files by the SHA-256 that identifies each, from utils/digest.py: file_sha256 of a file’s bytes, or what an importer passes as digest (path_sha256, which takes directory_sha256 of a Zarr store’s paths and bytes, for recorder alleles and phylogenies, and the digests of the files that each source’s reader takes for variant counts), and the join’s diagnostics: fileBarcodes, the files’ distinct barcodes by the cell ID they name, unmatchedBarcodes, those that name no cell of the store, and unselectedBarcodes, those that name a cell of the store outside the selection, each kind with up to five examples that show the barcode beside the cell ID it derives. The join tells the two kinds apart by the 64-bit hashes of the store’s cell IDs, which it reads once, a band of chunks at a time, the first time a barcode matches no selected cell; it charges what that pass holds when it starts, so that what an importer sizes from its ledger afterwards leaves room for it, and neither reads nor charges anything for a selection of every cell of the store; it counts a barcode that the pattern does not match apart from one that names the same ID, so the counts do not depend on the order or the chunks of the rows; it charges the hashes of the barcodes of each kind, the store’s hashes and each block that it hashes to the importer’s memory ledger with its lookup of the cells’ IDs. Only unmatched barcodes give the join’s warning, which a reused import gives again from the saved diagnostics. The join also counts each file’s rows, which file_rows gives in the order of an import’s files, and empty_files_rule is the warning that the clone, receptor, lineage barcode and recorder allele imports give from those counts, saved as rowsPerFile or contigsPerFile, naming the files that hold none, files_with_rows picks from them the files that hold rows, which the warnings of files whose rows give the selected cells no clone or no barcode name, and selected_cells_named counts those cells from the join’s saved counts. cell_groups groups the cells of a cell-aligned artifact for the summaries that count within groups: the combinations of the labels of cell metadata columns, of a cell-label artifact, and of the labels that the artifact keeps apart, coded once in natural order, refusing a key column named twice, and counting the grouping’s diagnostics, the measured cells without a clone, the cells with a clone but no group, and the groups; it charges what it reads and builds to the caller’s memory ledger, beside what the caller holds there. The summaries’ tables name each group, and their records hold the groups’ labels apart in group_keys, which clones/groups.group_key_table builds, so a key column may take any name. clone_artifacts plans the clones artifact with the per-cell arrays that its source adds, states what saving it holds from the writer’s own cost, charges it to the operation’s memory ledger before it writes anything, and writes and logs it for every operation that saves clones, with the operation’s diagnostics and its own, cellsWithClone and largestCloneShare, so clone import, clones from a cell column, barcode clones, clones called from variants, allele clones and the clones of a phylogeny’s cut share one artifact contract. clone_steps holds the steps that the clone operations repeat, each charged to the operation’s ledger: integer codes read whole as int64, the IDs of a cell-aligned artifact’s cells, the labels of clones ranked by size, and the words for an import’s files; it also tells from a lineage barcode import’s saved counts whether its rows of selected cells give none of them a barcode, in words that the barcode import’s warning and the clone summaries’ refusal of clones called from such barcodes share. Operation mixins have no runtime inheritance from datastore facades, no __init__, and no runtime imports of sibling operation mixins. TYPE_CHECKING imports of siblings are allowed. Reusable algorithms must be placed in their domain package before being exposed through a datastore method.

datastore.pipeline_accessor exposes the pipeline recipes rna, atac, adt, multimodal, and perturbation. Each recipe method is thin: it passes its keywords to a resolver in datastore._pipeline.recipes, one module per recipe (rna.py, atac.py, adt.py, multimodal.py, and perturbation.py, with the steps that the single-modality recipes share in common.py). A resolver checks the call against the store without writing anything and returns a RecipePlan: the recorded recipe name, the assay, the label, the configuration that the run records, and every stage in order as a PlannedStage. It checks the keywords, the columns and cells, the stage combinations, and every stage setting with the check that the stage’s method runs on it before it reads anything, so a setting that the method refuses raises the method’s message, after the stage’s name, before the run starts; limits that depend on the data are checked by each stage’s method when the stage runs. A planned stage without an action is recorded as skipped, and its on_skip hook gives later stages the inputs that they would have read from it. _pipeline/stages.py builds the stages that several recipes share, from the input snapshot and filtering through highly variable genes, normalization, PCA, Harmony, the graph, the embeddings, Leiden, Paris, cluster selection, and membership strength to doublets and markers. The perturbation recipe runs the RNA recipe’s stages from filtering to Harmony, so a run with an RNA run’s cells and settings reuses that run’s artifacts, and adds one stage per DataStore.perturbation method. The input snapshot freezes each group of cell columns that a stage reads apart, the QC columns of filtering in cell_snapshot and the others in capture_snapshot, harmony_snapshot, doublet_sample_snapshot, and column_snapshot, so that a column one stage reads never enters the provenance of another stage’s result. _pipeline/settings.py checks each stage keyword against the keywords of the stage’s method, and its settings with the settings function that the method calls, which the method’s domain module holds, such as doublet_settings of quality_control/doublets.py, ann_index_settings of neighbors/index.py, and the *_settings functions of perturbation/, and _pipeline/filtering.py resolves and applies QC filtering. Each recipe module also holds recorded_call, which turns the configuration that its runs record back into its keywords for PipelineRun.settings, with the shared inverses cells_argument of _pipeline/stages.py and filtering_argument of _pipeline/filtering.py, so a recipe that changes what it records changes its recorded_call beside it. A stage recorded under its keyword’s name in config["stages"] passes through recorded_call unchanged, so a new stage or stage setting needs no change there. A run recorded before a keyword or setting existed leaves it out of its settings, and the recipe gives it its default, so a new keyword’s default must reproduce what runs did without it, such as False for a new optional stage. The normalization method is the exception: recorded_settings gives a run recorded without it the normalizer that its saved normalized values record, which recorded_normalizer of _pipeline/normalizers.py reads. A new recipe adds a resolver module and a recorded_call, and reuses the rest.

One generic executor, _pipeline/executor.py, runs every plan. Every stage reads the normalizer from its assay’s normMethod, so a plan’s normalizers names the normalizer that the run applies to each assay, which _pipeline/normalizers.py resolves from the normalization method setting, and the executor and the planner make it the assay’s normMethod while the stages run and give the session’s back however they end. The executor creates the run record, passes a RunState that holds the refs of the stages that ran so far from stage to stage, and completes the run with its outputs and the frozen cell and feature fields that _pipeline/fields.py builds from them. The ledger, _pipeline/ledger.py, runs one stage at a time in plan order on the calling thread, and each stage record is terminal before the next stage starts. A record holds the stage’s artifact-plan receipts, wall time, sampled memory, and the warnings that CyteArc logged or issued while it ran, and a completed stage’s record also holds a summary that _pipeline/summaries.py computes from the stage’s artifacts and the diagnostics they saved, so a reused stage reports what a computed one would; an output of a kind without a summary of its own reports its saved diagnostics. _pipeline/events.py delivers each run’s PipelineEvent values in order, on the run’s thread, to its callback and to the listeners that pipeline_listener registered in the calling context. The event types name datastore.pipeline_accessor, where users import them, as their module, so they are documented and pickled there. While a stage runs, CyteArc’s log records carry the run ID and stage, its progress bars forward throttled stage_progress events, and its Zarr reads and writes decode and encode on a pool of the store’s workers, as Zarr internals describes under “Memory controls”. A CancellationToken passed as cancel requests shutdown on the run’s shutdown token, so the run stops at its next shutdown checkpoint, as it does after a signal, records the run as interrupted, and raises PipelineCancelled. The ledger records the running stage as interrupted when the cancellation cut its work short, and as completed when its work had finished. The shutdown token keeps the first request and the first signal apart, so a signal after a cancellation does not escalate and takes its usual effect once the interrupted run is recorded.

The reusable bounded silhouette comparison lives in metrics.cluster_selection. Its datastore adapter, _pipeline/cluster_selection.py, validates graph-coordinate lineage, scores the Leiden candidates in the coordinates that built the graph (PCA, LSI, or Harmony coordinates, or normalized values), and persists the immutable decision. metrics.cluster_selection is not part of the public cytearc.metrics facade. datastore.pipeline_run exposes the narrow durable PipelineRun handle and its frozen cell and feature views. Pipeline execution creates immutable artifacts and a strict run/stage ledger under pipeline/runs; it does not write live metadata. DataStore-owned plotting, marker loading, and export consume narrow frozen-run views. Completed runs can be reopened by their immutable label or exact run ID.

_pipeline/planning.py answers DataStore.pipeline.plan, which reports what a resolved recipe would reuse and compute without executing it. It runs each stage’s action inside artifact_forecast_scope of storage/artifact_writer.py, where plan_artifact reuses as it always does but, instead of planning an artifact to compute, raises ArtifactComputationRequired with the reason: no artifact of the operation, the closest one and the parameters and inputs in which it differs, which nearest_stored_artifacts of storage/artifacts.py finds, a superseding revision, an interrupted artifact, missing diagnostics, or a failed payload check. An operation therefore stops before it computes or writes anything, and the plan learns each reused stage’s refs from the operation’s own planning, with the identities and reuse checks that a run uses. A PlannedStage declares the run-state keys that its action or skip hook reads, inputs, and adds, outputs: artifact keys, COORDINATES and FEATURE_NAMES for those values of the RunState, and keys of its extras. The plan follows them to report a stage that reads what a computed stage would produce as waiting on that stage, without running it, and refuses an action that reads or adds an artifact key that it does not declare, so a new stage declares both. Each computed stage’s estimate comes from the stage records of the latest earlier run of the same recipe and assay that computed the stage.

datastore.trajectory_plan answers TrajectoryAccessor.plan, which plans the trajectory calls made in its block. datastore.namespaces binds the trajectory calls that save results through planned_call, which runs each of them in the same artifact_forecast_scope while a plan is open, and returns the call’s plan in place of a ref when it would compute; a call that takes such a plan is recorded as waiting on it, as _pipeline/planning.py records a stage that reads what an earlier stage would compute. The pipeline accessor refuses to run, rerun or resume a recipe while a forecast is active, since a run writes its records outside plan_artifact.

A recipe called with run_until and PipelineAccessor.resume run through the same executor. The executor pauses a run once the stage that run_until names has completed, with pause_pipeline_run_record of storage/pipeline_runs.py, which fails the run when another run has committed its requested label and otherwise closes the process’s segment of the run record. resume rebuilds the plan from the recorded settings with the resolution that plan uses, and the executor replays each finished stage’s action inside artifact_forecast_scope, as the planner runs it, and requires the refs that the stage’s record names, so the replay restores the RunState without computing or writing anything. Only then does resume_pipeline_run_record claim the pause, with an append-only set_if_not_exists key for each pause, and the ledger starts at the first stage left to run. PipelineAccessor.end_paused ends a paused run that will not resume through end_paused_pipeline_run_record, which claims the pause with the same key and records the run as interrupted, so a resume and an end of one pause cannot both go ahead. The executor and resume_pipeline_run_record read the run record again before the replay and before the claim, and a record that holds more segments than the pause that the process read, or that is no longer paused, means that another process resumed or ended the run.

_pipeline/description.py answers PipelineAccessor.describe, which needs no store. It describes each stage keyword of a recipe’s signature from what resolves the recipe: the settings of STAGE_SETTINGS, and the annotations and defaults of the public methods that STAGE_METHODS of _pipeline/settings.py names for each stage, the method that the stage runs first. It declares the few settings whose default the recipe sets itself, the keys that configure the recipe, such as the Leiden partitions of DEFAULT_LEIDEN_PARTITIONS and MULTIMODAL_LEIDEN_PARTITIONS, and the defaults that a recipe fits to its data or call, stated as rules, such as the ATAC recipe’s prevalent_peaks top_n. A stage setting that no method of its stage takes and that declares nothing cannot be described, which tests/test_pipeline_description.py checks for every recipe.

A cell field may read an artifact of any assay, since every assay shares cellData; the cell view checks the artifact’s recorded cell_selection against the run’s. A feature field must belong to the run’s assay, whose featureData the feature view covers. The executor opens both views on the record that it is about to complete, so a field that a view refuses fails the run at finalize, before complete_pipeline_run_record claims the label.

Presentation

plotting/ owns the reusable plotting APIs. It has no import dependency on datastore. The removed cytearc.plots, cytearc.plotting._legacy, and DataStore.plot_* APIs must not be restored. New plots should return the established plotting result types, accept documented data contracts, and use narrow adapters instead of adding storage-path knowledge. Figures of clones, receptors and variants that split cells by group take the groups from one store adapter, _figure_groups, over the grouping of the clone summaries in datastore._operations.cell_groups, so a figure groups cells by several columns, a label artifact and the labels its artifact keeps apart as the summaries do; a figure of a summary takes the record the summary returns rather than computing it again, and reads its groups’ labels from the record’s group_keys. Beside a table’s own columns, a figure holds groups and fates as values, never as column names. The figures of clones, immune receptors, lineage records and variants draw through the private charts of plotting/_charts.py, draw_bars, draw_lines, draw_histograms, draw_matrix and draw_tree, which draws a collapsed tree as one path of branches and one path of wedges for each color, so its memory grows by a few numbers for each node drawn, beside capped_counts, which bins counts for a bar chart, log_values, which labels a log axis of values that need not be whole, and legend_of, the legend of a side legend that a figure draws itself, and the palettes of their fixed vocabularies in plotting/_style.py; variants.genotypes draws its embedding panel through the categorical drawing and draw order of plotting/embedding.py; the charts return each legend with its scale for _figure.finish_plot to report, so compose_results can draw a legend that several figures share once; plotting/_groups.py’s PlotGroups gives each figure its groups and their colors, and plotting/_clone_names.py what the figure calls the clones and how it labels them, through the store’s _clone_figure_nouns and _clone_figure_labels.

DataStore.plots is a thin, store-bound accessor over the canonical store-first functions in cytearc.plotting. The accessor imports concrete plot implementations only when a method is called, so this convenience namespace does not reverse the dependency from plotting to datastore.

Public facade policy

Lazy and eager facades

The lazy facades in cytearc, features and its subpackages, readers, writers, merge, utils, neighbors, clustering, embeddings, trajectory, regulons, and plotting are architectural boundaries, not temporary deprecation shims. Their documented 1.x exports preserve stable import paths and defer optional or expensive implementations until an export is accessed. All of them use one private helper, cytearc._facade: an export wins over a same-named submodule, resolving an export never replaces a bound value, and only readers, writers, merge, and utils present the objects they own under the facade’s __module__. cytebase is a plain module that keeps the earlier public names of the example downloads, re-exported from datasets, through CyteArc 1.x.

The assay, mapping, matrix, metadata, metrics, and quality_control package initializers are eager domain facades. API reference pages and public contract tests define which of their exports carry compatibility guarantees.

Reloading a lazy facade clears cached exports before resolving them again. This keeps reload behavior deterministic for tests and interactive work.

Private facade exports used by repository tests are patch seams, not additions to the documented user API. New production code should import its canonical implementation directly unless it intentionally needs a public patch seam.

Invalidation policy

Operation revisions are the one explicit mechanism that stops CyteArc from reusing stored results. storage/operation_revisions.py gives each operation that has revisions an append-only tuple of them; an operation that is not listed is at revision 1. Planning records a revision in provenance only when it is 2 or more, so an operation without revisions keeps its identities. A stored artifact that differs from a request only in its revision is superseded: it is never reused, it stays listable, loadable, and traceable, and lineage reports mark it stale. Changing recorded parameters or inputs is not an invalidation mechanism. Operation revisions holds the decision ladder.

Stored data and API contracts

CyteArc validates persisted data and public arguments against the following contracts:

Compatibility exists only where a current public facade or an explicit file-schema test says it does. There are no silent migrations, implicit compatibility branches, or forwarding shims for retired internal modules. Incompatible stores and artifacts fail with an actionable error.

Placement rules

Use these rules when adding code:

  1. Put Zarr mechanics in storage, blockwise matrix behavior in matrix, and generic operational helpers in utils.

  2. Keep metadata and assay focused on table access, normalization, and persistence.

  3. Put reusable computation in a concrete domain package.

  4. Keep domain packages independent of datastore and plotting.

  5. Use a named storage adapter when a domain persists an artifact.

  6. Put parsing in readers, materialization in writers, and combination in merge.

  7. Keep plotting free of datastore imports and use narrow adapters for new storage-backed inputs.

  8. Add compatibility only at an existing public facade.

  9. Use a concrete biological or computational package name. Do not introduce catch-all packages such as core or analysis.

  10. Record a change to what an operation computes as an OperationRevision in storage/operation_revisions.py (Operation revisions), with a test of the revision; never change recorded parameters to invalidate results.

Architecture boundaries are enforced in tests/test_import_architecture.py. Public imports, result records, facade behavior, and wheel contents have separate contract tests.

Accepted and deferred decisions

Accepted

Deferred

Deferred to a later structural phase:

Rejected

Implementation references

Read Zarr internals for the on-disk implementation boundary and the public API reference for current contracts. Use Contributing for the test, documentation, and review workflow before making a change.