From e95fe4151ba855902f7cfa9ea5b362a50b2c56a6 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Wed, 11 Nov 2026 03:34:26 -0600 Subject: [PATCH 1/3] feat(fleet): derived per-app versioning from tags (#8566) Implement the #5790 ruled policy (2026-11-06) for the fleet apps in pkgs/fleet: the version a binary reports is derived at build time, never a hand-maintained literal. - New pure derivation module (crates/fleet/src/derived_version.rs, shared with build.rs by path): nearest /vX.Y.Z tag exactly -> X.Y.Z; N commits after on main -> X.Y.(Z+1)-dev.N+g; feature branch adds +; no tag yet -> the 0.1.0-dev fallback family. 9 unit tests whose oracle is the #5790 sec.1 policy text (tag-present, no-tag, prerelease-from-main cases). - build.rs bakes FLEET_DERIVED_VERSION via git describe --match 'fleet/v*' (short app name = tag prefix for all apps), with $FLEET_DERIVED_VERSION as the packaged-build channel - the same channel shape as the existing FLEET_SOURCE_REV bake. - Surface: `fleet version`, `fleet capabilities` (build. derived_version) and every --version form now print `Derived version: ...` alongside the source rev, so --version and the #5760 deployed-state checks can consume it. - README gains the tag/release procedure where the fleet release tooling lives: per-app short-name tags, first tag 0.1.0, stay in 0.x (minor = features, patch = fixes, no major bumps), releases are tag builds only, main deploys are prereleases, repo tags repo/v.. at release points (prerelease repo tags on deploys allowed). - smoke.sh asserts the derived-version line on the version surfaces. Tests: cargo test -p fleet --locked - 28+1+7 passed. A binary built from this branch reports: Derived version: 0.1.0-dev.11339+g3c42146+queue-14886-8566-derived-version (no fleet/v* tag exists yet, so the no-tag fallback on a feature branch is the live proof). Out of scope per #8566: cutting the first real tags, any 1.0 move, the #5760 drift-check work itself. --- pkgs/fleet/README.md | 58 +++ pkgs/fleet/crates/fleet/build.rs | 100 ++++- .../fleet/crates/fleet/src/derived_version.rs | 354 ++++++++++++++++++ pkgs/fleet/crates/fleet/src/main.rs | 13 + pkgs/fleet/smoke.sh | 2 + 5 files changed, 511 insertions(+), 16 deletions(-) create mode 100644 pkgs/fleet/crates/fleet/src/derived_version.rs diff --git a/pkgs/fleet/README.md b/pkgs/fleet/README.md index 556987f138..98d03cbae9 100644 --- a/pkgs/fleet/README.md +++ b/pkgs/fleet/README.md @@ -116,6 +116,64 @@ default.nix the four variant packages (see below) smoke.sh per-variant smoke suite (post-build) ``` +## Versioning — derived per-app versions (#8566; policy #5790) + +A fleet binary's version is **derived, never hand-maintained**. The +workspace `version = "0.1.0"` in `Cargo.toml` is only the release-line +base cargo requires; the version a deployed binary reports — the one +`fleet version`, `fleet capabilities` (JSON `build.derived_version`) +and every `--version` surface print as `Derived version:` — is baked +at build time by `crates/fleet/build.rs` from the derivation in +`crates/fleet/src/derived_version.rs`, through the same channel that +reports the source rev (`FLEET_SOURCE_REV`): a packaged build with no +git history receives it as `$FLEET_DERIVED_VERSION`, computed by the +release tooling where the history exists. + +Derivation (nearest `/vX.Y.Z` tag on the build commit's history; +the app is this workspace's short name, `fleet`): + +| build state | reported version | +| --- | --- | +| exactly on the tag | `X.Y.Z` | +| on `main`, N commits after the tag | `X.Y.(Z+1)-dev.N+g` | +| on a feature branch, N commits after | `X.Y.(Z+1)-dev.N+g+` | +| no `/v*` tag yet | `0.1.0-dev.N+g` (bare `0.1.0-dev` if no history is available) | + +The `+g` suffix is what guarantees no two distinct commits ever +report the same version string; the patch-bump + `-dev.N` form is what +makes the string sort after the tag it descends from and before its +own release. + +### Tag and release procedure (ruled on #5790, 2026-11-06) + +1. **Per-app tags.** A release is cut by tagging the exact tested + commit `/vX.Y.Z` — for this workspace, + `fleet/vX.Y.Z`. The short app name is the tag prefix for ALL apps + (one policy, no per-app mixing); app names used in tags and + deploys must be unique across apps — if a short name would + collide, fix the app name, not the policy. +2. **First tag and 0.x discipline.** Each app's first tag is + `0.1.0`. Versions stay in 0.x: minor for feature releases, patch + for fixes, and **no major-version bumps** until a separate 1.0 + decision. +3. **Releases are tag builds only.** Build the release artifact + from the tagged commit and verify the artifact itself reports + the clean version: `./result/bin/fleet version` must show + `Derived version: X.Y.Z`. Builds deployed from `main` are + **prereleases** (their `-dev.N` strings say so) — deploying one + never makes it a release. +4. **Repo tags.** At every release point (not every commit, not + every deploy), also cut `repo/v..` — + the date is the major segment; within a date, a release point + including any app feature increments minor and resets patch, a + fix-only or repeat point increments patch; minor/patch may + reset to `0.0` on a new date. A repo **prerelease** tag on a + deploy from main is also fine and does not make the deploy a + release. +5. **Deploy truth.** What a target runs is read from the deployed + binary's own `Derived version:` line, never from paperwork + (that read is the #5760 deployed-state check's input). + ## Variants Capability surface = compiled features ∩ invocation-name profile ∩ diff --git a/pkgs/fleet/crates/fleet/build.rs b/pkgs/fleet/crates/fleet/build.rs index fedfa56d37..4b9d04903b 100644 --- a/pkgs/fleet/crates/fleet/build.rs +++ b/pkgs/fleet/crates/fleet/build.rs @@ -1,30 +1,98 @@ -//! Bake the source revision into the binary for `fleet version`. +//! Bake the source revision and the derived version into the +//! binary for `fleet version`. //! -//! Resolution: `$FLEET_SOURCE_REV` (the nix build passes the flake's -//! rev) → `git rev-parse` in the repo root (developer builds) → -//! "unknown". The nix sandbox has no `.git`, so without the env var a -//! packaged build honestly reports "unknown" rather than inventing one. +//! Source rev resolution: `$FLEET_SOURCE_REV` (the nix build passes +//! the flake's rev) → `git rev-parse` in the repo root (developer +//! builds) → "unknown". The nix sandbox has no `.git`, so without +//! the env var a packaged build honestly reports "unknown" rather +//! than inventing one. +//! +//! Derived version resolution (#8566; policy #5790): the version is +//! derived, never hand-maintained — +//! `$FLEET_DERIVED_VERSION` (release tooling / packaged builds, +//! computed where the git history exists, exactly the way +//! `$FLEET_SOURCE_REV` already flows) → `git describe --tags +//! --match '/v*'` transformed by the shared derivation in +//! `src/derived_version.rs` → the pre-first-tag fallback +//! `0.1.0-dev` for a build with no history at all. See the +//! "Versioning" section of pkgs/fleet/README.md for the tag and +//! release procedure this implements. use std::process::Command; +#[path = "src/derived_version.rs"] +mod derived_version; + +use derived_version::{branch_class, derive, parse_describe}; + +/// The app's short name — its tag prefix and deploy name (#5790: +/// one short-name policy for all apps). +const APP_NAME: &str = "fleet"; + +fn git(root: &std::path::Path, args: &[&str]) -> Option { + Command::new("git") + .args(args) + .current_dir(root) + .output() + .ok() + .filter(|o| o.status.success()) + .and_then(|o| String::from_utf8(o.stdout).ok()) + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) +} + +fn derived_version(root: &std::path::Path) -> String { + if let Some(v) = std::env::var("FLEET_DERIVED_VERSION") + .ok() + .filter(|s| !s.is_empty()) + { + return v; + } + let branch = git(root, &["branch", "--show-current"]); + if let Some(described) = git( + root, + &[ + "describe", + "--tags", + "--long", + "--match", + &format!("{APP_NAME}/v*"), + ], + ) + .and_then(|out| parse_describe(APP_NAME, &out)) + { + let class = branch_class(branch.as_deref(), described.distance == 0); + return derive( + Some(described.tag), + described.distance, + described.hash.as_deref(), + &class, + ); + } + // No `/v*` tag yet: the 0.1.0-dev fallback family, with the + // repo-wide commit count as the (monotonic) distance and the + // HEAD hash as the uniqueness suffix, when git can prove them. + let hash = git(root, &["rev-parse", "--short=7", "HEAD"]); + let distance = git(root, &["rev-list", "--count", "HEAD"]) + .and_then(|s| s.parse::().ok()) + .unwrap_or(0); + let class = branch_class(branch.as_deref(), false); + derive(None, distance, hash.as_deref(), &class) +} + fn main() { println!("cargo:rerun-if-env-changed=FLEET_SOURCE_REV"); + println!("cargo:rerun-if-env-changed=FLEET_DERIVED_VERSION"); + let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_default(); + let root = std::path::Path::new(&manifest).join("../../.."); let rev = std::env::var("FLEET_SOURCE_REV") .ok() .filter(|s| !s.is_empty()) .unwrap_or_else(|| { - let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_default(); - let root = std::path::Path::new(&manifest).join("../../.."); - Command::new("git") - .args(["rev-parse", "--short=12", "HEAD"]) - .current_dir(root) - .output() - .ok() - .filter(|o| o.status.success()) - .and_then(|o| String::from_utf8(o.stdout).ok()) - .map(|s| s.trim().to_string()) - .filter(|s| !s.is_empty()) + git(&root, &["rev-parse", "--short=12", "HEAD"]) .unwrap_or_else(|| "unknown".to_string()) }); println!("cargo:rustc-env=FLEET_SOURCE_REV={rev}"); + let derived = derived_version(&root); + println!("cargo:rustc-env=FLEET_DERIVED_VERSION={derived}"); } diff --git a/pkgs/fleet/crates/fleet/src/derived_version.rs b/pkgs/fleet/crates/fleet/src/derived_version.rs new file mode 100644 index 0000000000..604863e625 --- /dev/null +++ b/pkgs/fleet/crates/fleet/src/derived_version.rs @@ -0,0 +1,354 @@ +//! Derived per-app versioning for the fleet apps (issue #8566; +//! policy ruled on issue #5790, 2026-11-06). +//! +//! The version a fleet binary reports is DERIVED at build time from +//! the app's latest tag plus the commits since it — never a +//! hand-maintained literal. The grammar is the interim policy of +//! #5790 §1, with the #8566 acceptance forms: +//! +//! * exactly on tag `/vX.Y.Z` -> `X.Y.Z` +//! * on `main`, N commits after that tag -> `X.Y.(Z+1)-dev.N+g` +//! * on a feature branch, N commits after -> the same, plus +//! `+` build metadata +//! * no `/v*` tag yet (pre-first-tag) -> the `0.1.0-dev` +//! fallback family: `0.1.0-dev.N+g` when the commit +//! count and hash are known, bare `0.1.0-dev` when they are not +//! (a build with no git history and no version passed in). +//! +//! Tag prefixes are the app's SHORT name for every app (#5790 +//! refinement, 2026-11-06): one naming policy, no per-app mixing. +//! App names used in tags and deploys must be unique across apps; +//! if a short name would collide, the app name is fixed, not the +//! policy. Versions stay in 0.x until a separate 1.0 decision: +//! minor = features, patch = fixes, no major bumps. +//! +//! This module is pure (no I/O) so the build script can include it +//! by path and feed it `git describe` output, and the binary can +//! unit-test the same code the build script ran. The oracle for +//! every test below is the #5790 §1 policy text quoted above. + +/// A released version from an `/vX.Y.Z` tag. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ReleaseVersion { + pub major: u64, + pub minor: u64, + pub patch: u64, +} + +impl ReleaseVersion { + /// Parse the `X.Y.Z` part of a tag (no `v` prefix, no app part). + pub fn parse(text: &str) -> Option { + let mut parts = text.split('.'); + let major = parse_segment(parts.next()?)?; + let minor = parse_segment(parts.next()?)?; + let patch = parse_segment(parts.next()?)?; + if parts.next().is_some() { + return None; + } + Some(ReleaseVersion { + major, + minor, + patch, + }) + } +} + +impl std::fmt::Display for ReleaseVersion { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}.{}.{}", self.major, self.minor, self.patch) + } +} + +fn parse_segment(text: &str) -> Option { + if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + // No leading zeros: semver numeric segments forbid them, and a + // `v01.2.3` tag is a typo to reject, not a version to honour. + if text.len() > 1 && text.starts_with('0') { + return None; + } + text.parse().ok() +} + +/// Which kind of ref the build was cut from (#5790 §1 rule 1's +/// branch classes). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum BranchClass { + /// HEAD is exactly the tagged commit: a release build. + Tag, + /// A build from `main` (or a detached HEAD with no branch): + /// a prerelease, never a release. + Main, + /// A feature-branch build; carries the sanitized branch slug + /// as extra build metadata. + Feature(String), +} + +/// Parse a per-app tag of the form `/vX.Y.Z` for `app`. +/// Tags for any other app, and malformed tags, return `None` — +/// another app's tag must never version this app. +pub fn parse_app_tag(app: &str, tag: &str) -> Option { + let version = tag.strip_prefix(app)?.strip_prefix("/v")?; + ReleaseVersion::parse(version) +} + +/// The parsed result of `git describe --tags --long --match '/v*'`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Describe { + pub tag: ReleaseVersion, + /// Commits on HEAD since the tag (0 = exactly on the tag). + pub distance: u64, + /// Short commit hash, without git describe's `g` prefix. + pub hash: Option, +} + +/// Parse `git describe` output for `app`. Accepts both the `--long` +/// form (`fleet/v0.4.2-7-g1a2b3c4`) and the exact-tag form +/// (`fleet/v0.4.2`, distance 0, no hash). +pub fn parse_describe(app: &str, output: &str) -> Option { + let text = output.trim(); + if let Some(tag) = parse_app_tag(app, text) { + return Some(Describe { + tag, + distance: 0, + hash: None, + }); + } + // Long form: strip the trailing `--g` first, + // because the tag itself contains no `-` but the split must + // anchor at the END, not at the first dash in the string. + let (head, hash) = text.rsplit_once("-g")?; + if hash.is_empty() || !hash.bytes().all(|b| b.is_ascii_alphanumeric()) { + return None; + } + let (tag_text, distance_text) = head.rsplit_once('-')?; + let tag = parse_app_tag(app, tag_text)?; + let distance: u64 = distance_text.parse().ok()?; + Some(Describe { + tag, + distance, + hash: Some(hash.to_string()), + }) +} + +/// Sanitize a branch name into semver build-metadata slug form: +/// lowercase alphanumerics and `-`, runs of anything else collapsed +/// to one `-`, no leading/trailing `-`, capped at 32 chars. +pub fn slugify_branch(branch: &str) -> String { + let mut slug = String::new(); + for ch in branch.chars() { + if ch.is_ascii_alphanumeric() { + slug.extend(ch.to_lowercase()); + } else if !slug.is_empty() && !slug.ends_with('-') { + slug.push('-'); + } + } + while slug.ends_with('-') { + slug.pop(); + } + slug.truncate(32); + while slug.ends_with('-') { + slug.pop(); + } + if slug.is_empty() { + "feature".to_string() + } else { + slug + } +} + +/// Classify a branch name for [`derive`]. `on_tag` (a describe +/// distance of 0) wins over the branch name; an absent branch +/// (detached HEAD, the usual CI/deploy shape) off a tag is `Main` +/// class — deployed from main, a prerelease. +pub fn branch_class(branch: Option<&str>, on_tag: bool) -> BranchClass { + if on_tag { + return BranchClass::Tag; + } + match branch { + None | Some("") | Some("main") | Some("master") => BranchClass::Main, + Some(other) => BranchClass::Feature(slugify_branch(other)), + } +} + +/// The fallback base before an app's first tag: every app starts +/// at 0.1.0 (#5790 ruling 3). +pub const FIRST_VERSION: ReleaseVersion = ReleaseVersion { + major: 0, + minor: 1, + patch: 0, +}; + +/// Derive the version string for one build. +/// +/// * `tag` — the app's nearest tag version, if any tag exists yet. +/// * `distance` — commits since that tag; with no tag, the commit +/// count the caller can prove (the build script passes the +/// repo-wide count, so the number still grows monotonically). +/// * `hash` — the build commit's short hash, if known. It rides as +/// `+g` build metadata, which is what guarantees no two +/// distinct commits ever share a version string (#5790 §1). +/// * `branch` — the branch class of the build. +pub fn derive( + tag: Option, + distance: u64, + hash: Option<&str>, + branch: &BranchClass, +) -> String { + let hash_part = hash + .filter(|h| !h.is_empty()) + .map(|h| format!("+g{h}")) + .unwrap_or_default(); + let slug_part = match branch { + BranchClass::Feature(slug) => format!("+{slug}"), + _ => String::new(), + }; + match tag { + Some(version) if distance == 0 => format!("{version}"), + Some(version) => { + // Past a tag on a non-release build: the NEXT patch + // release's prerelease form, so the string sorts after + // the tag it descends from and before its own release + // (raw describe output would sort before the tag). + let next = ReleaseVersion { + patch: version.patch + 1, + ..version + }; + format!("{next}-dev.{distance}{hash_part}{slug_part}") + } + None => { + // Pre-first-tag fallback (#8566 acceptance): the + // 0.1.0-dev form. Bare `0.1.0-dev` only when neither a + // distance nor a hash is known (history-less build). + if distance == 0 && hash_part.is_empty() { + format!("{FIRST_VERSION}-dev{slug_part}") + } else { + format!("{FIRST_VERSION}-dev.{distance}{hash_part}{slug_part}") + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const APP: &str = "fleet"; + + fn v(major: u64, minor: u64, patch: u64) -> ReleaseVersion { + ReleaseVersion { + major, + minor, + patch, + } + } + + #[test] + fn exact_tag_is_the_clean_release() { + // Oracle: #5790 §1 — exactly on the tag -> clean X.Y.Z. + assert_eq!( + derive(Some(v(0, 4, 2)), 0, Some("1a2b3c4"), &BranchClass::Tag), + "0.4.2" + ); + } + + #[test] + fn main_after_tag_is_next_patch_dev() { + // Oracle: #5790 §1 — on main, N commits after X.Y.Z -> + // X.Y.(Z+1)-dev.N+g (its worked example shape). + assert_eq!( + derive(Some(v(0, 4, 2)), 7, Some("1a2b3c4"), &BranchClass::Main), + "0.4.3-dev.7+g1a2b3c4" + ); + } + + #[test] + fn feature_branch_adds_slug_metadata() { + // Oracle: #5790 §1 — feature branch adds +. + let class = branch_class(Some("ws-h-versioning"), false); + assert_eq!( + derive(Some(v(0, 4, 2)), 7, Some("1a2b3c4"), &class), + "0.4.3-dev.7+g1a2b3c4+ws-h-versioning" + ); + } + + #[test] + fn no_tag_falls_back_to_0_1_0_dev_form() { + // Oracle: #8566 acceptance — with no tag the app reports + // the 0.1.0-dev fallback form. + assert_eq!( + derive(None, 12, Some("abc1234"), &BranchClass::Main), + "0.1.0-dev.12+gabc1234" + ); + assert_eq!(derive(None, 0, None, &BranchClass::Main), "0.1.0-dev"); + } + + #[test] + fn app_tag_parsing_is_scoped_to_the_app() { + assert_eq!(parse_app_tag(APP, "fleet/v0.1.0"), Some(v(0, 1, 0))); + // Another app's tag never versions this app. + assert_eq!(parse_app_tag(APP, "mcpx/v0.1.0"), None); + assert_eq!(parse_app_tag("mcpx", "fleet/v0.1.0"), None); + // Malformed tags are rejected, not guessed at. + assert_eq!(parse_app_tag(APP, "fleet/v0.1"), None); + assert_eq!(parse_app_tag(APP, "fleet/0.1.0"), None); + assert_eq!(parse_app_tag(APP, "fleet/v01.2.3"), None); + assert_eq!(parse_app_tag(APP, "fleet/v0.1.0-rc1"), None); + } + + #[test] + fn describe_parsing_handles_long_and_exact_forms() { + assert_eq!( + parse_describe(APP, "fleet/v0.4.2-7-g1a2b3c4\n"), + Some(Describe { + tag: v(0, 4, 2), + distance: 7, + hash: Some("1a2b3c4".to_string()), + }) + ); + assert_eq!( + parse_describe(APP, "fleet/v0.4.2"), + Some(Describe { + tag: v(0, 4, 2), + distance: 0, + hash: None, + }) + ); + assert_eq!(parse_describe(APP, "mcpx/v0.4.2-7-g1a2b3c4"), None); + assert_eq!(parse_describe(APP, ""), None); + } + + #[test] + fn describe_round_trip_matches_the_policy_example() { + // The #5790 §1 worked example, end to end. + let described = parse_describe(APP, "fleet/v0.4.2-7-g1a2b3c4").unwrap(); + let class = branch_class(Some("main"), described.distance == 0); + assert_eq!( + derive( + Some(described.tag), + described.distance, + described.hash.as_deref(), + &class + ), + "0.4.3-dev.7+g1a2b3c4" + ); + } + + #[test] + fn slugify_sanitizes_branch_names() { + assert_eq!( + slugify_branch("queue/14886-8566-derived-versioning"), + "queue-14886-8566-derived-version" + ); + assert_eq!(slugify_branch("Feature/Weird_Name!!"), "feature-weird-name"); + assert_eq!(slugify_branch("---"), "feature"); + } + + #[test] + fn branch_class_defaults_detached_and_main_to_main() { + assert_eq!(branch_class(None, false), BranchClass::Main); + assert_eq!(branch_class(Some("main"), false), BranchClass::Main); + assert_eq!(branch_class(Some("main"), true), BranchClass::Tag); + } +} diff --git a/pkgs/fleet/crates/fleet/src/main.rs b/pkgs/fleet/crates/fleet/src/main.rs index 48ea8e6478..7f3e0d34a9 100644 --- a/pkgs/fleet/crates/fleet/src/main.rs +++ b/pkgs/fleet/crates/fleet/src/main.rs @@ -45,8 +45,17 @@ use fleet_registry::{ #[cfg(feature = "secrets")] mod secrets; +#[allow(dead_code)] +// the derivation runs in build.rs (which includes this module by path); the binary itself consumes only the baked FLEET_DERIVED_VERSION value, plus these unit tests +mod derived_version; + const VERSION: &str = env!("CARGO_PKG_VERSION"); const SOURCE_REV: &str = env!("FLEET_SOURCE_REV"); +/// The derived per-app version (#8566; derivation in +/// `derived_version.rs`, baked by build.rs from the app's tags, +/// with `$FLEET_DERIVED_VERSION` as the packaged-build channel — +/// the same channel shape as `FLEET_SOURCE_REV`). +const DERIVED_VERSION: &str = env!("FLEET_DERIVED_VERSION"); const EXIT_OK: i32 = 0; const EXIT_USAGE: i32 = 2; @@ -250,6 +259,7 @@ fn print_version(surface: &Surface, invoked_as: &str) { ), None => println!("Build: {build}"), } + println!("Derived version: {DERIVED_VERSION}"); println!("Source rev: {SOURCE_REV}"); println!("Enabled capabilities: {}", format_caps(&surface.usable())); } @@ -280,6 +290,7 @@ fn print_capabilities(surface: &Surface, invoked_as: &str) { "build": { "name": build, "version": VERSION, + "derived_version": DERIVED_VERSION, "source_rev": SOURCE_REV, "invoked_as": invoked_as, "profile": surface.profile.map(|v| v.name()), @@ -531,6 +542,7 @@ fn run_domain(surface: &Surface, d: &Domain, args: &[String], invoked_as: &str) "fleet" } ); + println!("Derived version: {DERIVED_VERSION}"); return EXIT_OK; } return fleet_queue::client::run(args); @@ -1016,6 +1028,7 @@ fn run_root(surface: &Surface, args: &[String], invoked_as: &str) -> i32 { return code; } println!("fleet {VERSION}"); + println!("Derived version: {DERIVED_VERSION}"); EXIT_OK } Some("version") => { diff --git a/pkgs/fleet/smoke.sh b/pkgs/fleet/smoke.sh index bd6a252cb4..7bec95475d 100755 --- a/pkgs/fleet/smoke.sh +++ b/pkgs/fleet/smoke.sh @@ -474,6 +474,8 @@ mkdir -p "$TMP/full" ln -s "$FULL_OUT/bin/fleet" "$TMP/full/repo-queue" run "repo-queue: --help renders the queue commands" 0 "Commands: validate" "$TMP/full/repo-queue" --help run "repo-queue: --version reports the fleet release" 0 "repo-queue 0.1.0" "$TMP/full/repo-queue" --version +run "repo-queue: --version reports the derived version" 0 "Derived version: " "$TMP/full/repo-queue" --version +run "fleet: version reports the derived version" 0 "Derived version: " "$FULL_OUT/bin/fleet" version run "fleet queue: --help renders the queue commands" 0 "Commands: validate" "$FULL_OUT/bin/fleet" queue --help # Client -> broker wiring: health reaches the scratch queue-broker, From 605e3e255aee7d0f7fe6dbf2c17ed830e51107e3 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Wed, 11 Nov 2026 03:47:47 -0600 Subject: [PATCH 2/3] fix(fleet): address Codex P2s on derived versioning (PR #8630) Four findings from the Codex review of e95fe4151b, all accepted: 1. SemVer build metadata permits ONE '+' separator: the feature branch slug now dot-joins the hash identifier (0.4.3-dev.7+g1a2b3c4.ws-h-versioning) instead of a second '+'. The #5790 policy text's example spelling is corrected in the module docs and the README table; a regression test asserts every derived form carries at most one '+'. 2. The packaged (nix) build now produces the derived version: pkgs/fleet/default.nix takes a derivedVersion argument (release tooling passes the clean tag version for a tag build, where the git history exists) and otherwise derives a unique prerelease from sourceRev (0.1.0-dev+g) - no more colliding bare 0.1.0-dev from every packaged build. README step 3 documents it. 3. A malformed nearest tag (fleet/v01.2.3, fleet/v0.4.3-rc.1) no longer hides a valid older release tag: when parse_describe rejects describe's pick, build.rs scans reachable fleet/v* tags, keeps only validated /vX.Y.Z ones, and derives from the nearest (ties: highest version). 4. build.rs registers the git refs it reads (refs/tags, packed-refs, HEAD) as rerun-if-changed inputs, so cutting a release tag on an already-built tree invalidates the bake. Verified live in the worktree: with fleet/v01.2.3 tagged at HEAD (describe's pick) and fleet/v0.1.0 at HEAD~1, a build reports 0.1.1-dev.1+ge95fe41.queue-14886-8566-derived-version; with fleet/v0.1.0 at HEAD, a source-unmodified rebuild reports clean 0.1.0; with the tags deleted it reports the 0.1.0-dev fallback again. cargo test -p fleet --locked: 29+1+7 passed. --- pkgs/fleet/README.md | 10 ++- pkgs/fleet/crates/fleet/build.rs | 80 ++++++++++++++++++- .../fleet/crates/fleet/src/derived_version.rs | 72 +++++++++++++---- pkgs/fleet/default.nix | 19 +++++ 4 files changed, 163 insertions(+), 18 deletions(-) diff --git a/pkgs/fleet/README.md b/pkgs/fleet/README.md index 98d03cbae9..a51f44fbd3 100644 --- a/pkgs/fleet/README.md +++ b/pkgs/fleet/README.md @@ -136,7 +136,7 @@ the app is this workspace's short name, `fleet`): | --- | --- | | exactly on the tag | `X.Y.Z` | | on `main`, N commits after the tag | `X.Y.(Z+1)-dev.N+g` | -| on a feature branch, N commits after | `X.Y.(Z+1)-dev.N+g+` | +| on a feature branch, N commits after | `X.Y.(Z+1)-dev.N+g.` | | no `/v*` tag yet | `0.1.0-dev.N+g` (bare `0.1.0-dev` if no history is available) | The `+g` suffix is what guarantees no two distinct commits ever @@ -159,7 +159,13 @@ own release. 3. **Releases are tag builds only.** Build the release artifact from the tagged commit and verify the artifact itself reports the clean version: `./result/bin/fleet version` must show - `Derived version: X.Y.Z`. Builds deployed from `main` are + `Derived version: X.Y.Z`. A packaged (nix) release build takes + the version through the package's `derivedVersion` argument — + the build source carries no `.git`, so the release tooling + computes the version where the history exists and passes it in; + a packaged build without one reports the rev-derived prerelease + form `0.1.0-dev+g`, never a clean release string. Builds + deployed from `main` are **prereleases** (their `-dev.N` strings say so) — deploying one never makes it a release. 4. **Repo tags.** At every release point (not every commit, not diff --git a/pkgs/fleet/crates/fleet/build.rs b/pkgs/fleet/crates/fleet/build.rs index 4b9d04903b..7df958db38 100644 --- a/pkgs/fleet/crates/fleet/build.rs +++ b/pkgs/fleet/crates/fleet/build.rs @@ -23,7 +23,7 @@ use std::process::Command; #[path = "src/derived_version.rs"] mod derived_version; -use derived_version::{branch_class, derive, parse_describe}; +use derived_version::{ReleaseVersion, branch_class, derive, parse_app_tag, parse_describe}; /// The app's short name — its tag prefix and deploy name (#5790: /// one short-name policy for all apps). @@ -41,6 +41,55 @@ fn git(root: &std::path::Path, args: &[&str]) -> Option { .filter(|s| !s.is_empty()) } +/// Fallback tag selection (PR #8630 Codex finding): `git describe` +/// considers every tag matching `fleet/v*`, including malformed +/// ones (`fleet/v0.4.3-rc.1`, `fleet/v01.2.3`) that parse_describe +/// rightly rejects — and a rejected NEAREST tag must not hide an +/// older valid release tag behind it. Scan the reachable tags, +/// keep only the ones that validate as `/vX.Y.Z`, and pick +/// the nearest (smallest commit distance; ties go to the highest +/// version). +fn from_validated_tags(root: &std::path::Path, branch: Option<&str>) -> Option { + let tags = git( + root, + &[ + "tag", + "--list", + &format!("{APP_NAME}/v*"), + "--merged", + "HEAD", + ], + )?; + let hash = git(root, &["rev-parse", "--short=7", "HEAD"]); + let mut best: Option<(u64, ReleaseVersion)> = None; + for line in tags.lines() { + let tag = line.trim(); + let Some(version) = parse_app_tag(APP_NAME, tag) else { + continue; + }; + let Some(distance) = git(root, &["rev-list", "--count", &format!("{tag}..HEAD")]) + .and_then(|s| s.parse::().ok()) + else { + continue; + }; + let wins = match best { + None => true, + Some((bd, bv)) => { + distance < bd + || (distance == bd + && (version.major, version.minor, version.patch) + > (bv.major, bv.minor, bv.patch)) + } + }; + if wins { + best = Some((distance, version)); + } + } + let (distance, version) = best?; + let class = branch_class(branch, distance == 0); + Some(derive(Some(version), distance, hash.as_deref(), &class)) +} + fn derived_version(root: &std::path::Path) -> String { if let Some(v) = std::env::var("FLEET_DERIVED_VERSION") .ok() @@ -69,6 +118,9 @@ fn derived_version(root: &std::path::Path) -> String { &class, ); } + if let Some(v) = from_validated_tags(root, branch.as_deref()) { + return v; + } // No `/v*` tag yet: the 0.1.0-dev fallback family, with the // repo-wide commit count as the (monotonic) distance and the // HEAD hash as the uniqueness suffix, when git can prove them. @@ -80,11 +132,37 @@ fn derived_version(root: &std::path::Path) -> String { derive(None, distance, hash.as_deref(), &class) } +/// Register the git state the bake reads as build-script inputs +/// (PR #8630 Codex finding): without this, cutting a tag on an +/// already-built tree changes no env var and no source file, and +/// cargo keeps the stale baked version. Tag refs live in the +/// common git dir (shared across worktrees); HEAD is per-git-dir. +fn rerun_on_git_refs(root: &std::path::Path) { + for (args, leaf) in [ + (vec!["rev-parse", "--git-common-dir"], "refs/tags"), + (vec!["rev-parse", "--git-common-dir"], "packed-refs"), + (vec!["rev-parse", "--git-dir"], "HEAD"), + ] { + if let Some(dir) = git(root, &args) { + let base = if std::path::Path::new(&dir).is_absolute() { + std::path::PathBuf::from(dir) + } else { + root.join(dir) + }; + let watched = base.join(leaf); + if watched.exists() { + println!("cargo:rerun-if-changed={}", watched.display()); + } + } + } +} + fn main() { println!("cargo:rerun-if-env-changed=FLEET_SOURCE_REV"); println!("cargo:rerun-if-env-changed=FLEET_DERIVED_VERSION"); let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_default(); let root = std::path::Path::new(&manifest).join("../../.."); + rerun_on_git_refs(&root); let rev = std::env::var("FLEET_SOURCE_REV") .ok() .filter(|s| !s.is_empty()) diff --git a/pkgs/fleet/crates/fleet/src/derived_version.rs b/pkgs/fleet/crates/fleet/src/derived_version.rs index 604863e625..80d90cb691 100644 --- a/pkgs/fleet/crates/fleet/src/derived_version.rs +++ b/pkgs/fleet/crates/fleet/src/derived_version.rs @@ -8,8 +8,12 @@ //! //! * exactly on tag `/vX.Y.Z` -> `X.Y.Z` //! * on `main`, N commits after that tag -> `X.Y.(Z+1)-dev.N+g` -//! * on a feature branch, N commits after -> the same, plus -//! `+` build metadata +//! * on a feature branch, N commits after -> the same, with the +//! branch slug dot-joined into the ONE build-metadata section: +//! `X.Y.(Z+1)-dev.N+g.` (the #5790 text +//! spells the slug with a second `+`; SemVer permits only one +//! `+` separator, so the identifiers are dot-joined instead — +//! Codex finding on PR #8630) //! * no `/v*` tag yet (pre-first-tag) -> the `0.1.0-dev` //! fallback family: `0.1.0-dev.N+g` when the commit //! count and hash are known, bare `0.1.0-dev` when they are not @@ -196,13 +200,19 @@ pub fn derive( hash: Option<&str>, branch: &BranchClass, ) -> String { - let hash_part = hash - .filter(|h| !h.is_empty()) - .map(|h| format!("+g{h}")) - .unwrap_or_default(); - let slug_part = match branch { - BranchClass::Feature(slug) => format!("+{slug}"), - _ => String::new(), + // Build metadata is ONE `+` section; its identifiers are + // dot-joined (SemVer permits a single `+` separator). + let mut metadata: Vec = Vec::new(); + if let Some(h) = hash.filter(|h| !h.is_empty()) { + metadata.push(format!("g{h}")); + } + if let BranchClass::Feature(slug) = branch { + metadata.push(slug.clone()); + } + let metadata_part = if metadata.is_empty() { + String::new() + } else { + format!("+{}", metadata.join(".")) }; match tag { Some(version) if distance == 0 => format!("{version}"), @@ -215,16 +225,20 @@ pub fn derive( patch: version.patch + 1, ..version }; - format!("{next}-dev.{distance}{hash_part}{slug_part}") + format!("{next}-dev.{distance}{metadata_part}") } None => { // Pre-first-tag fallback (#8566 acceptance): the // 0.1.0-dev form. Bare `0.1.0-dev` only when neither a // distance nor a hash is known (history-less build). - if distance == 0 && hash_part.is_empty() { - format!("{FIRST_VERSION}-dev{slug_part}") + if distance == 0 && metadata.is_empty() { + format!("{FIRST_VERSION}-dev") + } else if distance == 0 && hash.is_none() { + // A slug with no distance and no hash: keep the + // metadata, drop the meaningless `.0` counter. + format!("{FIRST_VERSION}-dev{metadata_part}") } else { - format!("{FIRST_VERSION}-dev.{distance}{hash_part}{slug_part}") + format!("{FIRST_VERSION}-dev.{distance}{metadata_part}") } } } @@ -265,14 +279,42 @@ mod tests { #[test] fn feature_branch_adds_slug_metadata() { - // Oracle: #5790 §1 — feature branch adds +. + // Oracle: #5790 §1 — a feature branch adds its slug as + // build metadata; the identifiers dot-join inside the ONE + // `+` section SemVer allows (PR #8630 Codex finding: the + // policy text's second `+` is not parseable SemVer). let class = branch_class(Some("ws-h-versioning"), false); assert_eq!( derive(Some(v(0, 4, 2)), 7, Some("1a2b3c4"), &class), - "0.4.3-dev.7+g1a2b3c4+ws-h-versioning" + "0.4.3-dev.7+g1a2b3c4.ws-h-versioning" ); } + #[test] + fn derived_versions_have_at_most_one_plus() { + // Oracle: SemVer grammar — build metadata follows a single + // `+`; every derived form must stay parseable. + for derived in [ + derive(Some(v(0, 4, 2)), 0, Some("1a2b3c4"), &BranchClass::Tag), + derive(Some(v(0, 4, 2)), 7, Some("1a2b3c4"), &BranchClass::Main), + derive( + Some(v(0, 4, 2)), + 7, + Some("1a2b3c4"), + &branch_class(Some("feat/x"), false), + ), + derive( + None, + 3, + Some("1a2b3c4"), + &branch_class(Some("feat/x"), false), + ), + derive(None, 0, None, &branch_class(Some("feat/x"), false)), + ] { + assert!(derived.matches('+').count() <= 1, "invalid: {derived}"); + } + } + #[test] fn no_tag_falls_back_to_0_1_0_dev_form() { // Oracle: #8566 acceptance — with no tag the app reports diff --git a/pkgs/fleet/default.nix b/pkgs/fleet/default.nix index 9e9e0825c2..2538e111d3 100644 --- a/pkgs/fleet/default.nix +++ b/pkgs/fleet/default.nix @@ -42,6 +42,12 @@ callPackage, craneLib ? null, sourceRev ? "unknown", + # The derived per-app version (#8566), computed by the release + # tooling where the git history exists (the nix build source has + # no .git). A release build passes the clean tag version here + # (e.g. "0.1.0" at fleet/v0.1.0); left null, the package derives + # an honest prerelease from sourceRev below. + derivedVersion ? null, }: let @@ -102,6 +108,19 @@ let # role there needs ATLAS_ORT_LIB). envAttrs = { FLEET_SOURCE_REV = sourceRev; + # #8566: the binary's Derived version channel. An explicit + # derivedVersion wins; otherwise a real sourceRev yields a + # unique prerelease form (0.1.0-dev+g) instead of the + # colliding bare 0.1.0-dev every packaged build would + # otherwise report. "unknown"/"dirty" pass nothing and the + # build script's own fallback applies. + FLEET_DERIVED_VERSION = + if derivedVersion != null then + derivedVersion + else if sourceRev != "unknown" && sourceRev != "dirty" then + "0.1.0-dev+g${lib.substring 0 7 sourceRev}" + else + "0.1.0-dev"; } // lib.optionalAttrs (features != [ ] && !static) { ATLAS_SEARCH_ORT_LIB_DEFAULT = "${onnxruntime}/lib/libonnxruntime.so"; From f7ae1dfc4c5c12769a57bb91073b14ba7230aee7 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Wed, 11 Nov 2026 03:55:51 -0600 Subject: [PATCH 3/3] fix(fleet): watch the current branch ref in the version bake (PR #8630) Codex round-2 P2 on 605e3e255a: the rerun watcher tracked HEAD, refs/tags and packed-refs, but on an attached HEAD an ordinary commit updates the loose branch ref (refs/heads/, in the common dir for linked worktrees) - HEAD is only the symref naming it and never changes content - so a rebuild after an unrelated commit could keep the previous commit's derived version and source rev. rerun_on_git_refs now also watches refs/heads (the directory covers a ref's first loose creation out of packed-refs) and the resolved current branch ref itself (git symbolic-ref -q HEAD, joined to the common dir). Verified live before this commit: an empty commit on the branch with no source edits moved the rebuilt binary from 0.1.0-dev.11341+g605e3e2... to 0.1.0-dev.11342+g4855f7a... (distance and hash both refreshed). cargo test -p fleet --locked: 29+1+7 passed. --- pkgs/fleet/crates/fleet/build.rs | 46 +++++++++++++++++++++----------- 1 file changed, 31 insertions(+), 15 deletions(-) diff --git a/pkgs/fleet/crates/fleet/build.rs b/pkgs/fleet/crates/fleet/build.rs index 7df958db38..c6d02ad73d 100644 --- a/pkgs/fleet/crates/fleet/build.rs +++ b/pkgs/fleet/crates/fleet/build.rs @@ -138,21 +138,37 @@ fn derived_version(root: &std::path::Path) -> String { /// cargo keeps the stale baked version. Tag refs live in the /// common git dir (shared across worktrees); HEAD is per-git-dir. fn rerun_on_git_refs(root: &std::path::Path) { - for (args, leaf) in [ - (vec!["rev-parse", "--git-common-dir"], "refs/tags"), - (vec!["rev-parse", "--git-common-dir"], "packed-refs"), - (vec!["rev-parse", "--git-dir"], "HEAD"), - ] { - if let Some(dir) = git(root, &args) { - let base = if std::path::Path::new(&dir).is_absolute() { - std::path::PathBuf::from(dir) - } else { - root.join(dir) - }; - let watched = base.join(leaf); - if watched.exists() { - println!("cargo:rerun-if-changed={}", watched.display()); - } + let resolve = |args: &[&str]| -> Option { + let dir = git(root, args)?; + let base = if std::path::Path::new(&dir).is_absolute() { + std::path::PathBuf::from(dir) + } else { + root.join(dir) + }; + Some(base) + }; + let mut watched: Vec = Vec::new(); + if let Some(common) = resolve(&["rev-parse", "--git-common-dir"]) { + watched.push(common.join("refs/tags")); + watched.push(common.join("refs/heads")); + watched.push(common.join("packed-refs")); + // The current branch's own ref (PR #8630 Codex round 2): + // on an attached HEAD, an ordinary commit updates the + // loose branch ref under the COMMON dir — HEAD itself is + // just the symref naming it and never changes content — + // so watch the resolved ref as well as its directory + // (the directory watch covers its first loose creation + // when it previously lived only in packed-refs). + if let Some(branch_ref) = git(root, &["symbolic-ref", "-q", "HEAD"]) { + watched.push(common.join(branch_ref)); + } + } + if let Some(gitdir) = resolve(&["rev-parse", "--git-dir"]) { + watched.push(gitdir.join("HEAD")); + } + for path in watched { + if path.exists() { + println!("cargo:rerun-if-changed={}", path.display()); } } }