diff --git a/pkgs/fleet/README.md b/pkgs/fleet/README.md index 556987f138..a51f44fbd3 100644 --- a/pkgs/fleet/README.md +++ b/pkgs/fleet/README.md @@ -116,6 +116,70 @@ 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`. 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 + 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..c6d02ad73d 100644 --- a/pkgs/fleet/crates/fleet/build.rs +++ b/pkgs/fleet/crates/fleet/build.rs @@ -1,30 +1,192 @@ -//! 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::{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). +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()) +} + +/// 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() + .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, + ); + } + 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. + 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) +} + +/// 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) { + 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()); + } + } +} + 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()) .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..80d90cb691 --- /dev/null +++ b/pkgs/fleet/crates/fleet/src/derived_version.rs @@ -0,0 +1,396 @@ +//! 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, 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 +//! (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 { + // 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}"), + 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}{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 && 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}{metadata_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 — 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" + ); + } + + #[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 + // 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/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"; 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,