Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(rust): improves selective build accuracy and CI performance (#61731)

Nick Bestd2ae5f970b83
diff --git a/.github/actions/rust-compute-affected/action.yml b/.github/actions/rust-compute-affected/action.yml
index ab1ffee232ab..8020ac1a35a1 100644
--- a/.github/actions/rust-compute-affected/action.yml
+++ b/.github/actions/rust-compute-affected/action.yml
@@ -71,7 +71,26 @@ runs:
if [ "$EVENT_NAME" = "push" ]; then
base_ref="$PUSH_BEFORE_SHA"
else
- base_ref="$PR_BASE_SHA"
+ # Try to resolve the base branch name from the input or
+ # the GitHub event payload so we diff against the current
+ # tip rather than the potentially stale PR base SHA.
+ base_branch=""
+ if [ -f "$GITHUB_EVENT_PATH" ]; then
+ base_branch=$(jq -r '.pull_request.base.ref // empty' "$GITHUB_EVENT_PATH" 2>/dev/null || true)
+ fi
+
+ if [ -n "$base_branch" ]; then
+ git fetch --no-tags origin "$base_branch"
+ base_ref=$(git merge-base FETCH_HEAD HEAD || true)
+ if [ -n "$base_ref" ]; then
+ echo "Using merge-base of origin/$base_branch and HEAD: $base_ref"
+ else
+ echo "merge-base empty; falling back to PR base SHA"
+ base_ref="$PR_BASE_SHA"
+ fi
+ else
+ base_ref="$PR_BASE_SHA"
+ fi
fi
if [ -z "$base_ref" ] || echo "$base_ref" | grep -qE '^0+$'; then
diff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.yml
index 89cd019dd04b..d8a21526729f 100644
--- a/.github/workflows/ci-rust.yml
+++ b/.github/workflows/ci-rust.yml
@@ -85,6 +85,12 @@ jobs:
with:
fetch-depth: 0
filter: blob:none
+ sparse-checkout: |
+ rust/
+ proto/
+ .github/rust-images.yml
+ .github/actions/rust-compute-affected/
+ sparse-checkout-cone-mode: false
clean: false
- name: Install rust
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index af1d8315a310..a6ea5bfad3e6 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -42,6 +42,7 @@ dependencies = [
"clap",
"determinator",
"guppy",
+ "rstest",
"serde",
"serde_json",
"tempfile",
diff --git a/rust/affected-services/Cargo.toml b/rust/affected-services/Cargo.toml
index 0cd22f238ebd..28467c9fa9f1 100644
--- a/rust/affected-services/Cargo.toml
+++ b/rust/affected-services/Cargo.toml
@@ -11,3 +11,6 @@ guppy = "0.17"
serde = { workspace = true }
serde_json = { workspace = true }
tempfile = "3"
+
+[dev-dependencies]
+rstest = "0.26"
diff --git a/rust/affected-services/determinator-rules.toml b/rust/affected-services/determinator-rules.toml
index 7a5b61338bd6..adc5e39d057a 100644
--- a/rust/affected-services/determinator-rules.toml
+++ b/rust/affected-services/determinator-rules.toml
@@ -33,6 +33,48 @@ mark-changed = "all"
globs = ["../proto/**"]
mark-changed = ["personhog-proto", "kafka-assigner-proto", "cymbal-proto"]
+# Hypercache contract: Python serializer changes may break Rust deserialization.
+# Must come BEFORE the catch-all rule below.
+[[path-rule]]
+globs = [
+ "../posthog/api/feature_flag.py",
+ "../posthog/models/feature_flag/flags_cache.py",
+ "../posthog/models/feature_flag/feature_flag.py",
+]
+mark-changed = ["feature-flags", "hypercache-server", "common-hypercache"]
+
+# Django migrations and test environment setup — needed for Rust integration tests.
+[[path-rule]]
+globs = [
+ "../posthog/migrations/**",
+ "../ee/migrations/**",
+ "../posthog/management/commands/setup_test_environment.py",
+ "../docker-compose.dev.yml",
+]
+mark-changed = "all"
+
+# CI harness inputs that the rust test/build jobs depend on — a change here
+# should run all rust CI to catch regressions.
+[[path-rule]]
+globs = [
+ "../manage.py",
+ "../posthog/settings/**",
+ "../bin/download-mmdb",
+ "../.github/workflows/ci-rust.yml",
+ "../.github/actions/setup-protoc/**",
+ "../.github/actions/setup-sccache/**",
+ "../.github/actions/setup-sqlx-cli/**",
+ "../.github/actions/rust-compute-affected/**",
+]
+mark-changed = "all"
+
+# Catch-all for files outside the rust workspace (Python, frontend, CI, docs,
+# etc.) — these are not crate source and should not trigger rust rebuilds.
+# Must come AFTER all specific rules for files outside the workspace.
+[[path-rule]]
+globs = ["../**"]
+mark-changed = []
+
# Migration directories are not cargo crates. Tell the determinator to
# ignore them (don't try ancestor-walk package matching). The sqlx-migrate
# image trigger is handled in custom code outside the determinator.
diff --git a/rust/affected-services/src/graph.rs b/rust/affected-services/src/graph.rs
index 9e4e51048f51..46aee99531c0 100644
--- a/rust/affected-services/src/graph.rs
+++ b/rust/affected-services/src/graph.rs
@@ -45,18 +45,21 @@ struct TempWorktree {
}
impl TempWorktree {
- fn create(base_ref: &str) -> Result<Self> {
+ fn create(base_ref: &str, sparse_paths: &[&str]) -> Result<Self> {
let path = tempfile::Builder::new()
.prefix("affected-services-")
.tempdir()
.context("failed to create temp directory")?
.keep();
+ let path_s = path.to_string_lossy();
+
let out = Command::new("git")
.args([
"worktree",
"add",
"--detach",
- &path.to_string_lossy(),
+ "--no-checkout",
+ path_s.as_ref(),
base_ref,
])
.output()
@@ -66,6 +69,32 @@ impl TempWorktree {
"git worktree add failed: {}",
String::from_utf8_lossy(&out.stderr).trim()
);
+
+ // Configure sparse checkout on the worktree so we only materialize
+ // the paths needed for cargo metadata, not the entire repo.
+ let mut sparse_args = vec!["sparse-checkout", "set", "--no-cone"];
+ sparse_args.extend_from_slice(sparse_paths);
+ let sparse_out = Command::new("git")
+ .args(["-C", path_s.as_ref()])
+ .args(&sparse_args)
+ .output()
+ .context("failed to configure sparse checkout on worktree")?;
+ anyhow::ensure!(
+ sparse_out.status.success(),
+ "git sparse-checkout set failed: {}",
+ String::from_utf8_lossy(&sparse_out.stderr).trim()
+ );
+
+ let checkout_out = Command::new("git")
+ .args(["-C", path_s.as_ref(), "checkout"])
+ .output()
+ .context("failed to checkout worktree")?;
+ anyhow::ensure!(
+ checkout_out.status.success(),
+ "git checkout in worktree failed: {}",
+ String::from_utf8_lossy(&checkout_out.stderr).trim()
+ );
+
Ok(Self { path })
}
@@ -88,7 +117,7 @@ impl Drop for TempWorktree {
}
pub fn build_old_package_graph(base_ref: &str, workspace_subdir: &str) -> Option<PackageGraph> {
- let worktree = match TempWorktree::create(base_ref) {
+ let worktree = match TempWorktree::create(base_ref, &[workspace_subdir]) {
Ok(w) => w,
Err(e) => {
eprintln!("warning: could not create worktree at {base_ref}: {e}");
diff --git a/rust/affected-services/tests/integration.rs b/rust/affected-services/tests/integration.rs
index 033fd315d9c7..a85012ccb486 100644
--- a/rust/affected-services/tests/integration.rs
+++ b/rust/affected-services/tests/integration.rs
@@ -6,6 +6,7 @@ use affected_services::images::{
build_binary_to_crate_map, parse_images_yaml, ImageConfig, NON_CRATE_IMAGE_TRIGGERS,
};
use guppy::graph::PackageGraph;
+use rstest::rstest;
fn load_test_fixtures() -> (PackageGraph, Vec<ImageConfig>) {
let repo_root = find_repo_root().expect("must be in a git repo");
@@ -289,6 +290,50 @@ fn multi_binary_crate_produces_all_images() {
assert!(result.images.contains(&"flags-cache-warmer".into()));
}
+// ── Path-rule ordering tests ─────────────────────────────────────
+
+#[rstest]
+#[case::hypercache_rule_fires_before_catch_all(
+ "posthog/api/feature_flag.py",
+ false,
+ &["feature-flags", "hypercache-server", "common-hypercache"],
+)]
+#[case::catch_all_ignores_unrelated_non_rust_files(
+ "frontend/src/foo.tsx",
+ false,
+ &[],
+)]
+#[case::ci_harness_change_triggers_rebuild_all(
+ ".github/workflows/ci-rust.yml",
+ true,
+ &[],
+)]
+fn path_rule_ordering(
+ #[case] file: &str,
+ #[case] expect_rebuild_all: bool,
+ #[case] expect_crates: &[&str],
+) {
+ let (graph, images) = load_test_fixtures();
+ let result = compute_affected(&[file.into()], None, &graph, &images).unwrap();
+ assert_eq!(
+ result.rebuild_all, expect_rebuild_all,
+ "rebuild_all mismatch for {file}"
+ );
+ if !expect_rebuild_all {
+ let crates: HashSet<&str> = result.crates.iter().map(|s| s.as_str()).collect();
+ if expect_crates.is_empty() {
+ assert!(
+ crates.is_empty(),
+ "expected no crates for {file}, got {crates:?}"
+ );
+ } else {
+ for name in expect_crates {
+ assert!(crates.contains(name), "{file} should mark {name} affected");
+ }
+ }
+ }
+}
+
// ── Determinator two-graph tests ─────────────────────────────────
#[test]