Most data teams do not lose time writing analysis code. They lose time explaining, months later, why a directory of outputs cannot be regenerated. A script grew a for loop, the loop grew a shell call, the shell call grew an environment name, and now nobody remembers which CSV fed which plot. Snakemake exists to remove exactly that class of pain: you declare rules with inputs and outputs, hand it a target file, and it works backward to the commands that produce it.
The interesting part is that Snakemake does this without a compiler and without a database of your history. It is a Python program that reads your Snakefile, rewrites it into Python, discovers a dependency graph at runtime, and then decides which jobs to run next under whatever cores and memory you allow. This tour follows that path through the real source tree of the main branch, from the tokenizer to the scheduler.
The payoff for reading the code is practical. Once you see that the graph is materialised from file patterns rather than declared upfront, and that job order comes from a solver that can quietly fall back to a greedy heuristic, the error messages and the “why is it running that first” questions stop being mysterious.
The end-to-end path: a Snakefile is parsed into Python, registered as rules, expanded into jobs, wired into a DAG, then scheduled and executed.
Reading the overview from left to right:
- TokenAutomaton, L100 turns the Snakefile into a stream of decisions over Python tokens; there is no grammar file, only a state machine over
tokenizeoutput. - parse, L1358 drives that automaton and returns a joined Python compilation plus a rule count, which is what the workflow ultimately executes.
- Workflow, L162 is the central object that owns settings, the rule registry, the source cache, and a lazily built DAG reference.
- _build_dag, L1255 is the short method that actually constructs the graph by awaiting the DAG initialiser.
- DAG, L109 holds dependencies, the need-run set, and the ready-job set that the scheduler consumes.
- toposort, L94 is a thin wrapper around the standard library’s
graphlib.TopologicalSorter, yielding batches of ready nodes. - Job, L192 is the concrete, expanded unit of work: resolved inputs, outputs, params, threads, and resources.
- JobScheduler, L65 runs the scheduling loop, respects global resources, and submits selected jobs to an executor.
- Scheduler, L84 is the integer-programming selector that can fall back to the greedy scheduler when it cannot find an optimal assignment.
The detailed view adds modules, checkpoints, target aggregation, shell and resource handling, the greedy fallback, and the individual executors.
A Snakefile is Python, rewritten
The first surprise is that Snakemake does not parse a Snakefile the way a build system parses a Makefile. It runs Python’s own tokenizer over the file. In parser.py, the Snakefile class opens the source through the workflow’s source cache and sets up tokenize.generate_tokens at line 1332, so the raw material is a stream of TokenInfo objects rather than characters.
On top of that stream sits a hand-written automaton. TokenAutomaton at line 100 tracks indentation, dedents, and the current state, while subclasses such as Rule, Module, Include, and Checkpoint describe what each top-level keyword should do. When the automaton reaches a rule block, it rewrites the block into an ordinary Python function decorated for later execution. The parse function at line 1358 simply consumes the automaton, records original line numbers into a map, and joins the emitted fragments into one compilation string. That line map matters later: when a rule raises, Snakemake can point back to the line in your Snakefile rather than to generated code.
Because the parser is a state machine rather than a formal grammar, it has to cope with Python’s moving syntax. A dedicated parse_fstring method handles the f-string tokenisation changes introduced by PEP 701, which is a good reminder that this is real, maintained engineering and not a cute metaprogramming trick.
Rules become jobs, jobs become a graph
Once the rewritten file is executed, each rule call lands in the Workflow. The Rule class at line 100 of rules.py stores the rule name, line number, wildcard constraints, and the input, output, params, and resource declarations. Rules are patterns, not instances: an output like results/{sample}.bam contains a wildcard that can match many concrete files. The expansion helpers such as expand_input at line 865 and expand_output at line 1016 turn a pattern plus a wildcard dictionary into the concrete file names a job will actually touch.
Files themselves are wrapped by IOFile. The IOFile factory at line 250 of io/__init__.py returns an instance of the internal _IOFile string subclass defined later in the same module. Because it is a string, it flows through ordinary path code; because it carries a rule reference and a compiled wildcard regex, it can also be matched against other patterns. This dual nature is why Snakemake can build a graph from glob-like declarations without asking you to enumerate every sample.
The DAG class does the assembly. It scans target files, walks backward through rules that could produce them, and records dependencies between instantiated Job objects. _build_dag in workflow.py at line 1255 shows the entry point: it logs “Building DAG of jobs…”, awaits dag.init(), then updates checkpoint dependencies. Checkpoints are the dynamic branch: their outputs are not known until they run, so the graph can be rebuilt mid-execution. Topological order is not reinvented; toposort at line 94 delegates to graphlib.TopologicalSorter and collects batches of ready tasks. The ready_jobs property at line 595 exposes the subset that currently has all inputs satisfied.
From ready graph to running process
The “From ready graph to running process” section is where the build facts live. A Job is a big object: jobs.py defines Job at line 192 and gives it slots for the rule, the DAG, wildcards, inputs, outputs, params, log files, threads, and resources. Before execution it is prepared asynchronously; its inputs are checked against modification times, its outputs are staged, and its resources are evaluated. The local executor at line 71 of executors/local.py receives that job in run_job at line 102, submits it to a thread pool, and runs the prepared command through the shell class at line 67 of shell.py, which tracks child processes and formatting.
Resource accounting is not bolted on. The Resource class at line 462 of resources.py models a named value that can be an integer or a string such as a memory quantity, supports constraint checking, and parses human-friendly sizes. Threads are a resource with well-known semantics, which is why declaring threads: 8 both makes eight cores unavailable and exposes {threads} to the command.
The scheduler is the conductor. JobScheduler at line 65 builds a greedy scheduler through the plugin registry and also constructs the main selector at lines 166 to 169, keeping a greedy select_jobs around precisely so it can fall back. The MILP Scheduler in scheduling/milp.py formulates selection as a PuLP integer program. Its objective, starting at line 148, is deliberately layered: job priority dominates core load, core load dominates temporary-file removal, and instant removal dominates temporary-file size. Constraints at line 183 enforce that the sum of chosen jobs’ resource requests stays within the available resources. The solver is given a ten-second budget by default in _solve_ilp at line 242, and if it is infeasible or times out the code logs a warning and returns None at lines 216 to 238, which pushes the scheduler back to the greedy path.
The scheduling trade-off
A greedy scheduler is easy to reason about: sort ready jobs by priority and take them until resources run out. It is also myopic, and temporary files can accumulate because the ordering that would delete them fastest is never found. The integer program improves on that by considering the whole ready set at once and encoding the temporary-file preference directly in the objective. The cost is that an ILP is not guaranteed to be fast, so Snakemake bounds it and treats failure as a normal condition rather than an error.
This design explains behaviour you may have seen. On a laptop with a handful of jobs, the greedy selector and the solver usually agree. On a large cluster run with many ready nodes and tight memory, the solver can pick a different subset, and occasionally you will see the “falling back to greedy scheduler” warning. That warning is not a crash; it is the system honouring its promise to keep making progress when the optimiser cannot.
The executor boundary is equally deliberate. Only local.py, dryrun.py, and touch.py live in the core tree; cluster, Kubernetes, and cloud backends are distributed as separate packages that implement the executor-plugin interface. The base pyproject.toml depends on snakemake-interface-executor-plugins and snakemake-interface-scheduler-plugins, so the core stays small while the ecosystem grows around it. Environment deployment is kept modular too, with the deployment module handling Conda-compatible specifications; the project also develops itself using pixi lock files, and conda-style environments remain the familiar way to pin the solver stack, with fast alternatives such as mamba in the broader Conda ecosystem.
Honest Limits
This is a 10.0.0 alpha codebase, and the tree shows the weight of experience. dag.py alone is 3,471 lines, workflow.py is 2,520, and cli.py is 2,467; the core is powerful but not petite, and newcomers will spend time following calls across a few very large modules. The parser’s token-automaton approach is pragmatic, but it is also why unusual Python constructs need special cases like the f-string handling, and why editor tooling cannot fully understand a Snakefile without executing it.
There are further trade-offs worth stating plainly. The MILP path depends on PuLP and an available solver, and its ten-second default is a real ceiling rather than a formality. Graph construction is largely dynamic, so a subtle wildcard or checkpoint interaction can change the graph after the first jobs start. And because the ecosystem is now plugin-based, behaviour differs between the in-tree local executor and external cluster executors; reading only the core tree will not tell you the whole story of production execution.
None of this undermines the central idea. Snakemake earns its place by making the relationship between files explicit and by refusing to guess when a target is already up to date. The parser, the DAG, and the scheduler are three honest layers of that promise, and each can be read in isolation. Start with Enjoyed this post? Never miss out on future posts by following us parser.py if you want to understand the language, dag.py if you want to understand dependencies, and scheduling/milp.py if you want to understand why your jobs started in that order.