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.

chore(rust): selective builds (#59563)

Nick Best45ece2f3352a
diff --git a/.github/actions/rust-compute-affected/action.yml b/.github/actions/rust-compute-affected/action.yml
new file mode 100644
index 000000000000..ab1ffee232ab
--- /dev/null
+++ b/.github/actions/rust-compute-affected/action.yml
@@ -0,0 +1,103 @@
+name: Compute affected Rust services
+description: |
+ Builds the affected-services binary (cached) and runs it to determine
+ which crates and container images are affected by the current change.
+
+inputs:
+ event-name:
+ description: github.event_name — controls how the base ref is resolved
+ required: true
+ pr-base-sha:
+ description: 'Base SHA for PR / merge-group events'
+ required: false
+ default: ''
+ push-before-sha:
+ description: 'Previous HEAD for push events (github.event.before)'
+ required: false
+ default: ''
+ rebuild-all:
+ description: 'Force a full rebuild (skip diff analysis)'
+ required: false
+ default: 'false'
+
+outputs:
+ crates:
+ description: JSON array of affected crate names
+ value: ${{ steps.compute.outputs.crates }}
+ images:
+ description: "Comma-separated affected image names (empty = all, 'none' = skip)"
+ value: ${{ steps.compute.outputs.images }}
+ rebuild-all:
+ description: "'true' when every service needs rebuilding"
+ value: ${{ steps.compute.outputs.rebuild_all }}
+
+runs:
+ using: composite
+ steps:
+ - name: Restore cached binary
+ id: cache
+ uses: actions/cache/restore@9255dc7a253b0ccc959486e2bca901246202afeb # v5.0.1
+ with:
+ path: rust/target/release/affected-services
+ key: affected-services-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('rust/affected-services/**', 'rust/Cargo.lock') }}
+
+ - name: Build on cache miss
+ if: steps.cache.outputs.cache-hit != 'true'
+ shell: bash
+ working-directory: rust
+ run: cargo build -p affected-services --release --locked
+
+ - name: Save binary to cache
+ if: steps.cache.outputs.cache-hit != 'true'
+ uses: actions/cache/save@9255dc7a253b0ccc959486e2bca901246202afeb # v5.0.1
+ with:
+ path: rust/target/release/affected-services
+ key: affected-services-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('rust/affected-services/**', 'rust/Cargo.lock') }}
+
+ - name: Compute affected services
+ id: compute
+ shell: bash
+ env:
+ EVENT_NAME: ${{ inputs.event-name }}
+ PR_BASE_SHA: ${{ inputs.pr-base-sha }}
+ PUSH_BEFORE_SHA: ${{ inputs.push-before-sha }}
+ FORCE_REBUILD: ${{ inputs.rebuild-all }}
+ working-directory: rust
+ run: |
+ if [ "$FORCE_REBUILD" = "true" ]; then
+ echo "rebuild-all requested"
+ result=$(./target/release/affected-services --files rust/Cargo.lock)
+ else
+ if [ "$EVENT_NAME" = "push" ]; then
+ base_ref="$PUSH_BEFORE_SHA"
+ else
+ base_ref="$PR_BASE_SHA"
+ fi
+
+ if [ -z "$base_ref" ] || echo "$base_ref" | grep -qE '^0+$'; then
+ echo "No valid base ref — rebuilding all"
+ result=$(./target/release/affected-services --files rust/Cargo.lock)
+ else
+ result=$(./target/release/affected-services --base-ref "$base_ref")
+ fi
+ fi
+
+ rebuild_all=$(echo "$result" | jq -r '.rebuild_all')
+ crates=$(echo "$result" | jq -c '.crates')
+ images=$(echo "$result" | jq -r '.images | join(",")')
+
+ echo "rebuild_all=$rebuild_all, crates=$crates, images=$images"
+
+ echo "rebuild_all=$rebuild_all" >> "$GITHUB_OUTPUT"
+ echo "crates=$crates" >> "$GITHUB_OUTPUT"
+
+ if [ "$rebuild_all" = "true" ]; then
+ echo "Rebuild all triggered"
+ echo "images=" >> "$GITHUB_OUTPUT"
+ elif [ -z "$images" ]; then
+ echo "No images affected — build will be skipped"
+ echo "images=none" >> "$GITHUB_OUTPUT"
+ else
+ echo "Affected images: $images"
+ echo "images=$images" >> "$GITHUB_OUTPUT"
+ fi
diff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.yml
index b4ddbafbae84..054b22245e3e 100644
--- a/.github/workflows/ci-rust.yml
+++ b/.github/workflows/ci-rust.yml
@@ -30,7 +30,6 @@ jobs:
# Set job outputs to values from filter step
outputs:
rust: ${{ steps.filter.outputs.rust || 'true' }}
- matrix: ${{ steps.shards.outputs.matrix }}
steps:
# For pull requests it's not necessary to checkout the code, but we
# also want this to run on master so we need to checkout
@@ -68,17 +67,50 @@ jobs:
- 'posthog/models/feature_flag/feature_flag.py'
- 'rust/feature-flags/tests/fixtures/hypercache_contract.json'
- # Bin-pack packages into balanced test shards.
- # Weights are approximate total durations (compile + test) in seconds,
- # calibrated against 2-week avg CI job times (last updated: 2026-05-07).
- # TARGET_MINUTES controls max wall-clock per shard; shard count is derived.
+ # Compute affected crates and test shards. Only runs when Rust changes
+ # are detected, keeping the lightweight `changes` job fast for non-Rust PRs.
+ affected:
+ name: Compute affected Rust crates
+ needs: changes
+ if: needs.changes.outputs.rust == 'true'
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ permissions:
+ contents: read
+ outputs:
+ matrix: ${{ steps.shards.outputs.matrix }}
+ affected_crates: ${{ steps.affected.outputs.crates }}
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ fetch-depth: 0
+ clean: false
+
+ - name: Install rust
+ uses: dtolnay/rust-toolchain@3c5f7ea28cd621ae0bf5283f0e981fb97b8a7af9
+ with:
+ toolchain: 1.91.1
+
+ - name: Compute affected crates
+ id: affected
+ uses: ./.github/actions/rust-compute-affected
+ with:
+ event-name: ${{ github.event_name }}
+ pr-base-sha: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }}
+ push-before-sha: ${{ github.event.before }}
+ rebuild-all: ${{ github.event_name == 'workflow_dispatch' && 'true' || 'false' }}
+
+ # Bin-pack affected packages into balanced test shards.
- name: Compute test shards
id: shards
- if: steps.filter.outputs.rust != 'false'
+ env:
+ AFFECTED_CRATES: ${{ steps.affected.outputs.crates }}
shell: python3 {0}
run: |
import json, math, os
+ affected = set(json.loads(os.environ.get("AFFECTED_CRATES", "[]")))
+
packages = {
"assignment-coordination": 11,
"batch-import-worker": 124,
@@ -119,10 +151,30 @@ jobs:
"serve-metrics": 14,
}
- # Target max minutes for the cargo-test step per shard.
- # Total job time ≈ this + ~2.5 min setup overhead.
- # Shard count is computed dynamically so adding packages doesn't
- # silently blow past the budget — just adds more shards.
+ # Filter to only affected crates when selective builds are active.
+ # Unknown crates (not in packages dict) get a default weight so new
+ # services are never silently dropped from CI.
+ DEFAULT_WEIGHT = 60
+ if affected:
+ unknown = affected - packages.keys()
+ if unknown:
+ print(f"WARNING: affected crates missing from weight table (using {DEFAULT_WEIGHT}s default): {', '.join(sorted(unknown))}")
+ print("Add them to the packages dict in ci-rust.yml with measured weights.")
+ for crate in unknown:
+ packages[crate] = DEFAULT_WEIGHT
+ packages = {k: v for k, v in packages.items() if k in affected}
+ print(f"Selective build: testing {len(packages)} of affected crates")
+ else:
+ print("Full build: testing all crates")
+
+ if not packages:
+ with open(os.environ["GITHUB_OUTPUT"], "a") as f:
+ f.write('matrix={"include":[]}\n')
+ raise SystemExit(0)
+
+ # Weights are approximate total durations (compile + test) in seconds,
+ # calibrated against 2-week avg CI job times (last updated: 2026-05-07).
+ # TARGET_MINUTES controls max wall-clock per shard; shard count is derived.
TARGET_MINUTES = 8
target_seconds = TARGET_MINUTES * 60
total = sum(packages.values())
@@ -155,7 +207,7 @@ jobs:
build:
name: Build Rust services (depot-ubuntu-22.04-4)
- needs: changes
+ needs: [changes, affected]
if: needs.changes.outputs.rust == 'true'
runs-on: depot-ubuntu-22.04-4
timeout-minutes: 15
@@ -207,13 +259,22 @@ jobs:
env:
# Use system OpenSSL instead of vendored to avoid assembly build issue (2026-01-13)
OPENSSL_NO_VENDOR: '1'
- run: cargo build --all --locked --release && find target/release/ -maxdepth 1 -executable -type f | xargs strip
+ AFFECTED_CRATES: ${{ needs.affected.outputs.affected_crates }}
+ run: |
+ crates=$(echo "$AFFECTED_CRATES" | python3 -c "import json,sys; print(' '.join(f'-p {c}' for c in json.load(sys.stdin)))")
+ if [ -z "$crates" ]; then
+ echo "No affected crates — skipping build"
+ else
+ echo "Building affected crates: $crates"
+ cargo build $crates --locked --release
+ find target/release/ -maxdepth 1 -executable -type f -exec strip {} +
+ fi
test:
name: Test Rust (${{ matrix.packages }})
strategy:
- matrix: ${{ fromJSON(needs.changes.outputs.matrix) }}
- needs: changes
+ matrix: ${{ fromJSON(needs.affected.outputs.matrix) }}
+ needs: [changes, affected]
if: needs.changes.outputs.rust == 'true'
runs-on: depot-ubuntu-24.04-4
timeout-minutes: 20
@@ -432,7 +493,7 @@ jobs:
# Collate job - single required status check for branch protection.
# Individual jobs skip entirely when no Rust changes, saving runner time.
rust_tests:
- needs: [changes, build, test, linting]
+ needs: [changes, affected, build, test, linting]
name: Rust Tests Pass
runs-on: ubuntu-latest
timeout-minutes: 5
@@ -441,7 +502,7 @@ jobs:
steps:
- name: Check all Rust jobs
run: |
- # Fail if change detection itself failed
+ # Fail if change detection or affected computation failed
if [[ "${{ needs.changes.result }}" == "failure" ]]; then
echo "Change detection job failed."
exit 1
@@ -453,6 +514,11 @@ jobs:
exit 0
fi
+ if [[ "${{ needs.affected.result }}" == "failure" ]]; then
+ echo "Affected crate computation failed."
+ exit 1
+ fi
+
if [[ "${{ needs.build.result }}" != "success" && "${{ needs.build.result }}" != "skipped" ]]; then
echo "Rust build failed."
exit 1
diff --git a/.github/workflows/rust-docker-build.yml b/.github/workflows/rust-docker-build.yml
index 5c25a5dfa6b2..829749959a07 100644
--- a/.github/workflows/rust-docker-build.yml
+++ b/.github/workflows/rust-docker-build.yml
@@ -1,16 +1,19 @@
name: Build and deploy rust container images
# Production build + deploy for Rust services on master.
+# Uses selective builds: only images affected by changed files are built and deployed.
+# workflow_dispatch always builds all images (escape hatch).
#
# Image list: .github/rust-images.yml
# Build steps: .github/workflows/_rust-build-images.yml
-# Deploy matrix below must be updated when adding new services.
+# Affected-set computation: rust/affected-services (Rust binary crate)
on:
workflow_dispatch:
push:
paths:
- 'rust/**'
+ - 'proto/**'
- '.github/workflows/rust-docker-build.yml'
- '.github/workflows/_rust-build-images.yml'
- '.github/rust-images.yml'
@@ -19,6 +22,7 @@ on:
pull_request:
paths:
- 'rust/**'
+ - 'proto/**'
- '.github/workflows/rust-docker-build.yml'
- '.github/workflows/_rust-build-images.yml'
- '.github/rust-images.yml'
@@ -30,9 +34,54 @@ concurrency:
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
+ affected:
+ name: compute affected images
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ # Skip on workflow_dispatch — always build everything (escape hatch)
+ if: github.event_name != 'workflow_dispatch'
+ permissions:
+ contents: read
+ outputs:
+ image-filter: ${{ steps.compute.outputs.images }}
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ fetch-depth: 0
+ sparse-checkout: |
+ rust/
+ proto/
+ .github/rust-images.yml
+ .github/actions/rust-compute-affected/
+ sparse-checkout-cone-mode: false
+ clean: false
+
+ - name: Install rust
+ uses: dtolnay/rust-toolchain@3c5f7ea28cd621ae0bf5283f0e981fb97b8a7af9
+ with:
+ toolchain: 1.91.1
+
+ - name: Compute affected images
+ id: compute
+ uses: ./.github/actions/rust-compute-affected
+ with:
+ event-name: ${{ github.event_name }}
+ pr-base-sha: ${{ github.event.pull_request.base.sha }}
+ push-before-sha: ${{ github.event.before }}
+
build-images:
+ needs: affected
+ # always() is required because 'affected' may be skipped (workflow_dispatch),
+ # and GitHub Actions treats skipped dependencies as failures by default.
+ # !cancelled() prevents running after manual workflow cancellation.
+ # Run unless affected explicitly found zero images ('none') or failed.
+ if: |
+ always() && !cancelled() &&
+ needs.affected.result != 'failure' &&
+ needs.affected.outputs.image-filter != 'none'
uses: ./.github/workflows/_rust-build-images.yml
with:
+ image-filter: ${{ needs.affected.outputs.image-filter || '' }}
tag-rules: |
type=ref,event=pr
type=ref,event=branch
@@ -53,6 +102,8 @@ jobs:
needs: build-images
if: github.ref == 'refs/heads/master'
strategy:
+ # fail-fast false so one missing digest doesn't cancel other deploys
+ fail-fast: false
matrix:
include:
- release: capture
@@ -122,7 +173,23 @@ jobs:
digest_key: hypercache-server
values_key: image
steps:
+ - name: check if image was built
+ id: check
+ env:
+ DIGESTS: ${{ needs.build-images.outputs.digests }}
+ KEY: ${{ matrix.digest_key }}
+ run: |
+ digest=$(echo "$DIGESTS" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('$KEY',''))")
+ if [ -n "$digest" ]; then
+ echo "skip=false" >> "$GITHUB_OUTPUT"
+ echo "digest=$digest" >> "$GITHUB_OUTPUT"
+ else
+ echo "Skipping ${{ matrix.release }} — image not in this build"
+ echo "skip=true" >> "$GITHUB_OUTPUT"
+ fi
+
- name: get deployer token
+ if: steps.check.outputs.skip != 'true'
id: deployer
uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
with:
@@ -132,6 +199,7 @@ jobs:
repositories: charts
- name: trigger ${{ matrix.release }} deployment
+ if: steps.check.outputs.skip != 'true'
uses: peter-evans/repository-dispatch@28959ce8df70de7be546dd1250a005dd32156697 # v4.0.1
with:
token: ${{ steps.deployer.outputs.token }}
@@ -139,7 +207,7 @@ jobs:
event-type: commit_state_update
client-payload: |
{
- "values": {"${{ matrix.values_key }}": {"sha": "${{ fromJson(needs.build-images.outputs.digests)[matrix.digest_key] }}"}},
+ "values": {"${{ matrix.values_key }}": {"sha": "${{ steps.check.outputs.digest }}"}},
"release": "${{ matrix.release }}",
"commit": ${{ toJson(github.event.head_commit) }},
"repository": ${{ toJson(github.repository) }},
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 86c58e4353a2..050301dc4e2e 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -34,6 +34,19 @@ dependencies = [
"cpufeatures",
]
+[[package]]
+name = "affected-services"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "clap",
+ "determinator",
+ "guppy",
+ "serde",
+ "serde_json",
+ "tempfile",
+]
+
[[package]]
name = "ahash"
version = "0.7.8"
@@ -1713,6 +1726,15 @@ dependencies = [
"pkg-config",
]
+[[package]]
+name = "camino"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e629a66d692cb9ff1a1c664e41771b3dcaf961985a9774c0eb0bd1b51cf60a48"
+dependencies = [
+ "serde_core",
+]
+
[[package]]
name = "capture"
version = "0.1.0"
@@ -1816,6 +1838,30 @@ dependencies = [
"uuid",
]
+[[package]]
+name = "cargo-platform"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd0061da739915fae12ea00e16397555ed4371a6bb285431aab930f61b0aa4ba"
+dependencies = [
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "cargo_metadata"
+version = "0.23.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef987d17b0a113becdd19d3d0022d04d7ef41f9efe4f3fb63ac44ba61df3ade9"
+dependencies = [
+ "camino",
+ "cargo-platform",
+ "semver",
+ "serde",
+ "serde_json",
+ "thiserror 2.0.18",
+]
+
[[package]]
name = "cast"
version = "0.3.0"
@@ -1852,6 +1898,16 @@ dependencies = [
"nom",
]
+[[package]]
+name = "cfg-expr"
+version = "0.20.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fb693542bcafa528e198be0ebd9d3632ca5b7c93dbe7237460e199910835997c"
+dependencies = [
+ "smallvec",
+ "target-lexicon 0.13.5",
+]
+
[[package]]
name = "cfg-if"
version = "1.0.4"
@@ -2863,6 +2919,12 @@ dependencies = [
"regex",
]
+[[package]]
+name = "debug-ignore"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ffe7ed1d93f4553003e20b629abe9085e1e81b1429520f897f8f8860bc6dfc21"
+
[[package]]
name = "debugid"
version = "0.8.0"
@@ -2952,6 +3014,32 @@ dependencies = [
"syn 2.0.117",
]
+[[package]]
+name = "determinator"
+version = "0.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bf14b901cdfba3f731d01c4c184100e85f586a272d38874824175b845dbaeaf9"
+dependencies = [
+ "camino",
+ "globset",
+ "guppy",
+ "guppy-workspace-hack",
+ "once_cell",
+ "petgraph 0.6.5",
+ "rayon",
+ "serde",
+ "toml",
+]
+
+[[package]]
+name = "diffus"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c0ff24a73b51d9009c40897faf87d31b77345c90ffbf4dc3a1d2957032c5653"
+dependencies = [
+ "itertools 0.10.5",
+]
+
[[package]]
name = "digest"
version = "0.10.7"
@@ -3970,6 +4058,19 @@ version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"
+[[package]]
+name = "globset"
+version = "0.4.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52dfc19153a48bde0cbd630453615c8151bce3a5adfac7a0aebfbf0a1e1f57e3"
+dependencies = [
+ "aho-corasick",
+ "bstr",
+ "log",
+ "regex-automata",
+ "regex-syntax",
+]
+
[[package]]
name = "gloo-timers"
version = "0.3.0"
@@ -4022,6 +4123,57 @@ dependencies = [
"subtle",
]
+[[package]]
+name = "guppy"
+version = "0.17.26"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eb611f63088c20f3f7252d896f0beaa176a9628da8c21cdf258fe9ae179bebda"
+dependencies = [
+ "ahash 0.8.12",
+ "camino",
+ "cargo_metadata",
+ "cfg-if",
+ "debug-ignore",
+ "fixedbitset 0.5.7",
+ "guppy-summaries",
+ "guppy-workspace-hack",
+ "indexmap 2.13.0",
+ "itertools 0.14.0",
+ "nested",
+ "once_cell",
+ "pathdiff",
+ "petgraph 0.8.3",
+ "rayon",
+ "semver",
+ "serde",
+ "serde_json",
+ "smallvec",
+ "static_assertions",
+ "target-spec",
+ "toml",
+]
+
+[[package]]
+name = "guppy-summaries"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8bd039b8f587513b48754811cfa37c2ba079df537b490b602fa641ce18f6e72a"
+dependencies = [
+ "camino",
+ "cfg-if",
+ "diffus",
+ "guppy-workspace-hack",
+ "semver",
+ "serde",
+ "toml",
+]
+
+[[package]]
+name = "guppy-workspace-hack"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92620684d99f750bae383ecb3be3748142d6095760afd5cbcf2261e9a279d780"
+
[[package]]
name = "h2"
version = "0.3.27"
@@ -6057,6 +6209,12 @@ dependencies = [
"syn 2.0.117",
]
+[[package]]
+name = "nested"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca2b420f638f07fe83056b55ea190bb815f609ec5a35e7017884a10f78839c9e"
+
[[package]]
name = "new_debug_unreachable"
version = "1.0.6"
@@ -6622,6 +6780,15 @@ version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
+[[package]]
+name = "pathdiff"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3"
+dependencies = [
+ "camino",
+]
+
[[package]]
name = "pbkdf2"
version = "0.12.2"
@@ -7722,7 +7889,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b14b5775b5ff446dd1056212d778012cbe8a0fbffd368029fd9e25b514479c38"
dependencies = [
"once_cell",
- "target-lexicon",
+ "target-lexicon 0.12.16",
]
[[package]]
@@ -8854,6 +9021,10 @@ name = "semver"
version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
+dependencies = [
+ "serde",
+ "serde_core",
+]
[[package]]
name = "send_wrapper"
@@ -10033,6 +10204,24 @@ version = "0.12.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"
+[[package]]
+name = "target-lexicon"
+version = "0.13.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
+
+[[package]]
+name = "target-spec"
+version = "3.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b00e973676af5497c2a69cc9787e2205c00f3b6f4f70e7d7b0112e28aa84b501"
+dependencies = [
+ "cfg-expr",
+ "guppy-workspace-hack",
+ "serde",
+ "target-lexicon 0.13.5",
+]
+
[[package]]
name = "tempfile"
version = "3.26.0"
@@ -10422,6 +10611,16 @@ dependencies = [
"tokio",
]
+[[package]]
+name = "toml"
+version = "0.5.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f4f7f0dd8d50a853a531c426359045b1998f04219d88799810762cd4ad314234"
+dependencies = [
+ "indexmap 1.9.3",
+ "serde",
+]
+
[[package]]
name = "toml_datetime"
version = "0.7.5+spec-1.1.0"
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 0fe47f3e75a7..4943c401ead8 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -52,6 +52,7 @@ members = [
"personhog-proto",
"personhog-replica",
"personhog-router",
+ "affected-services",
"property-vals-rs",
]
diff --git a/rust/affected-services/Cargo.toml b/rust/affected-services/Cargo.toml
new file mode 100644
index 000000000000..0cd22f238ebd
--- /dev/null
+++ b/rust/affected-services/Cargo.toml
@@ -0,0 +1,13 @@
+[package]
+name = "affected-services"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+anyhow = { workspace = true }
+clap = { workspace = true }
+determinator = "0.12"
+guppy = "0.17"
+serde = { workspace = true }
+serde_json = { workspace = true }
+tempfile = "3"
diff --git a/rust/affected-services/determinator-rules.toml b/rust/affected-services/determinator-rules.toml
new file mode 100644
index 000000000000..7a5b61338bd6
--- /dev/null
+++ b/rust/affected-services/determinator-rules.toml
@@ -0,0 +1,48 @@
+# Rules for the determinator crate.
+#
+# Custom rules are processed before default rules. Default rules already handle:
+# - .cargo/config, .cargo/config.toml → mark-changed = "all"
+# - Cargo.toml (workspace root) → mark-changed = "all"
+# - Cargo.lock → mark-changed = [] (ignored — we override below)
+# - README, LICENSE, .gitignore, etc. → mark-changed = []
+#
+# Paths are workspace-relative (strip the `rust/` repo prefix before passing).
+
+use-default-rules = true
+
+# Cargo.lock: When two graphs are available (--base-ref mode), the determinator
+# diffs resolved dependency versions directly — no rule needed. When only one
+# graph is available (fallback), compute_affected() handles the rebuild-all
+# logic in code. Either way, this rule is not needed here.
+#
+# The default determinator rule for Cargo.lock is mark-changed = [] (ignore),
+# which is what we want — the diff or the code handles it.
+
+# Dockerfiles and CI image config — cross-cutting build changes.
+[[path-rule]]
+globs = ["Dockerfile", "Dockerfile.sqlx-migrate", "../.github/rust-images.yml"]
+mark-changed = "all"
+
+# sqlx offline query metadata — affects all sqlx-using crates.
+[[path-rule]]
+globs = [".sqlx/**"]
+mark-changed = "all"
+
+# Proto files trigger the two build-script crates that read them.
+[[path-rule]]
+globs = ["../proto/**"]
+mark-changed = ["personhog-proto", "kafka-assigner-proto", "cymbal-proto"]
+
+# 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.
+[[path-rule]]
+globs = [
+ "persons_migrations/**",
+ "behavioral_cohorts_migrations/**",
+ "cyclotron-core/migrations/**",
+ "cyclotron-node-migrations/**",
+ "flags_read_store_migrations/**",
+ "bin/migrate-*",
+]
+mark-changed = []
diff --git a/rust/affected-services/src/affected.rs b/rust/affected-services/src/affected.rs
new file mode 100644
index 000000000000..a97f8d1f70c7
--- /dev/null
+++ b/rust/affected-services/src/affected.rs
@@ -0,0 +1,164 @@
+use std::collections::HashSet;
+
+use anyhow::{Context, Result};
+use determinator::rules::DeterminatorRules;
+use determinator::Determinator;
+use guppy::graph::{DependencyDirection, PackageGraph};
+use serde::Serialize;
+
+use crate::images::{
+ build_binary_to_crate_map, map_crates_to_images, non_crate_images_affected, ImageConfig,
+};
+use crate::RULES_TOML;
+const WORKSPACE_PREFIX: &str = "rust/";
+
+#[derive(Debug, Serialize)]
+pub struct AffectedResult {
+ pub rebuild_all: bool,
+ pub images: Vec<String>,
+ pub crates: Vec<String>,
+ pub directly_changed: Vec<String>,
+}
+
+/// Convert repo-root-relative paths to workspace-relative paths.
+///
+/// `rust/capture/src/main.rs` → `capture/src/main.rs`
+/// `proto/personhog.proto` → `../proto/personhog.proto`
+fn to_workspace_relative(repo_path: &str) -> String {
+ if let Some(rest) = repo_path.strip_prefix(WORKSPACE_PREFIX) {
+ rest.to_string()
+ } else {
+ format!("../{repo_path}")
+ }
+}
+
+pub fn compute_affected(
+ changed_files: &[String],
+ old_graph: Option<&PackageGraph>,
+ new_graph: &PackageGraph,
+ images: &[ImageConfig],
+) -> Result<AffectedResult> {
+ let rules =
+ DeterminatorRules::parse(RULES_TOML).context("failed to parse determinator rules")?;
+
+ let workspace_paths: Vec<String> = changed_files
+ .iter()
+ .map(|f| to_workspace_relative(f))
+ .collect();
+
+ // When no old graph is available (single-graph fallback) and Cargo.lock
+ // changed, the determinator can't diff resolved dependencies — it sees
+ // old == new. Force a full rebuild to be safe.
+ if old_graph.is_none()
+ && changed_files
+ .iter()
+ .any(|f| f == "rust/Cargo.lock" || f == "Cargo.lock")
+ {
+ let mut all_images: Vec<String> = images.iter().map(|i| i.image.clone()).collect();
+ all_images.sort();
+ let mut all_crates: Vec<String> = new_graph
+ .workspace()
+ .iter()
+ .map(|p| p.name().to_string())
+ .collect();
+ all_crates.sort();
+ return Ok(AffectedResult {
+ rebuild_all: true,
+ images: all_images,
+ crates: all_crates,
+ directly_changed: Vec::new(),
+ });
+ }
+
+ let old = old_graph.unwrap_or(new_graph);
+ let mut det = Determinator::new(old, new_graph);
+ det.set_rules(&rules)
+ .context("failed to set determinator rules")?;
+ det.add_changed_paths(workspace_paths.iter().map(|s| s.as_str()));
+ let result = det.compute();
+
+ let workspace_size = new_graph.workspace().iter().count();
+ let affected_count = result.affected_set.len();
+ let rebuild_all = affected_count == workspace_size;
+
+ let bin_to_crate = build_binary_to_crate_map(new_graph);
+
+ let affected_names: HashSet<String> = result
+ .affected_set
+ .packages(DependencyDirection::Forward)
+ .map(|p| p.name().to_string())
+ .collect();
+
+ let directly_changed_names: HashSet<String> = result
+ .path_changed_set
+ .packages(DependencyDirection::Forward)
+ .map(|p| p.name().to_string())
+ .collect();
+
+ if rebuild_all {
+ let mut all_images: Vec<String> = images.iter().map(|i| i.image.clone()).collect();
+ all_images.sort();
+ let mut all_crates: Vec<String> = affected_names.into_iter().collect();
+ all_crates.sort();
+ return Ok(AffectedResult {
+ rebuild_all: true,
+ images: all_images,
+ crates: all_crates,
+ directly_changed: Vec::new(),
+ });
+ }
+
+ let mut affected_images = map_crates_to_images(&affected_names, &bin_to_crate, images);
+ for img in non_crate_images_affected(changed_files) {
+ if !affected_images.contains(&img) {
+ affected_images.push(img);
+ }
+ }
+ affected_images.sort();
+
+ let mut crates: Vec<String> = affected_names.into_iter().collect();
+ crates.sort();
+ let mut directly: Vec<String> = directly_changed_names.into_iter().collect();
+ directly.sort();
+
+ Ok(AffectedResult {
+ rebuild_all: false,
+ images: affected_images,
+ crates,
+ directly_changed: directly,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn workspace_relative_strips_rust_prefix() {
+ assert_eq!(
+ to_workspace_relative("rust/capture/src/main.rs"),
+ "capture/src/main.rs"
+ );
+ }
+
+ #[test]
+ fn workspace_relative_adds_parent_for_external() {
+ assert_eq!(
+ to_workspace_relative("proto/personhog.proto"),
+ "../proto/personhog.proto"
+ );
+ }
+
+ #[test]
+ fn workspace_relative_github_files() {
+ assert_eq!(
+ to_workspace_relative(".github/rust-images.yml"),
+ "../.github/rust-images.yml"
+ );
+ }
+
+ #[test]
+ fn rules_parse_successfully() {
+ DeterminatorRules::parse(RULES_TOML).expect("rules TOML should parse");
+ }
+}
diff --git a/rust/affected-services/src/dump.rs b/rust/affected-services/src/dump.rs
new file mode 100644
index 000000000000..8c9f327c6b16
--- /dev/null
+++ b/rust/affected-services/src/dump.rs
@@ -0,0 +1,134 @@
+use std::collections::{HashMap, HashSet};
+
+use determinator::rules::DeterminatorRules;
+use determinator::Determinator;
+use guppy::graph::{DependencyDirection, PackageGraph};
+
+use crate::images::{build_binary_to_crate_map, map_crates_to_images, ImageConfig};
+use crate::RULES_TOML;
+
+pub fn dump_graph(graph: &PackageGraph, images: &[ImageConfig]) {
+ let bin_to_crate = build_binary_to_crate_map(graph);
+
+ let mut crate_to_bins: HashMap<&str, Vec<&str>> = HashMap::new();
+ for (bin_name, crate_name) in &bin_to_crate {
+ crate_to_bins
+ .entry(crate_name.as_str())
+ .or_default()
+ .push(bin_name.as_str());
+ }
+
+ let deployable_crates: HashSet<&str> = images
+ .iter()
+ .filter_map(|img| {
+ let bin_name = img.bin.as_deref().unwrap_or(&img.image);
+ bin_to_crate.get(bin_name).map(|s| s.as_str())
+ })
+ .collect();
+
+ println!("REVERSE DEPENDENCY GRAPH");
+ println!("(crate → workspace crates that depend on it)");
+ println!("{}", "=".repeat(70));
+
+ let mut members: Vec<_> = graph.workspace().iter().collect();
+ members.sort_by_key(|m| m.name().to_string());
+
+ for member in &members {
+ let name = member.name();
+
+ let mut dependents: Vec<String> = Vec::new();
+ for link in member.reverse_direct_links() {
+ let from = link.from();
+ if !graph.workspace().contains_name(from.name()) {
+ continue;
+ }
+ let is_dev_only = !link.normal().is_present() && !link.build().is_present();
+ if !is_dev_only {
+ dependents.push(from.name().to_string());
+ }
+ }
+ dependents.sort();
+
+ let mut tags = Vec::new();
+ if let Some(bins) = crate_to_bins.get(name) {
+ let mut bins = bins.clone();
+ bins.sort();
+ tags.push(format!("bins: {}", bins.join(", ")));
+ }
+ if deployable_crates.contains(name) {
+ tags.push("deployable".to_string());
+ }
+ let tag_str = if tags.is_empty() {
+ String::new()
+ } else {
+ format!(" [{}]", tags.join(", "))
+ };
+
+ let dep_str = if dependents.is_empty() {
+ "(leaf)".to_string()
+ } else {
+ dependents.join(", ")
+ };
+
+ println!(" {name}{tag_str}");
+ println!(" depended on by: {dep_str}");
+ }
+
+ println!();
+ println!("TRANSITIVE IMPACT (crates affecting >2 others)");
+ println!("{}", "=".repeat(70));
+
+ let rules = DeterminatorRules::parse(RULES_TOML).expect("rules should parse");
+
+ let mut impacts: Vec<(&str, usize, Vec<String>)> = Vec::new();
+ for member in &members {
+ let name = member.name();
+ let workspace_path = format!("{}/src/lib.rs", member.source().workspace_path().unwrap());
+ let mut det = Determinator::new(graph, graph);
+ det.set_rules(&rules).unwrap();
+ det.add_changed_paths(std::iter::once(workspace_path.as_str()));
+ let result = det.compute();
+
+ let affected: HashSet<String> = result
+ .affected_set
+ .packages(DependencyDirection::Forward)
+ .map(|p| p.name().to_string())
+ .collect();
+ let affected_images = map_crates_to_images(&affected, &bin_to_crate, images);
+ let dep_count = affected.len().saturating_sub(1);
+ if dep_count > 2 {
+ impacts.push((name, dep_count, affected_images));
+ }
+ }
+ impacts.sort_by(|a, b| b.1.cmp(&a.1));
+
+ for (crate_name, dep_count, imgs) in &impacts {
+ println!(" {crate_name} → {dep_count} crates, {} images", imgs.len());
+ if !imgs.is_empty() {
+ println!(" images: {}", imgs.join(", "));
+ }
+ }
+
+ println!();
+ println!("BINARY → CRATE → IMAGE MAPPING");
+ println!("{}", "=".repeat(70));
+
+ let mut sorted_images: Vec<&ImageConfig> = images.iter().collect();
+ sorted_images.sort_by_key(|i| &i.image);
+
+ for img in sorted_images {
+ let bin_name = img.bin.as_deref().unwrap_or(&img.image);
+ let owning = bin_to_crate
+ .get(bin_name)
+ .map(|s| s.as_str())
+ .unwrap_or("???");
+ let mut extra = String::new();
+ if img.bin.is_some() {
+ extra.push_str(&format!(" (bin={bin_name})"));
+ }
+ println!(
+ " image:{} ← crate:{owning} ← bin:{bin_name}{extra}",
+ img.image
+ );
+ }
+}
diff --git a/rust/affected-services/src/graph.rs b/rust/affected-services/src/graph.rs
new file mode 100644
index 000000000000..9e4e51048f51
--- /dev/null
+++ b/rust/affected-services/src/graph.rs
@@ -0,0 +1,115 @@
+use std::path::{Path, PathBuf};
+use std::process::Command;
+
+use anyhow::{Context, Result};
+use guppy::graph::PackageGraph;
+use guppy::MetadataCommand;
+
+pub fn find_repo_root() -> Result<PathBuf> {
+ let out = Command::new("git")
+ .args(["rev-parse", "--show-toplevel"])
+ .output()
+ .context("failed to run git")?;
+ Ok(PathBuf::from(
+ String::from_utf8(out.stdout)?.trim().to_string(),
+ ))
+}
+
+pub fn get_changed_files(base_ref: &str) -> Result<Vec<String>> {
+ let out = Command::new("git")
+ .args(["diff", "--name-only", &format!("{base_ref}...HEAD")])
+ .output()
+ .context("failed to run git diff")?;
+ anyhow::ensure!(
+ out.status.success(),
+ "git diff exited with {}: {}",
+ out.status,
+ String::from_utf8_lossy(&out.stderr).trim()
+ );
+ Ok(String::from_utf8(out.stdout)?
+ .lines()
+ .filter(|l| !l.is_empty())
+ .map(String::from)
+ .collect())
+}
+
+pub fn build_package_graph(workspace_dir: &Path) -> Result<PackageGraph> {
+ let mut cmd = MetadataCommand::new();
+ cmd.current_dir(workspace_dir);
+ cmd.build_graph()
+ .context("failed to build package graph from cargo metadata")
+}
+
+struct TempWorktree {
+ path: PathBuf,
+}
+
+impl TempWorktree {
+ fn create(base_ref: &str) -> Result<Self> {
+ let path = tempfile::Builder::new()
+ .prefix("affected-services-")
+ .tempdir()
+ .context("failed to create temp directory")?
+ .keep();
+ let out = Command::new("git")
+ .args([
+ "worktree",
+ "add",
+ "--detach",
+ &path.to_string_lossy(),
+ base_ref,
+ ])
+ .output()
+ .context("failed to create git worktree")?;
+ anyhow::ensure!(
+ out.status.success(),
+ "git worktree add failed: {}",
+ String::from_utf8_lossy(&out.stderr).trim()
+ );
+ Ok(Self { path })
+ }
+
+ fn path(&self) -> &Path {
+ &self.path
+ }
+}
+
+impl Drop for TempWorktree {
+ fn drop(&mut self) {
+ let _ = Command::new("git")
+ .args([
+ "worktree",
+ "remove",
+ "--force",
+ &self.path.to_string_lossy(),
+ ])
+ .status();
+ }
+}
+
+pub fn build_old_package_graph(base_ref: &str, workspace_subdir: &str) -> Option<PackageGraph> {
+ let worktree = match TempWorktree::create(base_ref) {
+ Ok(w) => w,
+ Err(e) => {
+ eprintln!("warning: could not create worktree at {base_ref}: {e}");
+ return None;
+ }
+ };
+
+ let old_workspace = worktree.path().join(workspace_subdir);
+ if !old_workspace.join("Cargo.toml").exists() {
+ eprintln!("warning: {base_ref} has no {workspace_subdir}/Cargo.toml");
+ return None;
+ }
+
+ let mut cmd = MetadataCommand::new();
+ cmd.current_dir(&old_workspace);
+ cmd.other_options(["--locked"]);
+ match cmd.build_graph() {
+ Ok(graph) => Some(graph),
+ Err(e) => {
+ eprintln!("warning: could not build old package graph: {e}");
+ None
+ }
+ }
+}
diff --git a/rust/affected-services/src/images.rs b/rust/affected-services/src/images.rs
new file mode 100644
index 000000000000..dfbe81ec5a52
--- /dev/null
+++ b/rust/affected-services/src/images.rs
@@ -0,0 +1,238 @@
+use std::collections::{HashMap, HashSet};
+use std::path::Path;
+
+use anyhow::{Context, Result};
+use guppy::graph::PackageGraph;
+
+pub const NON_CRATE_IMAGE_TRIGGERS: &[(&str, &[&str])] = &[(
+ "sqlx-migrate",
+ &[
+ "rust/persons_migrations/",
+ "rust/behavioral_cohorts_migrations/",
+ "rust/cyclotron-core/migrations/",
+ "rust/cyclotron-node-migrations/",
+ "rust/flags_read_store_migrations/",
+ "rust/bin/migrate-",
+ "rust/Dockerfile.sqlx-migrate",
+ ],
+)];
+
+#[derive(Debug, Default)]
+pub struct ImageConfig {
+ pub image: String,
+ pub bin: Option<String>,
+}
+
+pub fn parse_images_yaml(path: &Path) -> Result<Vec<ImageConfig>> {
+ let content = std::fs::read_to_string(path)
+ .with_context(|| format!("failed to read {}", path.display()))?;
+ parse_images_yaml_content(&content)
+}
+
+pub fn parse_images_yaml_content(content: &str) -> Result<Vec<ImageConfig>> {
+ let mut items = Vec::new();
+ let mut current: Option<ImageConfig> = None;
+
+ for line in content.lines() {
+ let trimmed = line.trim();
+ if trimmed.is_empty() || trimmed.starts_with('#') {
+ continue;
+ }
+ if line.starts_with("- ") {
+ if let Some(item) = current.take() {
+ items.push(item);
+ }
+ current = Some(ImageConfig::default());
+ let rest = trimmed.strip_prefix("- ").unwrap_or(trimmed);
+ if let Some(item) = current.as_mut() {
+ apply_field(item, rest);
+ }
+ } else if let Some(ref mut item) = current {
+ apply_field(item, trimmed);
+ }
+ }
+ if let Some(item) = current {
+ items.push(item);
+ }
+ Ok(items)
+}
+
+fn apply_field(config: &mut ImageConfig, line: &str) {
+ if let Some((key, value)) = line.split_once(':') {
+ let value = value.trim();
+ match key.trim() {
+ "image" => config.image = value.to_string(),
+ "bin" => config.bin = Some(value.to_string()),
+ _ => {}
+ }
+ }
+}
+
+pub fn build_binary_to_crate_map(graph: &PackageGraph) -> HashMap<String, String> {
+ let mut map = HashMap::new();
+ for member in graph.workspace().iter() {
+ for target in member.build_targets() {
+ if let guppy::graph::BuildTargetId::Binary(name) = target.id() {
+ map.insert(name.to_string(), member.name().to_string());
+ }
+ }
+ }
+ map
+}
+
+pub fn map_crates_to_images(
+ affected: &HashSet<String>,
+ bin_to_crate: &HashMap<String, String>,
+ images: &[ImageConfig],
+) -> Vec<String> {
+ let mut result: Vec<String> = images
+ .iter()
+ .filter_map(|img| {
+ let bin_name = img.bin.as_deref().unwrap_or(&img.image);
+ let owning_crate = bin_to_crate.get(bin_name)?;
+ affected.contains(owning_crate).then(|| img.image.clone())
+ })
+ .collect();
+ result.sort();
+ result
+}
+
+pub fn non_crate_images_affected(files: &[String]) -> Vec<String> {
+ let mut result = Vec::new();
+ for &(image, prefixes) in NON_CRATE_IMAGE_TRIGGERS {
+ if files
+ .iter()
+ .any(|f| prefixes.iter().any(|p| f.starts_with(p)))
+ {
+ result.push(image.to_string());
+ }
+ }
+ result
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn simple_entry() {
+ let yaml = "- image: capture\n dockerfile: ./rust/Dockerfile\n";
+ let items = parse_images_yaml_content(yaml).unwrap();
+ assert_eq!(items.len(), 1);
+ assert_eq!(items[0].image, "capture");
+ assert!(items[0].bin.is_none());
+ }
+
+ #[test]
+ fn with_bin_override() {
+ let yaml = "- image: flags-cache-warmer\n bin: warm-flags-cache\n";
+ let items = parse_images_yaml_content(yaml).unwrap();
+ assert_eq!(items.len(), 1);
+ assert_eq!(items[0].image, "flags-cache-warmer");
+ assert_eq!(items[0].bin.as_deref(), Some("warm-flags-cache"));
+ }
+
+ #[test]
+ fn multiple_entries() {
+ let yaml = "\
+- image: capture
+ dockerfile: ./rust/Dockerfile
+
+- image: cymbal
+ dockerfile: ./rust/Dockerfile
+
+- image: flags-cache-warmer
+ bin: warm-flags-cache
+ dockerfile: ./rust/Dockerfile
+";
+ let items = parse_images_yaml_content(yaml).unwrap();
+ assert_eq!(items.len(), 3);
+ assert_eq!(items[0].image, "capture");
+ assert_eq!(items[1].image, "cymbal");
+ assert_eq!(items[2].image, "flags-cache-warmer");
+ assert_eq!(items[2].bin.as_deref(), Some("warm-flags-cache"));
+ }
+
+ #[test]
+ fn skips_comments_and_blank_lines() {
+ let yaml = "\
+# This is a comment
+- image: capture
+
+ # inline comment
+ dockerfile: ./rust/Dockerfile
+
+";
+ let items = parse_images_yaml_content(yaml).unwrap();
+ assert_eq!(items.len(), 1);
+ assert_eq!(items[0].image, "capture");
+ }
+
+ #[test]
+ fn ignores_unknown_fields() {
+ let yaml = "- image: capture\n dockerfile: ./rust/Dockerfile\n project: abc123\n features: some-feature\n target: runtime-jumphost\n";
+ let items = parse_images_yaml_content(yaml).unwrap();
+ assert_eq!(items.len(), 1);
+ assert_eq!(items[0].image, "capture");
+ assert!(items[0].bin.is_none());
+ }
+
+ #[test]
+ fn empty_input() {
+ let items = parse_images_yaml_content("").unwrap();
+ assert!(items.is_empty());
+ }
+
+ #[test]
+ fn comments_only() {
+ let items = parse_images_yaml_content("# just a comment\n# another one\n").unwrap();
+ assert!(items.is_empty());
+ }
+
+ #[test]
+ fn inline_image_on_dash_line() {
+ let yaml = "- image: capture\n";
+ let items = parse_images_yaml_content(yaml).unwrap();
+ assert_eq!(items.len(), 1);
+ assert_eq!(items[0].image, "capture");
+ }
+
+ #[test]
+ fn non_crate_migration_trigger() {
+ let affected = non_crate_images_affected(&["rust/persons_migrations/new.sql".into()]);
+ assert_eq!(affected, vec!["sqlx-migrate"]);
+ }
+
+ #[test]
+ fn non_crate_no_false_positives() {
+ let affected = non_crate_images_affected(&["rust/capture/src/main.rs".into()]);
+ assert!(affected.is_empty());
+ }
+
+ #[test]
+ fn image_mapping() {
+ let affected = HashSet::from(["feature-flags".into()]);
+ let bin_to_crate = HashMap::from([
+ ("feature-flags".into(), "feature-flags".into()),
+ ("warm-flags-cache".into(), "feature-flags".into()),
+ ("capture".into(), "capture".into()),
+ ]);
+ let images = vec![
+ ImageConfig {
+ image: "feature-flags".into(),
+ bin: None,
+ },
+ ImageConfig {
+ image: "flags-cache-warmer".into(),
+ bin: Some("warm-flags-cache".into()),
+ },
+ ImageConfig {
+ image: "capture".into(),
+ bin: None,
+ },
+ ];
+
+ let result = map_crates_to_images(&affected, &bin_to_crate, &images);
+ assert_eq!(result, vec!["feature-flags", "flags-cache-warmer"]);
+ }
+}
diff --git a/rust/affected-services/src/lib.rs b/rust/affected-services/src/lib.rs
new file mode 100644
index 000000000000..ff417ac9ee62
--- /dev/null
+++ b/rust/affected-services/src/lib.rs
@@ -0,0 +1,6 @@
+pub mod affected;
+pub mod dump;
+pub mod graph;
+pub mod images;
+
+pub const RULES_TOML: &str = include_str!("../determinator-rules.toml");
diff --git a/rust/affected-services/src/main.rs b/rust/affected-services/src/main.rs
new file mode 100644
index 000000000000..3b97daed0963
--- /dev/null
+++ b/rust/affected-services/src/main.rs
@@ -0,0 +1,94 @@
+use std::io::BufRead;
+use std::path::Path;
+
+use anyhow::Result;
+use clap::{Parser, ValueEnum};
+
+use affected_services::affected::compute_affected;
+use affected_services::dump::dump_graph;
+use affected_services::graph::{
+ build_old_package_graph, build_package_graph, find_repo_root, get_changed_files,
+};
+use affected_services::images::parse_images_yaml;
+
+#[derive(Parser)]
+#[command(about = "Compute affected Rust services from changed files")]
+struct Cli {
+ #[arg(long, conflicts_with_all = ["files", "stdin", "dump_graph"])]
+ base_ref: Option<String>,
+
+ #[arg(long, num_args = 1.., conflicts_with_all = ["base_ref", "stdin", "dump_graph"])]
+ files: Option<Vec<String>>,
+
+ #[arg(long, conflicts_with_all = ["base_ref", "files", "dump_graph"])]
+ stdin: bool,
+
+ #[arg(long, conflicts_with_all = ["base_ref", "files", "stdin"])]
+ dump_graph: bool,
+
+ #[arg(long)]
+ workspace_dir: Option<std::path::PathBuf>,
+
+ #[arg(long)]
+ images_file: Option<std::path::PathBuf>,
+
+ #[arg(long, value_enum, default_value = "json")]
+ output: OutputFormat,
+}
+
+#[derive(Clone, ValueEnum)]
+enum OutputFormat {
+ Json,
+ Images,
+ Crates,
+}
+
+fn main() -> Result<()> {
+ let cli = Cli::parse();
+
+ let repo_root = find_repo_root()?;
+ let workspace_dir = cli.workspace_dir.unwrap_or_else(|| repo_root.join("rust"));
+ let images_file = cli
+ .images_file
+ .unwrap_or_else(|| repo_root.join(".github/rust-images.yml"));
+
+ let new_graph = build_package_graph(&workspace_dir)?;
+ let images = parse_images_yaml(&images_file)?;
+
+ if cli.dump_graph {
+ dump_graph(&new_graph, &images);
+ return Ok(());
+ }
+
+ let (changed_files, old_graph) = if let Some(files) = cli.files {
+ (files, None)
+ } else if cli.stdin {
+ let files = std::io::stdin()
+ .lock()
+ .lines()
+ .map_while(Result::ok)
+ .filter(|l| !l.is_empty())
+ .collect();
+ (files, None)
+ } else if let Some(base_ref) = &cli.base_ref {
+ let files = get_changed_files(base_ref)?;
+ let workspace_subdir = workspace_dir
+ .strip_prefix(&repo_root)
+ .unwrap_or(Path::new("rust"))
+ .to_string_lossy()
+ .to_string();
+ let old = build_old_package_graph(base_ref, &workspace_subdir);
+ (files, old)
+ } else {
+ anyhow::bail!("one of --base-ref, --files, --stdin, or --dump-graph is required");
+ };
+
+ let result = compute_affected(&changed_files, old_graph.as_ref(), &new_graph, &images)?;
+
+ match cli.output {
+ OutputFormat::Json => println!("{}", serde_json::to_string_pretty(&result)?),
+ OutputFormat::Images => println!("{}", serde_json::to_string(&result.images)?),
+ OutputFormat::Crates => println!("{}", serde_json::to_string(&result.crates)?),
+ }
+ Ok(())
+}
diff --git a/rust/affected-services/tests/integration.rs b/rust/affected-services/tests/integration.rs
new file mode 100644
index 000000000000..033fd315d9c7
--- /dev/null
+++ b/rust/affected-services/tests/integration.rs
@@ -0,0 +1,396 @@
+use std::collections::HashSet;
+
+use affected_services::affected::compute_affected;
+use affected_services::graph::{build_old_package_graph, build_package_graph, find_repo_root};
+use affected_services::images::{
+ build_binary_to_crate_map, parse_images_yaml, ImageConfig, NON_CRATE_IMAGE_TRIGGERS,
+};
+use guppy::graph::PackageGraph;
+
+fn load_test_fixtures() -> (PackageGraph, Vec<ImageConfig>) {
+ let repo_root = find_repo_root().expect("must be in a git repo");
+ let graph = build_package_graph(&repo_root.join("rust")).expect("cargo metadata");
+ let images =
+ parse_images_yaml(&repo_root.join(".github/rust-images.yml")).expect("images YAML");
+ (graph, images)
+}
+
+// ── Structural tests ─────────────────────────────────────────────
+
+#[test]
+fn file_in_workspace_crate_affects_that_crate() {
+ let (graph, images) = load_test_fixtures();
+ let member = graph.workspace().iter().next().unwrap();
+ let fake_path = format!(
+ "rust/{}/src/lib.rs",
+ member.source().workspace_path().unwrap()
+ );
+ let result = compute_affected(&[fake_path], None, &graph, &images).unwrap();
+ assert!(!result.rebuild_all);
+ assert!(
+ result.crates.contains(&member.name().to_string()),
+ "changing a file in {} should mark it affected",
+ member.name()
+ );
+}
+
+#[test]
+fn directly_changed_is_subset_of_crates() {
+ let (graph, images) = load_test_fixtures();
+ let member = graph.workspace().iter().next().unwrap();
+ let fake_path = format!(
+ "rust/{}/src/lib.rs",
+ member.source().workspace_path().unwrap()
+ );
+ let result = compute_affected(&[fake_path], None, &graph, &images).unwrap();
+ let crates: HashSet<&str> = result.crates.iter().map(|s| s.as_str()).collect();
+ for dc in &result.directly_changed {
+ assert!(
+ crates.contains(dc.as_str()),
+ "directly_changed entry {dc} must appear in crates"
+ );
+ }
+}
+
+#[test]
+fn rebuild_all_marks_every_workspace_crate() {
+ let (graph, images) = load_test_fixtures();
+ let result = compute_affected(&["rust/Cargo.lock".into()], None, &graph, &images).unwrap();
+ assert!(result.rebuild_all);
+ let workspace_count = graph.workspace().iter().count();
+ assert_eq!(
+ result.crates.len(),
+ workspace_count,
+ "rebuild_all should include all {} workspace crates",
+ workspace_count
+ );
+}
+
+#[test]
+fn file_outside_workspace_produces_no_crates() {
+ let (graph, images) = load_test_fixtures();
+ let result = compute_affected(&["README.md".into()], None, &graph, &images).unwrap();
+ assert!(!result.rebuild_all);
+ assert!(result.crates.is_empty());
+ assert!(result.images.is_empty());
+}
+
+#[test]
+fn multi_file_is_union() {
+ let (graph, images) = load_test_fixtures();
+ let members: Vec<_> = graph.workspace().iter().collect();
+ let (a, b) = (&members[0], &members[1]);
+ let path_a = format!("rust/{}/src/lib.rs", a.source().workspace_path().unwrap());
+ let path_b = format!("rust/{}/src/lib.rs", b.source().workspace_path().unwrap());
+
+ let result_a = compute_affected(std::slice::from_ref(&path_a), None, &graph, &images).unwrap();
+ let result_b = compute_affected(std::slice::from_ref(&path_b), None, &graph, &images).unwrap();
+ let result_both = compute_affected(&[path_a, path_b], None, &graph, &images).unwrap();
+
+ let union: HashSet<&str> = result_a
+ .crates
+ .iter()
+ .chain(&result_b.crates)
+ .map(|s| s.as_str())
+ .collect();
+ let combined: HashSet<&str> = result_both.crates.iter().map(|s| s.as_str()).collect();
+ assert_eq!(
+ union, combined,
+ "multi-file result should be the union of individual results"
+ );
+}
+
+// ── Completeness tests ──────────────────────────────────────────
+
+#[test]
+fn every_deployable_binary_has_an_image_entry() {
+ let non_deployable: HashSet<&str> =
+ ["affected-services", "debug_rule", "stl_dump", "hermes"].into();
+
+ let (graph, images) = load_test_fixtures();
+ let bin_to_crate = build_binary_to_crate_map(&graph);
+
+ let image_binaries: HashSet<&str> = images
+ .iter()
+ .map(|img| img.bin.as_deref().unwrap_or(&img.image))
+ .collect();
+
+ let mut missing = Vec::new();
+ for bin_name in bin_to_crate.keys() {
+ if non_deployable.contains(bin_name.as_str()) {
+ continue;
+ }
+ if !image_binaries.contains(bin_name.as_str()) {
+ missing.push(bin_name.as_str());
+ }
+ }
+ missing.sort();
+ assert!(
+ missing.is_empty(),
+ "workspace binaries missing from .github/rust-images.yml: {:?}\n\
+ If these are not deployable services, add them to `non_deployable` in this test.",
+ missing,
+ );
+}
+
+#[test]
+fn proto_build_scripts_are_in_determinator_rules() {
+ let repo_root = find_repo_root().expect("must be in a git repo");
+ let workspace_dir = repo_root.join("rust");
+
+ let rules_content =
+ std::fs::read_to_string(workspace_dir.join("affected-services/determinator-rules.toml"))
+ .expect("determinator-rules.toml");
+
+ let mut proto_rule_crates: HashSet<String> = HashSet::new();
+ let mut in_proto_rule = false;
+ let mut in_mark_changed = false;
+ for line in rules_content.lines() {
+ let trimmed = line.trim();
+ if trimmed == "[[path-rule]]" {
+ in_proto_rule = false;
+ in_mark_changed = false;
+ }
+ if trimmed.contains("../proto/**") {
+ in_proto_rule = true;
+ }
+ if in_proto_rule && trimmed.starts_with("mark-changed") {
+ in_mark_changed = true;
+ }
+ if in_mark_changed {
+ for part in trimmed.split('"') {
+ let part = part.trim();
+ if !part.is_empty()
+ && !part.contains("mark-changed")
+ && !part.contains('[')
+ && !part.contains(']')
+ && !part.contains(',')
+ && !part.contains('=')
+ {
+ proto_rule_crates.insert(part.to_string());
+ }
+ }
+ if trimmed.contains(']') {
+ in_mark_changed = false;
+ }
+ }
+ }
+
+ let graph = build_package_graph(&workspace_dir).expect("cargo metadata");
+
+ let mut missing = Vec::new();
+ for member in graph.workspace().iter() {
+ let crate_dir = workspace_dir.join(
+ member
+ .source()
+ .workspace_path()
+ .expect("workspace member has path"),
+ );
+ let build_rs = crate_dir.join("build.rs");
+ if !build_rs.exists() {
+ continue;
+ }
+ let content = std::fs::read_to_string(&build_rs).unwrap_or_default();
+ if (content.contains("tonic_build")
+ || content.contains("prost_build")
+ || content.contains("protobuf_codegen"))
+ && !proto_rule_crates.contains(member.name())
+ {
+ missing.push(member.name().to_string());
+ }
+ }
+ missing.sort();
+ assert!(
+ missing.is_empty(),
+ "crates with proto build scripts missing from determinator-rules.toml proto rule: {:?}\n\
+ Add these to the `mark-changed` list for the `../proto/**` path-rule.",
+ missing,
+ );
+}
+
+// ── Concrete tests ───────────────────────────────────────────────
+//
+// Update these when adding/removing/renaming services.
+
+#[test]
+fn every_image_resolves_to_a_workspace_binary() {
+ let (graph, images) = load_test_fixtures();
+ let bin_to_crate = build_binary_to_crate_map(&graph);
+ for img in &images {
+ let bin_name = img.bin.as_deref().unwrap_or(&img.image);
+ if NON_CRATE_IMAGE_TRIGGERS
+ .iter()
+ .any(|&(name, _)| name == img.image)
+ {
+ continue;
+ }
+ assert!(
+ bin_to_crate.contains_key(bin_name),
+ "image '{}' references binary '{}' which doesn't exist in the workspace",
+ img.image,
+ bin_name,
+ );
+ }
+}
+
+#[test]
+fn leaf_service_only_affects_itself_and_dependents() {
+ let (graph, images) = load_test_fixtures();
+ let result =
+ compute_affected(&["rust/capture/src/main.rs".into()], None, &graph, &images).unwrap();
+ assert!(!result.rebuild_all);
+ assert_eq!(result.directly_changed, vec!["capture"]);
+ assert_eq!(result.images, vec!["capture", "capture-logs"]);
+}
+
+#[test]
+fn proto_change_maps_to_proto_crates() {
+ let (graph, images) = load_test_fixtures();
+ let result =
+ compute_affected(&["proto/personhog.proto".into()], None, &graph, &images).unwrap();
+ assert!(!result.rebuild_all);
+ assert!(result.directly_changed.contains(&"personhog-proto".into()));
+ assert!(result
+ .directly_changed
+ .contains(&"kafka-assigner-proto".into()));
+ assert!(
+ result.images.len() > 2,
+ "proto change should propagate to multiple images"
+ );
+}
+
+#[test]
+fn migration_only_triggers_sqlx_migrate() {
+ let (graph, images) = load_test_fixtures();
+ let result = compute_affected(
+ &["rust/persons_migrations/new.sql".into()],
+ None,
+ &graph,
+ &images,
+ )
+ .unwrap();
+ assert!(!result.rebuild_all);
+ assert_eq!(result.images, vec!["sqlx-migrate"]);
+ assert!(result.crates.is_empty());
+}
+
+#[test]
+fn multi_binary_crate_produces_all_images() {
+ let (graph, images) = load_test_fixtures();
+ let result = compute_affected(
+ &["rust/feature-flags/src/lib.rs".into()],
+ None,
+ &graph,
+ &images,
+ )
+ .unwrap();
+ assert!(!result.rebuild_all);
+ assert!(result.images.contains(&"feature-flags".into()));
+ assert!(result.images.contains(&"flags-cache-warmer".into()));
+}
+
+// ── Determinator two-graph tests ─────────────────────────────────
+
+#[test]
+fn same_old_and_new_graph_matches_none_fallback() {
+ let (graph, images) = load_test_fixtures();
+ let changed = vec!["rust/capture/src/main.rs".into()];
+
+ let result_none = compute_affected(&changed, None, &graph, &images).unwrap();
+ let result_some = compute_affected(&changed, Some(&graph), &graph, &images).unwrap();
+
+ assert_eq!(result_none.crates, result_some.crates);
+ assert_eq!(result_none.images, result_some.images);
+ assert_eq!(result_none.rebuild_all, result_some.rebuild_all);
+ assert_eq!(result_none.directly_changed, result_some.directly_changed);
+}
+
+#[test]
+fn old_graph_no_changed_files_produces_empty() {
+ let (graph, images) = load_test_fixtures();
+ let result = compute_affected(&[], Some(&graph), &graph, &images).unwrap();
+ assert!(!result.rebuild_all);
+ assert!(result.crates.is_empty());
+ assert!(result.images.is_empty());
+}
+
+#[test]
+fn two_graph_lockfile_with_identical_graphs_is_noop() {
+ let (graph, images) = load_test_fixtures();
+ let result =
+ compute_affected(&["rust/Cargo.lock".into()], Some(&graph), &graph, &images).unwrap();
+ assert!(
+ !result.rebuild_all,
+ "two identical graphs should detect no dependency changes from Cargo.lock"
+ );
+ assert!(result.crates.is_empty());
+}
+
+#[test]
+fn single_graph_lockfile_triggers_rebuild_all() {
+ let (graph, images) = load_test_fixtures();
+ let result = compute_affected(&["rust/Cargo.lock".into()], None, &graph, &images).unwrap();
+ assert!(
+ result.rebuild_all,
+ "Cargo.lock change without old graph should force rebuild-all"
+ );
+ let workspace_count = graph.workspace().iter().count();
+ assert_eq!(result.crates.len(), workspace_count);
+}
+
+#[test]
+fn old_graph_leaf_service() {
+ let (graph, images) = load_test_fixtures();
+ let result = compute_affected(
+ &["rust/capture/src/main.rs".into()],
+ Some(&graph),
+ &graph,
+ &images,
+ )
+ .unwrap();
+ assert!(!result.rebuild_all);
+ assert_eq!(result.directly_changed, vec!["capture"]);
+ assert!(result.crates.contains(&"capture".into()));
+}
+
+#[test]
+fn old_graph_proto_propagation() {
+ let (graph, images) = load_test_fixtures();
+ let result = compute_affected(
+ &["proto/personhog.proto".into()],
+ Some(&graph),
+ &graph,
+ &images,
+ )
+ .unwrap();
+ assert!(!result.rebuild_all);
+ assert!(result.directly_changed.contains(&"personhog-proto".into()));
+ assert!(
+ result.images.len() > 2,
+ "proto change should propagate to multiple images via old_graph path"
+ );
+}
+
+#[test]
+fn old_graph_from_master() {
+ let repo_root = find_repo_root().expect("must be in a git repo");
+ let old_graph = match build_old_package_graph("master", "rust") {
+ Some(g) => g,
+ None => {
+ eprintln!("skipping: could not build old graph from master");
+ return;
+ }
+ };
+ let new_graph = build_package_graph(&repo_root.join("rust")).expect("cargo metadata");
+ let images =
+ parse_images_yaml(&repo_root.join(".github/rust-images.yml")).expect("images YAML");
+
+ let result = compute_affected(
+ &["rust/capture/src/main.rs".into()],
+ Some(&old_graph),
+ &new_graph,
+ &images,
+ )
+ .unwrap();
+ assert!(result.crates.contains(&"capture".into()));
+}