What actually happens during Rust CI?
From the series Rust CI from first principles, part 2 of 3
- Reading time
- 15–20 min
- Level
- Intermediate–advanced
- Prerequisites
- Rust, Cargo and CI basics
Introduction: What happens when you run cargo test?
In the first article of this series, we explored the fundamentals of Rust continuous integration. We introduced the tools that make Rust CI so powerful, from the compiler’s type and ownership checks to Clippy and automated testing. We also built a simple CI pipeline using GitHub Actions.
But what actually happens when that pipeline runs? Consider these familiar commands:
cargo check
cargo clippy
cargo test
cargo build
They look straightforward. Yet behind them is a sophisticated system responsible for resolving dependencies, planning compilation, scheduling work, checking types and ownership rules, generating machine code, and executing tests.
That system has two principal components: Cargo is Rust’s package manager and build orchestrator. It decides what needs to be compiled, in what configuration, and in what order.
rustc is the Rust compiler. It takes individual Rust crates and performs the analysis and compilation needed to produce metadata, libraries, or executable code.
Understanding how these components cooperate is essential if we want to understand Rust CI performance. In this article, we’ll follow a small Rust workspace through a CI run, from source checkout to test execution. Along the way, we’ll investigate three important questions:
- How does Cargo decide what work needs to happen?
- What actually happens inside the Rust compiler?
- Why do
cargo check,cargo build,cargo clippy, andcargo testperform different amounts of work?
By the end, you’ll have a mental model of the Rust compilation pipeline that will help you understand everything from everyday compiler errors to advanced CI optimizations.
1. A simple Rust workspace
Rather than discussing compilation entirely in the abstract, let’s begin with a small example. Imagine we’re developing a Rust application containing two crates. The first is a library providing some shared functionality. The second is a command-line application that depends on that library.
Our project looks like this:
example-workspace/
├── Cargo.toml
├── Cargo.lock
└── crates/
├── core/
│ ├── Cargo.toml
│ └── src/
│ └── lib.rs
└── app/
├── Cargo.toml
├── src/
│ └── main.rs
└── tests/
└── greeting.rs
The workspace manifest is simple.
Cargo.toml
[workspace]
members = [
"crates/core",
"crates/app",
]
resolver = "2"
Our library crate has the following manifest.
crates/core/Cargo.toml
[package]
name = "ci-core"
version = "0.1.0"
edition = "2021"
And a small implementation.
crates/core/src/lib.rs
/// Returns a friendly greeting.
///
/// ```
/// assert_eq!(
/// ci_core::greet("Ferris"),
/// "Hello, Ferris!"
/// );
/// ```
pub fn greet(name: &str) -> String {
format!("Hello, {name}!")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_greeting() {
assert_eq!(greet("Rust"), "Hello, Rust!");
}
}
Our application depends on that library.
crates/app/Cargo.toml
[package]
name = "ci-app"
version = "0.1.0"
edition = "2021"
[dependencies]
ci-core = { path = "../core" }
Its implementation is equally simple.
crates/app/src/main.rs
fn main() {
println!("{}", ci_core::greet("Rust"));
}
We can also add an integration test.
crates/app/tests/greeting.rs
use ci_core::greet;
#[test]
fn test_application_greeting() {
assert_eq!(greet("World"), "Hello, World!");
}
That’s our entire example. It’s deliberately small, but it contains enough structure to demonstrate several important compilation behaviours. We have a workspace, two packages, a dependency between crates, unit tests, integration tests, and a documentation test. We’ll use this same workspace throughout the article.
To reproduce the examples, create these files with a recent stable Rust toolchain and run cargo generate-lockfile from the workspace root. The examples were checked with Rust 1.97.1. Commit Cargo.lock to use the --locked workflow from part 1.
2. From GitHub Actions to Cargo
Let’s imagine we’ve pushed a change to GitHub. Our CI pipeline starts and executes:
cargo test --workspace
Before this command runs, the CI system has already performed some preparation. It has provisioned a runner, checked out our repository, and prepared the Rust toolchain. These activities matter for overall CI performance, but they happen outside the Rust compilation process.
Once the runner invokes Cargo, responsibility shifts to Rust’s build tooling. It’s useful to distinguish these responsibilities.
- GitHub Actions
- Prepare runner and toolchain
- Invoke Cargo
- Resolve project and plan work
- Run rustc compilation jobs
- Execute tests
- Return results to CI
GitHub Actions doesn’t ordinarily decide which Rust crates need compiling. It doesn’t understand our workspace’s internal dependency graph or know which compiler artifacts can be reused. Instead, it invokes Cargo and relies on Cargo to manage those decisions.
This distinction will become important when we explore CI optimization. There are opportunities to improve performance at the CI orchestration level, but there are also opportunities within the Rust build process itself. They’re different problems.
3. How Cargo understands your project
When Cargo starts, its first task is to understand what we’re asking it to build. It reads the relevant Cargo manifests and determines which packages, dependencies, targets, and features are involved.
Packages, crates, and targets
These terms are closely related, but they aren’t interchangeable. A package is the unit described by a Cargo.toml manifest. A crate is a Rust compilation unit: a library or binary target that rustc compiles.
A single package can contain multiple compilation targets. For example, our ci-app package contains a binary target and an integration-test target. Our ci-core package contains a library target. Cargo can also compile that library in a special configuration for unit testing.
Consequently, a package doesn’t always correspond to exactly one compiler invocation. This is our first important insight. The number of packages in a Rust workspace doesn’t directly tell us how many compilation jobs Cargo will perform.
Dependency resolution
Cargo also needs to understand which packages depend on which others. In our example, ci-app depends on ci-core. The relationship is straightforward:
The direction of the arrow indicates a dependency, not execution order. Before Cargo can compile our application, it needs the appropriate compiled output from the library it depends on. For a real application, this graph can contain hundreds or thousands of packages.
Cargo must also account for dependency versions and selected features. If we introduce third-party dependencies from crates.io, Cargo consults the manifests, resolves the dependency requirements, and uses Cargo.lock to preserve the selected versions.
Inspecting the dependency graph
We can see our workspace’s dependency relationships by running:
cargo tree
This displays a dependency tree for the selected packages. For projects with more complicated feature configurations, we can also run:
cargo tree -e features
Cargo’s metadata command provides structured information about the workspace and its resolved dependencies:
cargo metadata --format-version 1
These tools are useful for understanding what a project depends on. But there’s an important limitation. The package dependency graph is not the complete compilation graph.
Cargo still needs to determine exactly which compilation jobs are required for the command we’ve requested. That’s our next subject.
4. From dependencies to compilation jobs
When we run:
cargo build --workspace
Cargo needs to compile our library and application. At a conceptual level, the process looks like this:
- Compile ci-core
- Compile ci-app
But now suppose we run:
cargo test --workspace
The situation becomes more complicated. Cargo may need to compile:
- The library in its normal configuration.
- The library as a unit-test executable.
- The application as a test target.
- The application’s integration-test executable.
- Other required artifacts and documentation tests.
Some of these compilations can share dependencies. Others require distinct compilation configurations. The reason is that a crate’s compilation isn’t determined solely by its source files.
Introducing Cargo compilation units
Internally, Cargo represents build work using compilation units. A unit identifies a particular piece of compilation work, incorporating information such as its target, compilation mode, profile, selected features, and compilation platform.
For example, compiling a library normally is not necessarily the same unit as compiling that library with the Rust test harness enabled. Similarly, compiling a crate for the host architecture isn’t necessarily equivalent to compiling it for a different target architecture.
This means Cargo can create multiple compilation units associated with the same package. And those units form their own dependency graph. For our example workspace, a simplified portion of the test compilation graph might look like this:
Notice that the unit-test compilation of the core library is separate from its normal library compilation. That’s because the test harness changes how the crate is compiled.
The diagram is intentionally simplified. It isn’t a literal dump of Cargo’s internal unit graph. Cargo also needs to account for additional build modes, dependencies, and test execution steps.
On nightly Cargo, an unstable --unit-graph feature can expose the internal compilation-unit graph as JSON. Unlike cargo tree, it represents the work associated with a particular Cargo command.
Scheduling compilation work
Once Cargo has established the necessary relationships, it can schedule the jobs. Dependencies must be available before compilation jobs that consume their outputs can proceed.
But independent jobs can execute concurrently. For example, if our application depended on two unrelated libraries, Cargo could potentially compile them in parallel. This is one reason Rust compilation can use multiple CPU cores effectively.
However, parallelism is constrained by the dependency graph. If crate B depends on crate A, then the relevant output of A must exist before B can finish compiling. Adding more CPU cores cannot eliminate that dependency. We’ll return to this observation when discussing CI performance.
5. How Cargo knows whether compilation is necessary
Here’s an interesting question. Suppose we run:
cargo build --workspace
And then immediately run the same command again. Why is the second invocation normally much faster? The answer is that Cargo tracks the freshness of compilation units.
Fresh and dirty units
For each required compilation unit, Cargo determines whether its existing outputs can be reused. A unit that is up to date is considered fresh. A unit that needs additional work is considered dirty.
If we haven’t compiled the workspace before, the necessary artifacts won’t exist. Cargo therefore needs to perform the required compilation work. But after a successful build, Cargo can often reuse those artifacts on subsequent invocations.
Fingerprints
One of Cargo’s mechanisms for tracking freshness is its fingerprinting system. Conceptually, a fingerprint records information about the configuration and dependencies associated with a compilation unit. Cargo also uses dependency information and filesystem modification timestamps to determine whether source files or other inputs have changed. These mechanisms work together.
It’s important not to think of a fingerprint as simply a hash of the source code. Cargo’s freshness logic is more sophisticated, incorporating compiler inputs, dependency relationships, and filesystem-based checks. The official Cargo implementation documentation describes these mechanisms and how changes can propagate through dependencies.
A small experiment
Try running:
cargo check --workspace -vv
Then run it again:
cargo check --workspace -vv
The -vv flag enables very verbose output. On the first invocation, Cargo may need to compile our crates. On the second, assuming nothing relevant has changed, Cargo should be able to identify the corresponding work as fresh. The verbose output helps us see which units Cargo considers fresh and which compiler commands it invokes.
Now modify crates/core/src/lib.rs and run the command again. Cargo must reassess which units remain fresh. Because our application depends on the core library, changes to the library can also affect downstream compilation work.
An important limitation
Cargo doesn’t generally determine freshness by proving whether a source change is semantically irrelevant to all downstream users. For example, changing the implementation of a function without changing its public signature can still trigger downstream work. The precise outcome depends on the compilation units, dependency artifacts, and compiler configuration.
This distinction between what actually changed and what Cargo can safely reuse is extremely important. It deserves its own detailed investigation, which we’ll cover in a later article: How Does Cargo Know What Needs Recompiling? For now, the main takeaway is that Cargo decides whether compilation work is necessary before executing the relevant jobs.
6. Build scripts and procedural macros
So far, our workspace contains ordinary Rust source code. But many real-world Rust projects have another complication. They execute code during compilation. There are two particularly important mechanisms: build scripts and procedural macros.
Build scripts
Rust packages can include a file named build.rs. Cargo compiles this file into an executable and runs it before compiling the package that owns it. Build scripts are commonly used to generate source files, prepare native dependencies, or discover system-specific configuration. Let’s add a simple build script to our application:
crates/app/build.rs
fn main() {
println!("cargo::rerun-if-changed=build.rs");
}
This script doesn’t perform any useful build preparation, but it illustrates the mechanism. When we build the application, Cargo must ensure that the build script has been compiled and executed as required. The rerun-if-changed instruction tells Cargo which file to watch when deciding whether the script needs to run again.
Real build scripts may perform much more substantial work. For example, they might compile C code, invoke an external tool, or generate Rust source files. The Cargo Book describes the build-script lifecycle and how its inputs are tracked.
Procedural macros
Procedural macros provide another way for Rust code to execute during compilation. A procedural macro takes Rust tokens as input and produces Rust tokens as output. This enables powerful features such as custom derives and attribute macros. For example, the serde ecosystem provides procedural macros for deriving serialization implementations.
These macros aren’t simply source-code substitutions performed by Cargo. The procedural macro itself is compiled into executable code that rustc loads and executes during macro expansion. That introduces additional compilation work.
Host and target compilation
There’s another subtlety. Build scripts and procedural macros generally execute on the machine performing the compilation. We call this the host.
But the Rust application itself might be compiled for a different architecture. We call that the target.
For example, we might compile on an x86-64 Linux machine while producing software intended to run on ARM. The build scripts and procedural macros need to run on the x86-64 host, while the application may need to be compiled for ARM. This means Cargo must account for multiple compilation contexts. It’s another reason that the real compilation graph can be more complex than the package dependency graph.
Why this matters for cargo check
This also explains an initially surprising behaviour. Even though cargo check generally avoids normal final machine-code generation for the crates being checked, it may still need to fully compile and execute build-time components. It can’t necessarily avoid compiling a procedural macro, because rustc needs to execute that macro to understand the source code that results from expansion.
So checking Rust code doesn’t mean avoiding every form of code generation or execution. That distinction becomes particularly important when measuring build performance.
7. What actually happens inside rustc?
We’ve now followed our CI job through Cargo’s responsibilities. Cargo has resolved the workspace, determined the required compilation units, checked freshness, and scheduled work. Eventually, it invokes rustc.
This is where the Rust compiler takes over. And this is where some of the most impressive engineering in the Rust ecosystem lives.
Rust’s compiler does much more than translate source code into machine instructions. It performs sophisticated analysis that makes Rust’s compile-time guarantees possible. Let’s follow the major stages.
Stage 1: Parsing Rust source code
The compiler begins by reading Rust source code and transforming it into a structured representation. This involves tokenization and parsing. Consider this source code:
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
The compiler transforms it into an abstract syntax tree, or AST. The AST represents the grammatical structure of the program. Rather than treating the function as arbitrary text, the compiler can reason about its parameters, return type, expressions, and statements. Syntax errors can be detected at this stage.
Stage 2: Macro expansion and name resolution
Rust supports several kinds of macros. Some are built into the language. Others are provided by libraries or implemented as procedural macros.
During macro expansion, the compiler expands macro invocations into Rust syntax that can be analyzed further. For example:
println!("Hello, Rust!");
This statement uses the println! macro. The compiler must expand that invocation as part of understanding the program.
Name resolution determines what identifiers refer to. For this call:
ci_core::greet("Rust")
The compiler needs to resolve the referenced crate and function. Macro expansion and name resolution are interrelated processes, rather than two completely independent passes.
Stage 3: HIR and type checking
After the earlier front-end work, the compiler lowers source constructs into its High-level Intermediate Representation, or HIR. HIR provides a representation suitable for semantic analysis.
One particularly important activity is type checking. The compiler verifies that expressions, function calls, and other constructs satisfy the language’s type rules. Consider:
let count: u32 = "hello";
This is invalid because the value doesn’t match the declared type. Rust identifies the problem during compilation rather than allowing the program to execute.
This is only one example of the analysis performed by the compiler. Rust also checks many other language constraints, including trait requirements and coherence rules.
Stage 4: MIR and borrow checking
The compiler eventually produces another representation called Mid-level Intermediate Representation, or MIR. MIR represents program control flow and operations in a form that is easier for several compiler analyses to work with.
It is particularly important for borrow checking. Consider:
fn main() {
let value = String::from("Hello");
let reference = &value;
drop(value);
println!("{reference}");
}
This program attempts to use a reference after the value it refers to has been destroyed. Rust’s borrow checker rejects the program.
MIR provides a foundation for the dataflow analysis needed to enforce borrowing and lifetime constraints. It is also used for other analyses and optimizations. This is one of the reasons Rust can provide strong memory-safety guarantees without requiring a garbage collector for ordinary safe Rust code.
Stage 5: Monomorphization
Rust supports generics. For example:
fn identity<T>(value: T) -> T {
value
}
A program might use this function with multiple concrete types. During code generation, rustc identifies the concrete instances of generic code required by the program. This process is called monomorphization. It allows Rust to produce specialized machine code for concrete type combinations.
That can provide excellent runtime performance. But it can also increase compilation work and the amount of generated code. We’ll return to monomorphization when investigating why some Rust builds take considerably longer than others.
Stage 6: Code generation
After the relevant analysis, rustc can generate machine code. For normal builds, Rust commonly uses LLVM as its code-generation backend. The compiler lowers the necessary representations into LLVM IR, where LLVM performs additional transformations and optimizations before producing machine-code objects.
This is a significant part of the work performed during compilation. The amount of code generated and the selected optimization settings can strongly influence compilation time. For example, development and release builds generally use different optimization settings. A release build may therefore perform substantially more optimization work than a typical development build.
Stage 7: Linking
Finally, producing an executable may require linking together object files and compiled libraries. The linker resolves symbols and combines the required components into the final executable. Depending on the platform and toolchain configuration, this work may be performed by an external linker invoked by rustc.
Not every compiler invocation performs a final executable link, and the precise outputs depend on the requested crate type. For our application, however, linking is part of producing the runnable program.
Putting the compiler stages together
We can summarize the major representations and activities:
- Rust source code
- Parsing and AST
- Macro expansion and resolution
- HIR and type checking
- THIR and MIR
- Borrow checking and MIR optimization
- Monomorphization and code generation
- LLVM IR
- Machine-code objects
- Linking
- Executable or library artifact
This is a conceptual overview, not an exact execution trace. The Rust Compiler Development Guide provides a much more detailed explanation of the compiler’s architecture.
An important nuance: rustc isn’t just a linear pipeline
We’ve presented compilation as a series of stages because that’s a useful way to understand it. But internally, rustc uses a more sophisticated architecture. Many compiler operations are implemented using a query system.
A query computes some piece of information about the program. For example, the compiler might ask for the type of an item or the optimized MIR representation of a function. Queries can depend on other queries. Rustc tracks these dependencies and caches many query results.
This architecture is particularly important for incremental compilation. Rather than always recomputing every compiler result from scratch, rustc can sometimes reuse previous results when the relevant inputs haven’t changed.
However, not every compiler operation is independently query-driven, and not every query result is persisted between compiler invocations. The distinction matters: incremental compilation isn’t a guarantee that arbitrary unchanged portions of a program can always be reused. The Rust Compiler Development Guide explains the query system and its relationship to incremental compilation.
This is another topic we’ll explore in depth later. For now, remember that Cargo’s crate-level freshness decisions and rustc’s internal incremental computation are two different mechanisms operating at different levels.
8. Why are check, build, Clippy, and test different?
We now have enough background to answer a question from our introductory article. Why do the familiar Cargo commands perform different amounts of work? The answer comes down to what each command needs to produce.
cargo check
When we run:
cargo check --workspace
Cargo arranges for rustc to analyze the selected crates without performing their normal final code-generation and linking work. The compiler still needs to perform substantial analysis. It must parse source code, expand macros, resolve names, check types, and enforce important language rules. It also produces metadata that downstream crate checks can consume.
Because normal machine-code generation is generally avoided, checking can be significantly faster than a full build. However, as we’ve seen, build scripts and procedural macros may still need executable compilation. And because code generation and linking are skipped for checked crates, some errors cannot be detected by cargo check alone.
cargo build
When we run:
cargo build --workspace
Cargo requests the compiled artifacts needed for a normal build. Rustc performs the required analysis, code generation, and linking.
This may require additional compilation work even if we’ve already run cargo check. The output from a check-only compilation isn’t generally a substitute for the linked library or executable artifacts required by a build. That explains why running cargo check before cargo build doesn’t necessarily make the build free.
cargo clippy
Clippy is closely integrated with Rust’s compiler infrastructure. When we run:
cargo clippy --workspace --all-targets
Cargo coordinates checking the selected targets with Clippy’s additional lint analysis. Clippy uses compiler information to identify suspicious patterns and opportunities for improvement. Much of its work resembles the analysis involved in cargo check, but the invocation and analysis requirements are not identical. We should not assume that all work performed by one command can automatically be reused by another.
cargo test
Testing introduces another layer of complexity. When we run:
cargo test --workspace
Cargo needs to build and execute the selected tests. Rust’s test harness allows functions marked with #[test] to be discovered and executed automatically. To do that, rustc may compile crates in a special test configuration. In addition, integration tests are separate compilation targets.
Our example therefore contains multiple forms of testing. The unit test inside ci-core is compiled as part of the library’s test configuration. The integration test inside ci-app becomes a separate test executable.
And the documentation test in our library is handled through rustdoc’s documentation-testing mechanism. The official Cargo documentation explains how these targets are compiled and executed.
Comparing the commands
| Command | Principal work | Normal final code generation? | Executes tests? |
|---|---|---|---|
cargo check |
Compiler analysis and metadata | Generally no for checked crates | No |
cargo clippy |
Compiler analysis and additional lints | Generally no for checked crates | No |
cargo build |
Compilation and artifact production | Yes, as needed | No |
cargo test |
Compilation of test targets | Yes, as needed | Yes |
This table describes the normal behaviour of the commands, not every compilation job they may trigger. Build scripts, procedural macros, target selection, and other configuration details can introduce exceptions.
An important consequence for CI
Now consider the pipeline from Article 1:
cargo check --workspace
cargo clippy --workspace --all-targets
cargo test --workspace
cargo build --workspace
These commands don’t represent four entirely independent tasks. They involve overlapping dependencies, source files, compiler analyses, and compilation configurations. Cargo and rustc can reuse some work across invocations, provided the existing artifacts and compilation settings are compatible.
But not all work is interchangeable. A check-only artifact isn’t the same thing as a fully compiled library. A unit-test compilation can differ from a normal library compilation. Different feature configurations or compilation targets can require additional work.
This means the order and configuration of CI commands can influence how much compilation work is repeated. We’ll examine those trade-offs in a later performance article.
9. What happens when we run CI again?
Let’s return to our example workspace. Imagine we’ve successfully completed:
cargo test --workspace
All tests pass. Now we make a small change.
Scenario A: We change the application
Suppose we modify:
fn main() {
println!("{}", ci_core::greet("Ferris"));
}
We’ve changed our application, but not the underlying library. Cargo can normally reuse compatible, fresh library artifacts. It only needs to rebuild the compilation units affected by the change. This is the kind of situation where incremental development can be particularly efficient.
Scenario B: We change the library
Now imagine we modify the implementation of greet. Because the application depends on the library, the change can affect downstream compilation units. Cargo must determine which units remain fresh and which require rebuilding. Even a change that leaves the public function signature untouched may still lead to downstream recompilation.
Why? Because Cargo’s freshness mechanism isn’t a general-purpose semantic-equivalence checker. It doesn’t automatically prove that every downstream use of a dependency remains unaffected by an implementation change.
Scenario C: We change compilation settings
Finally, suppose we change the compiler version, enable a different feature, or select a different compilation profile. These changes can alter the compilation units and their expected outputs. As a result, artifacts produced under one configuration may not be reusable under another. This is particularly relevant in CI environments, where toolchains and configuration can vary between jobs.
What about rustc’s incremental compilation?
Even when Cargo determines that a compilation unit needs rebuilding, rustc may be able to reuse some previously computed compiler results. That depends on whether incremental compilation is enabled and whether the stored results remain valid and available.
This gives us two distinct opportunities for reuse:
Cargo-level reuse: Avoid invoking the compiler for an already-fresh unit. rustc-level reuse: When compilation is required, avoid recomputing some compiler results. The distinction is central to understanding how Rust builds can be accelerated.
10. Investigating your own Rust CI pipeline
Everything we’ve discussed so far can be explored using Cargo’s built-in tools. Here are a few useful experiments.
Experiment 1: Inspect dependencies
cargo tree
cargo tree -e features
Observe the dependency relationships and enabled features.
Experiment 2: Inspect compiler invocations
From a disposable copy of the example workspace, run:
cargo clean
cargo check --workspace -vv
The cargo clean command removes the workspace’s existing build artifacts, giving us a fresh starting point. The verbose output makes it easier to observe the compiler work Cargo performs. Run the check again:
cargo check --workspace -vv
Compare the two invocations. Which compilation units were rebuilt? Which were considered fresh?
Experiment 3: Compare check and build
Now run:
cargo build --workspace -vv
Notice that the build may require additional compiler invocations even though the workspace has already been checked. That follows from the different output requirements.
Experiment 4: Inspect test compilation
Run:
cargo test --workspace --no-run -vv
The --no-run option compiles test targets without executing the ordinary test binaries. Compare the compiler jobs with those observed during the normal build. Then execute the tests:
cargo test --workspace
This also exercises the documentation test in our library.
Experiment 5: Inspect compilation timings
Cargo includes a useful timing-reporting feature:
cargo build --workspace --timings
This generates a report showing compilation durations and concurrency. For larger projects, it can reveal which crates take the longest to compile and where dependency ordering limits parallel execution. Cargo documents this functionality as part of its build commands.
Try running it on one of your own Rust projects. The results may be considerably more interesting than those from our tiny example.
11. Putting everything together
We’ve now followed a Rust CI job through its major stages. Let’s reconstruct the whole process.
First, the CI system prepares an execution environment and invokes Cargo. Cargo reads the workspace configuration, resolves dependencies and features, and determines which compilation units are required. It checks the freshness of those units to determine which work can be reused. For units that require compilation, Cargo schedules jobs according to their dependencies.
Rustc then performs the relevant compiler analysis and, when necessary, code generation. Some crates may also require build-time execution through procedural macros and build scripts. When tests are requested, Cargo builds the necessary test targets and executes the selected tests. Finally, Cargo reports the outcome to the CI system.
- CI runner
- Cargo: Project resolution
- Cargo: Compilation-unit graph
- Cargo: Freshness checks
Unit fresh?
Reuse existing artifacts.
- Schedule compilation
- rustc: Analysis
- rustc: Code generation, when required
- Artifacts / Test binaries
- Execute tests, when requested
- CI results
This diagram is conceptual. In practice, Cargo can schedule multiple compilation units concurrently, and different commands require different outputs.
There’s one final point worth emphasizing. Rust CI performance depends on considerably more than how quickly rustc can compile a single source file. It depends on the structure of the compilation graph, the work required by each unit, the availability of previous outputs, the compilation configuration, and the opportunities for parallelism.
And many of those factors interact. That leads us directly to the next question.
Next: Why is Rust CI so slow?
We’ve seen that Cargo and rustc already contain sophisticated mechanisms for avoiding unnecessary work. Cargo tracks compilation-unit freshness. Rustc supports incremental compilation.
Cargo schedules independent compilation work concurrently. And commands such as cargo check deliberately avoid some of the most expensive stages of ordinary compilation.
So why can Rust CI still be slow? Why can a cold build take dramatically longer than a warm build? Why can seemingly small changes trigger substantial recompilation? And why doesn’t caching eliminate these problems?
In the next article, Why is Rust CI so slow?, we’ll investigate these questions through concrete measurements and examples. We’ll look at where compilation time goes, how dependency graphs constrain parallelism, and why achieving fast, reliable Rust CI is a more interesting engineering problem than simply adding more CPU cores.
Rust CI from first principles is an educational series by Sorus, exploring Rust compilation, testing, continuous integration, and developer productivity.