You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tooling.apache.org by ar...@apache.org on 2026/06/30 12:53:13 UTC

(tooling-trusted-releases) 01/03: Fix calver support for cycle matching

This is an automated email from the ASF dual-hosted git repository.

alitheg pushed a commit to branch arm
in repository https://gitbox.apache.org/repos/asf/tooling-trusted-releases.git

commit efcde97bc875b7a10f5069ad4d5a058a787581c5
Author: Alastair McFarlane <ar...@apache.org>
AuthorDate: Mon Jun 29 16:27:38 2026 +0100

    Fix calver support for cycle matching
---
 atr/calver.py                                   | 206 ++++++++++++++++++++++++
 atr/cycles.py                                   |  29 +++-
 atr/docs/input-validation.md                    |  26 ++-
 atr/get/projects.py                             |   3 +-
 atr/models/sql.py                               |   1 +
 atr/shared/projects.py                          |  18 ++-
 atr/static/js/src/version-scheme-toggle.js      |  56 +++++++
 atr/storage/writers/policy.py                   |  50 ++++--
 atr/storage/writers/project.py                  |   1 +
 migrations/versions/0099_2026.06.29_ca1ec0de.py |  44 +++++
 tests/unit/test_calver.py                       | 117 ++++++++++++++
 tests/unit/test_cycles.py                       |  62 ++++++-
 tests/unit/test_policy_writer.py                |  42 +++++
 13 files changed, 632 insertions(+), 23 deletions(-)

diff --git a/atr/calver.py b/atr/calver.py
new file mode 100644
index 00000000..b23e8823
--- /dev/null
+++ b/atr/calver.py
@@ -0,0 +1,206 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Date-format compiler for calendar-versioned projects.
+
+A calver project declares the shape of its version strings as a date format
+rather than a raw regex. The format is a sequence of fixed tokens with literal
+separators between them:
+
+    YYYY / YY   four- or two-digit year
+    MM / M      zero-padded or 1-2 digit month
+    DD / D      zero-padded or 1-2 digit day
+    N           a numeric serial (a patch ordinal within a calendar line)
+
+A single parenthesised span marks which part forms the cycle key. Trailing
+tokens are optional, so one format covers mixed-granularity histories: for
+example YYYYMMDD matches both 20130710 and 201407.
+
+The format compiles two ways. cycle_regex renders the cycle span as capture
+group 1, for storing in Project.cycle_match so ordinary cycle resolution
+handles membership with no calver-specific code. order_key renders a
+named-group regex and extracts a comparable (year, month, day, serial) tuple
+for ordering releases within a cycle.
+"""
+
+from __future__ import annotations
+
+import functools
+import re
+from typing import TYPE_CHECKING, Final, NamedTuple
+
+if TYPE_CHECKING:
+    from collections.abc import Sequence
+
+# Longest tokens first so YYYY wins over YY and MM over M during the scan.
+_TOKENS: Final[list[tuple[str, str, str]]] = [
+    ("YYYY", r"\d{4}", "year"),
+    ("YY", r"\d{2}", "year"),
+    ("MM", r"\d{2}", "month"),
+    ("DD", r"\d{2}", "day"),
+    ("M", r"\d{1,2}", "month"),
+    ("D", r"\d{1,2}", "day"),
+    ("N", r"\d+", "serial"),
+]
+
+_CALENDAR_ROLES: Final[frozenset[str]] = frozenset({"year", "month", "day"})
+
+
+class _Atom(NamedTuple):
+    regex: str  # the regex fragment matching this token or literal
+    role: str | None  # the ordering role, or None for a literal separator
+    in_cycle: bool  # whether it sits inside the parenthesised cycle span
+
+
+def cycle_regex(date_format: str) -> str | None:
+    """Compile the cycle span to a regex with the cycle as group 1.
+
+    Returns None when the format has no parenthesised span - a linear calver
+    project that keeps a single default cycle, for which `cycle_match` stays
+    unset.
+    """
+    atoms = _parse(date_format)
+    cycle_indices = [i for i, atom in enumerate(atoms) if atom.in_cycle]
+    if not cycle_indices:
+        return None
+    first, last = cycle_indices[0], cycle_indices[-1]
+    before = "".join(atom.regex for atom in atoms[:first])
+    span = "".join(atom.regex for atom in atoms[first : last + 1])
+    tail = _nested_optional(_coalesce(atoms[last + 1 :]))
+    return f"^{before}({span}){tail}$"
+
+
+def order_key(date_format: str, version: str) -> tuple[int, int, int, int] | None:
+    """Resolve a version to a `(year, month, day, serial)` ordering tuple.
+
+    Absent fields read as 0, so a coarser version sorts below a finer one in
+    the same period. Returns None when the version doesn't fit the format.
+    """
+    match = _order_pattern(date_format).fullmatch(version)
+    if match is None:
+        return None
+    fields = match.groupdict()
+
+    def field(name: str) -> int:
+        captured = fields.get(name)
+        return int(captured) if captured else 0
+
+    return (field("year"), field("month"), field("day"), field("serial"))
+
+
+def validate(date_format: str) -> None:
+    """Raise ValueError if the format is malformed or carries no calendar field."""
+    if not date_format.strip():
+        raise ValueError("Calver format is empty")
+    atoms = _parse(date_format)
+    roles = [atom.role for atom in atoms if atom.role is not None]
+    if not any(role in _CALENDAR_ROLES for role in roles):
+        raise ValueError("Calver format needs at least one of YYYY/YY, MM/M or DD/D")
+    if len(roles) != len(set(roles)):
+        raise ValueError("Calver format repeats a field")
+    # Compile both regexes now, so an invalid format is caught here rather than
+    # when we first come to resolve a version against it.
+    re.compile(_order_regex(date_format))
+    compiled_cycle = cycle_regex(date_format)
+    if compiled_cycle is not None:
+        re.compile(compiled_cycle)
+
+
+def _coalesce(atoms: Sequence[_Atom]) -> list[str]:
+    # Fold each separator run onto the token that follows it, so a separator
+    # and its token become optional together rather than independently.
+    chunks: list[str] = []
+    pending = ""
+    for atom in atoms:
+        if atom.role is None:
+            pending += atom.regex
+            continue
+        chunks.append(pending + atom.regex)
+        pending = ""
+    if pending:
+        chunks.append(pending)
+    return chunks
+
+
+def _nested_optional(chunks: list[str]) -> str:
+    if not chunks:
+        return ""
+    return f"(?:{chunks[0]}{_nested_optional(chunks[1:])})?"
+
+
+@functools.lru_cache(maxsize=256)
+def _order_pattern(date_format: str) -> re.Pattern[str]:
+    return re.compile(_order_regex(date_format))
+
+
+def _order_regex(date_format: str) -> str:
+    chunks: list[str] = []
+    pending = ""
+    for atom in _parse(date_format):
+        if atom.role is None:
+            pending += atom.regex
+            continue
+        chunks.append(f"{pending}(?P<{atom.role}>{atom.regex})")
+        pending = ""
+    if pending:
+        chunks.append(pending)
+    if not chunks:
+        raise ValueError("Calver format has no fields")
+    # The leading field is required and the rest optional, which is what lets
+    # one format match both coarse and fine versions.
+    return f"^{chunks[0]}{_nested_optional(chunks[1:])}$"
+
+
+@functools.lru_cache(maxsize=256)
+def _parse(date_format: str) -> tuple[_Atom, ...]:
+    atoms: list[_Atom] = []
+    in_cycle = False
+    seen_cycle = False
+    i = 0
+    while i < len(date_format):
+        char = date_format[i]
+        if char == "(":
+            if seen_cycle:
+                raise ValueError("Calver format may contain at most one (cycle) span")
+            in_cycle = True
+            seen_cycle = True
+            i += 1
+            continue
+        if char == ")":
+            if not in_cycle:
+                raise ValueError("Calver format has an unmatched )")
+            in_cycle = False
+            i += 1
+            continue
+        token = _match_token(date_format, i)
+        if token is not None:
+            fragment, role, length = token
+            atoms.append(_Atom(fragment, role, in_cycle))
+            i += length
+            continue
+        atoms.append(_Atom(re.escape(char), None, in_cycle))
+        i += 1
+    if in_cycle:
+        raise ValueError("Calver format has an unmatched (")
+    return tuple(atoms)
+
+
+def _match_token(date_format: str, at: int) -> tuple[str, str, int] | None:
+    for token, fragment, role in _TOKENS:
+        if date_format.startswith(token, at):
+            return fragment, role, len(token)
+    return None
diff --git a/atr/cycles.py b/atr/cycles.py
index ecd75121..f8c0d35c 100644
--- a/atr/cycles.py
+++ b/atr/cycles.py
@@ -30,6 +30,7 @@ from typing import TYPE_CHECKING, Final
 
 import semver
 
+import atr.calver as calver
 import atr.models.sql as sql
 
 if TYPE_CHECKING:
@@ -82,7 +83,8 @@ def prior_release_in_cycle(
 
       - SIMPLE: the most recently released candidate
       - SEMVER: the highest semver version strictly less than `version`
-      - CALVER: not supported yet, returns None
+      - CALVER: the highest calendar version strictly less than `version`,
+        ordered through the project's `calver_format` date format
     """
     try:
         target_cycle = cycle_name_for_version(project, version)
@@ -107,7 +109,7 @@ def prior_release_in_cycle(
         case sql.VersionMethod.SEMVER:
             return _prior_release_semver(version, same_cycle)
         case sql.VersionMethod.CALVER:
-            return None
+            return _prior_release_calver(project, version, same_cycle)
 
 
 async def reassign_release_cycles(data: db.Session, project: sql.Project) -> None:
@@ -146,6 +148,29 @@ def _prior_release_by_released(candidates: list[sql.Release]) -> sql.Release | N
     return timed[0][1]
 
 
+def _prior_release_calver(project: sql.Project, version: str, candidates: list[sql.Release]) -> sql.Release | None:
+    # Without a format string there's no way to order calendar versions, so fall back to
+    # the most recently released candidate, as SIMPLE projects do.
+    format_str = project.calver_format
+    if not format_str:
+        return _prior_release_by_released(candidates)
+    target = calver.order_key(format_str, version)
+    if target is None:
+        return None
+    ranked: list[tuple[tuple[int, int, int, int], sql.Release]] = []
+    for candidate in candidates:
+        key = calver.order_key(format_str, candidate.version)
+        if key is None:
+            continue
+        if key >= target:
+            continue
+        ranked.append((key, candidate))
+    if not ranked:
+        return None
+    ranked.sort(key=lambda pair: pair[0], reverse=True)
+    return ranked[0][1]
+
+
 def _prior_release_semver(version: str, candidates: list[sql.Release]) -> sql.Release | None:
     target = _semver_parse(version)
     if target is None:
diff --git a/atr/docs/input-validation.md b/atr/docs/input-validation.md
index 0a93c24c..2d623822 100644
--- a/atr/docs/input-validation.md
+++ b/atr/docs/input-validation.md
@@ -190,7 +190,7 @@ Per-field coverage:
 
 ### Project validation
 
-Projects do have an input layer. [`AddProjectForm`](/ref/atr/shared/projects.py) (AddProjectForm) validates the key and display name at creation, and [`EditVersionSchemeForm`](/ref/atr/shared/projects.py) (EditVersionSchemeForm) rejects a `version_pattern` or `cycle_match` that is not a valid regex (and a `cycle_match` with no capture group). The data integrity validators mirror these and cover fields that have no form.
+Projects do have an input layer. [`AddProjectForm`](/ref/atr/shared/projects.py) (AddProjectForm) validates the key and display name at creation, and [`EditVersionSchemeForm`](/ref/atr/shared/projects.py) (EditVersionSchemeForm) rejects a `version_pattern` or `cycle_match` that is not a valid regex (and a `cycle_match` with no capture group). Calver projects describe their cycles with a `calver_format` date format instead of a regex; see [Calver cycle formats](#calver-cycle-formats) belo [...]
 
 The [`project`](/ref/atr/validate.py) (project) function checks:
 
@@ -200,6 +200,7 @@ The [`project`](/ref/atr/validate.py) (project) function checks:
 * `created` timestamp must be in the past
 * `created_by`, if set, must look like an ASF UID
 * `cycle_match`, if set, must be a regex with at least one capture group
+* `calver_format`, if set, must be a valid date format with at least one calendar field
 * `full_name` must be set and start with "Apache "
 * `programming_languages` must use comma-separated labels without colons
 * `release_policy_id` must be None (not used)
@@ -218,11 +219,34 @@ Per-field coverage:
 | `version_method` | `EditVersionSchemeForm` (enum) | type-enforced (enum) |
 | `version_pattern` | `EditVersionSchemeForm` (regex validity) | compilable regex |
 | `cycle_match` | `EditVersionSchemeForm` (regex and capture group) | regex with capture group |
+| `calver_format` | `EditVersionSchemeForm` (date format) | valid format with a calendar field |
 | `branch_template` | `EditVersionSchemeForm` (free text) | none, not currently enforced |
 | `committee_key` | `safe.CommitteeKey` | must be set |
 | `created` | set at creation | in the past |
 | `created_by` | none | ASF UID format |
 
+#### Calver cycle formats
+
+Calver projects declare the shape of their version strings with a date format string rather than a regex. The format is a sequence of tokens with literal separators between them:
+
+| Token | Matches | Role |
+| --- | --- | --- |
+| `YYYY` / `YY` | four- or two-digit year | ordering |
+| `MM` / `M` | zero-padded or 1-2 digit month | ordering |
+| `DD` / `D` | zero-padded or 1-2 digit day | ordering |
+| `N` | a numeric serial (a patch ordinal within a calendar line) | ordering |
+
+Wrap the part of the version that names the cycle in parentheses. A format with no parentheses keeps a single release track; one with a parenthesised span splits releases into one cycle per matched value. Trailing tokens are optional, so one format covers mixed-granularity histories - `YYYYMMDD` matches both `20130710` and `201407`, reading the missing day as zero.
+
+Examples:
+
+| Version | Format | Cycle | Notes |
+| --- | --- | --- | --- |
+| `2020.6.24` | `YYYY.M.D` | default | non-padded month and day |
+| `2025-11-03` | `YYYY-MM-DD` | default | dashed date |
+| `20130710` | `YYYYMMDD` | default | run-together, day optional |
+| `09.04.01` | `(YY.MM).N` | `09.04` | the `YY.MM` line is the cycle, `N` the patch |
+
 ### Release validation
 
 The [`release`](/ref/atr/validate.py) (release) function checks:
diff --git a/atr/get/projects.py b/atr/get/projects.py
index bbbc4e1d..f81e27e2 100644
--- a/atr/get/projects.py
+++ b/atr/get/projects.py
@@ -335,7 +335,7 @@ async def view(
 
     content = page.collect()
 
-    javascripts = ["copy-variable"] if can_edit_policy else []
+    javascripts = ["copy-variable", "version-scheme-toggle"] if can_edit_policy else []
     return await template.blank(
         title=f"{project.display_name}",
         description=f"Information regarding {project.display_name}.",
@@ -1317,6 +1317,7 @@ async def _render_version_scheme_form(project: sql.Project) -> htm.Element:
                 "version_method": project.version_method,
                 "version_pattern": project.version_pattern or "",
                 "cycle_match": project.cycle_match or "",
+                "calver_format": project.calver_format or "",
                 "branch_template": project.branch_template or "",
             },
         )
diff --git a/atr/models/sql.py b/atr/models/sql.py
index b950abae..01dd1a1c 100644
--- a/atr/models/sql.py
+++ b/atr/models/sql.py
@@ -890,6 +890,7 @@ class Project(sqlmodel.SQLModel, table=True):
     version_method: VersionMethod = sqlmodel.Field(default=VersionMethod.SIMPLE, **example(VersionMethod.SIMPLE))
     version_pattern: str | None = sqlmodel.Field(default=None, **example(r"^\d+\.\d+\.\d+$"))
     cycle_match: str | None = sqlmodel.Field(default=None, **example(r"^(\d+)\.\d+\.\d+$"))
+    calver_format: str | None = sqlmodel.Field(default=None, **example("(YY.MM).N"))
     branch_template: str | None = sqlmodel.Field(default=None, **example("release-{cycle}"))
 
     # M-1: Project -> Committee
diff --git a/atr/shared/projects.py b/atr/shared/projects.py
index c7e5e83a..42a069c8 100644
--- a/atr/shared/projects.py
+++ b/atr/shared/projects.py
@@ -22,6 +22,7 @@ from typing import Annotated, Literal
 
 import pydantic
 
+import atr.calver as calver
 import atr.form as form
 import atr.models.safe as safe
 import atr.models.sql as sql
@@ -301,10 +302,17 @@ class EditVersionSchemeForm(form.Form):
     )
     cycle_match: str = form.label(
         "Cycle match",
-        "Regex applied to the version string; capture group 1 is the cycle name."
+        "For semver projects: a regex applied to the version string; capture group 1 is the cycle name."
         r" For example, (\d+)\..* maps version 2.0.1 into cycle 2."
         " Leave empty for projects that keep a single default cycle.",
     )
+    calver_format: str = form.label(
+        "Cycle format",
+        "For calver projects: a date format describing the version shape."
+        " Tokens YYYY/YY, MM/M, DD/D and N (a serial), with literal separators."
+        " Wrap the part that names the cycle in parentheses, e.g. (YY.MM).N."
+        " Leave empty for projects that keep a single default cycle.",
+    )
     branch_template: str = form.label(
         "Branch template",
         "Optional naming hint for source branches per cycle. Not currently enforced.",
@@ -336,6 +344,14 @@ class EditVersionSchemeForm(form.Form):
 
         return val
 
+    @pydantic.field_validator("calver_format", mode="before")
+    @classmethod
+    def validate_calver_format(cls, val: str) -> str:
+        calver_format = val.strip()
+        if calver_format:
+            calver.validate(calver_format)
+        return val
+
 
 class FinishPolicyForm(form.Form):
     variant: FINISH = form.value(FINISH)
diff --git a/atr/static/js/src/version-scheme-toggle.js b/atr/static/js/src/version-scheme-toggle.js
new file mode 100644
index 00000000..90be78fa
--- /dev/null
+++ b/atr/static/js/src/version-scheme-toggle.js
@@ -0,0 +1,56 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+
+// Cycle config is per version method: semver projects fill in a cycle_match
+// regex, calver projects a date format, simple projects neither. Show whichever
+// applies to the selected radio. This is only a convenience - the server
+// validates per method regardless, so if the script doesn't run both fields
+// just stay visible.
+
+function selectedMethod() {
+	const checked = document.querySelector(
+		"input[name='version_method']:checked",
+	);
+	return checked ? checked.value : null;
+}
+
+document.addEventListener("DOMContentLoaded", () => {
+	const radios = document.querySelectorAll("input[name='version_method']");
+	if (radios.length === 0) return;
+
+	const cycleMatchRow = document.getElementById("cycle_match")?.closest(".row");
+	const calverFormatRow = document
+		.getElementById("calver_format")
+		?.closest(".row");
+	if (!cycleMatchRow || !calverFormatRow) return;
+
+	const apply = () => {
+		const method = selectedMethod();
+		// Toggle Bootstrap's .d-none rather than the hidden attribute: these are
+		// .row elements, and .row { display: flex } would otherwise win over the
+		// user-agent [hidden] rule and leave the field showing.
+		cycleMatchRow.classList.toggle("d-none", method !== "semver");
+		calverFormatRow.classList.toggle("d-none", method !== "calver");
+	};
+
+	radios.forEach((radio) => {
+		radio.addEventListener("change", apply);
+	});
+	apply();
+});
diff --git a/atr/storage/writers/policy.py b/atr/storage/writers/policy.py
index 52bd9aab..475e678d 100644
--- a/atr/storage/writers/policy.py
+++ b/atr/storage/writers/policy.py
@@ -26,6 +26,7 @@ import sqlmodel
 import strictyaml
 import strictyaml.ruamel.error as error
 
+import atr.calver as calver
 import atr.cycles as cycles
 import atr.db as db
 import atr.models as models
@@ -266,16 +267,27 @@ class ReleaseManager(CommitteeParticipant):
         project_key = form.project_key
         project = await self.__validate_project_in_committee(project_key)
 
-        # Validate cycle_match by trying to compile it. Empty becomes None
-        # so we don't store empty strings in nullable columns.
-        cycle_match = form.cycle_match.strip() or None
-        if cycle_match is not None:
-            try:
-                compiled = re.compile(cycle_match)
-            except re.error as exc:
-                raise ValueError(f"Invalid cycle_match regex: {exc}") from exc
-            if compiled.groups < 1:
-                raise ValueError("cycle_match must contain at least one capture group")
+        try:
+            version_method = models.sql.VersionMethod(form.version_method)
+        except ValueError as exc:
+            raise ValueError(f"Unsupported version method: {form.version_method}") from exc
+
+        # Calver projects describe cycles through a date format; everyone else
+        # through a cycle_match regex. Whichever applies, empty becomes None so
+        # we don't store empty strings in nullable columns.
+        if version_method is models.sql.VersionMethod.CALVER:
+            calver_format = form.calver_format.strip() or None
+            cycle_match = _calver_cycle_match(calver_format)
+        else:
+            calver_format = None
+            cycle_match = form.cycle_match.strip() or None
+            if cycle_match is not None:
+                try:
+                    compiled = re.compile(cycle_match)
+                except re.error as exc:
+                    raise ValueError(f"Invalid cycle_match regex: {exc}") from exc
+                if compiled.groups < 1:
+                    raise ValueError("cycle_match must contain at least one capture group")
 
         version_pattern = form.version_pattern.strip() or None
         if version_pattern is not None:
@@ -284,13 +296,10 @@ class ReleaseManager(CommitteeParticipant):
             except re.error as exc:
                 raise ValueError(f"Invalid version_pattern regex: {exc}") from exc
 
-        try:
-            version_method = models.sql.VersionMethod(form.version_method)
-        except ValueError as exc:
-            raise ValueError(f"Unsupported version method: {form.version_method}") from exc
         project.version_method = version_method
         project.version_pattern = version_pattern
         project.cycle_match = cycle_match
+        project.calver_format = calver_format
         project.branch_template = form.branch_template.strip() or None
 
         await cycles.reassign_release_cycles(self.__data, project)
@@ -488,6 +497,19 @@ async def _apply_policy_update_no_commit(
         setattr(release_policy, field, normalised_values[field])
 
 
+def _calver_cycle_match(calver_format: str | None) -> str | None:
+    # The format string's cycle group compiles to a cycle_match regex, so we don't
+    # need special calver membership handling. A string
+    # with no group (a linear project) leaves cycle_match unset.
+    if calver_format is None:
+        return None
+    try:
+        calver.validate(calver_format)
+    except ValueError as exc:
+        raise ValueError(f"Invalid calver format: {exc}") from exc
+    return calver.cycle_regex(calver_format)
+
+
 def _collapse_to_default(submitted: str, default_text: str) -> str:
     # Storing "" lets the project default apply. We compare ignoring line endings and
     # surrounding whitespace, otherwise a default that has been through a textarea - which
diff --git a/atr/storage/writers/project.py b/atr/storage/writers/project.py
index 7c6197cd..cc1b8704 100644
--- a/atr/storage/writers/project.py
+++ b/atr/storage/writers/project.py
@@ -508,6 +508,7 @@ async def _build_and_add_project(
         version_method=super_project.version_method if super_project else sql.VersionMethod.SIMPLE,
         version_pattern=super_project.version_pattern if super_project else None,
         cycle_match=super_project.cycle_match if super_project else None,
+        calver_format=super_project.calver_format if super_project else None,
         branch_template=super_project.branch_template if super_project else None,
         committee_key=str(committee_key),
         created=now,
diff --git a/migrations/versions/0099_2026.06.29_ca1ec0de.py b/migrations/versions/0099_2026.06.29_ca1ec0de.py
new file mode 100644
index 00000000..d0500722
--- /dev/null
+++ b/migrations/versions/0099_2026.06.29_ca1ec0de.py
@@ -0,0 +1,44 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Add calver_format to project
+
+Revision ID: 0099_2026.06.29_ca1ec0de
+Revises: 0098_2026.06.26_9a948e08
+Create Date: 2026-06-29 13:02:12.449325+00:00
+
+"""
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+revision: str = "0099_2026.06.29_ca1ec0de"
+down_revision: str | None = "0098_2026.06.26_9a948e08"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+    with op.batch_alter_table("project", schema=None) as batch_op:
+        batch_op.add_column(sa.Column("calver_format", sa.String(), nullable=True))
+
+
+def downgrade() -> None:
+    with op.batch_alter_table("project", schema=None) as batch_op:
+        batch_op.drop_column("calver_format")
diff --git a/tests/unit/test_calver.py b/tests/unit/test_calver.py
new file mode 100644
index 00000000..f8d327e5
--- /dev/null
+++ b/tests/unit/test_calver.py
@@ -0,0 +1,117 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+import re
+
+import pytest
+
+import atr.calver as calver
+
+
+def test_order_key_compares_dotted_non_padded_dates_numerically():
+    # Compared as strings "2020.10.5" sorts below "2020.6.24" ("1" < "6"), so
+    # the fields have to be compared as numbers instead.
+    date_format = "YYYY.M.D"
+    later = calver.order_key(date_format, "2020.10.5")
+    earlier = calver.order_key(date_format, "2020.6.24")
+    assert later is not None
+    assert earlier is not None
+    assert later > earlier
+
+
+def test_order_key_handles_run_together_mixed_granularity():
+    # A six- and an eight-digit version share one format; the shorter one reads
+    # its missing day as 0 rather than misparsing.
+    date_format = "YYYYMMDD"
+    assert calver.order_key(date_format, "201407") == (2014, 7, 0, 0)
+    assert calver.order_key(date_format, "20130710") == (2013, 7, 10, 0)
+    # The earlier year sorts first despite being the larger raw integer.
+    earlier = calver.order_key(date_format, "20130710")
+    later = calver.order_key(date_format, "201407")
+    assert earlier is not None
+    assert later is not None
+    assert earlier < later
+
+
+def test_order_key_reads_dashed_date():
+    assert calver.order_key("YYYY-MM-DD", "2025-11-03") == (2025, 11, 3, 0)
+
+
+def test_order_key_places_serial_after_calendar_fields():
+    date_format = "(YY.MM).N"
+    assert calver.order_key(date_format, "09.04") == (9, 4, 0, 0)
+    assert calver.order_key(date_format, "09.04.01") == (9, 4, 0, 1)
+    first_patch = calver.order_key(date_format, "09.04.01")
+    second_patch = calver.order_key(date_format, "09.04.02")
+    assert first_patch is not None
+    assert second_patch is not None
+    assert first_patch < second_patch
+
+
+def test_order_key_returns_none_for_unparseable_version():
+    assert calver.order_key("YYYY.MM.DD", "not-a-date") is None
+
+
+def test_cycle_regex_captures_parenthesised_span_as_group_one():
+    pattern = calver.cycle_regex("(YY.MM).N")
+    assert pattern is not None
+    compiled = re.compile(pattern)
+    patched = compiled.fullmatch("09.04.01")
+    assert patched is not None
+    assert patched.group(1) == "09.04"
+    # The trailing serial is optional, so the bare line still matches.
+    bare = compiled.fullmatch("09.04")
+    assert bare is not None
+    assert bare.group(1) == "09.04"
+
+
+def test_cycle_regex_returns_none_for_linear_format():
+    # No parenthesised span means a single default cycle, so cycle_match stays unset.
+    assert calver.cycle_regex("YYYY.MM.DD") is None
+
+
+def test_cycle_regex_round_trips_through_fullmatch():
+    pattern = calver.cycle_regex("(YYYY)-MM-DD")
+    assert pattern is not None
+    matched = re.compile(pattern).fullmatch("2025-11-03")
+    assert matched is not None
+    assert matched.group(1) == "2025"
+
+
+def test_validate_rejects_format_without_calendar_field():
+    with pytest.raises(ValueError, match="at least one"):
+        calver.validate("N.N")
+
+
+def test_validate_rejects_repeated_field():
+    with pytest.raises(ValueError, match="repeats"):
+        calver.validate("YYYY.YYYY")
+
+
+def test_validate_rejects_unbalanced_parentheses():
+    with pytest.raises(ValueError, match="unmatched"):
+        calver.validate("(YY.MM")
+
+
+def test_validate_rejects_two_cycle_spans():
+    with pytest.raises(ValueError, match="at most one"):
+        calver.validate("(YY).(MM)")
+
+
+def test_validate_accepts_real_world_formats():
+    for date_format in ("YYYY.M.D", "YYYYMMDD", "YYYY-MM-DD", "(YY.MM).N"):
+        calver.validate(date_format)
diff --git a/tests/unit/test_cycles.py b/tests/unit/test_cycles.py
index 5644730b..58b1e7de 100644
--- a/tests/unit/test_cycles.py
+++ b/tests/unit/test_cycles.py
@@ -20,6 +20,7 @@ from types import SimpleNamespace
 
 import pytest
 
+import atr.calver as calver
 import atr.cycles as cycles
 import atr.models.sql as sql
 
@@ -57,15 +58,68 @@ def test_cycle_name_supports_named_cycle_via_capture():
     assert cycles.cycle_name_for_version(project, "stable-2.5") == "stable"
 
 
-def test_prior_release_calver_returns_none():
-    # CALVER ordering not yet implemented - confirm explicit None contract.
+def test_prior_release_calver_picks_highest_below_target_within_a_cycle():
+    # A cycled calver project: the YY.MM is the cycle, the trailing serial
+    # the patch level. The prior of a patch is the patch below it in the line.
     project = SimpleNamespace(
         key="example",
-        cycle_match=r"^(\d{4})\.\d+$",
+        cycle_match=calver.cycle_regex("(YY.MM).N"),
+        calver_format="(YY.MM).N",
+        version_method=sql.VersionMethod.CALVER,
+    )
+    candidates = [
+        _release("09.04", _ts(1)),
+        _release("09.04.01", _ts(2)),
+        _release("09.04.02", _ts(3)),
+        _release("10.04", _ts(4)),
+    ]
+    prior = cycles.prior_release_in_cycle(project, "09.04.03", candidates)
+    assert prior is not None
+    assert prior.version == "09.04.02"
+
+
+def test_prior_release_calver_orders_non_padded_dotted_dates():
+    # A linear calver project with no cycle span: every release shares the
+    # default cycle and ordering is purely by date.
+    project = SimpleNamespace(
+        key="example",
+        cycle_match=None,
+        calver_format="YYYY.M.D",
+        version_method=sql.VersionMethod.CALVER,
+    )
+    # Released-date ordering deliberately reversed to prove we sort by version.
+    candidates = [
+        _release("2020.10.5", _ts(1)),
+        _release("2020.6.24", _ts(10)),
+        _release("2020.11.13", _ts(5)),
+    ]
+    prior = cycles.prior_release_in_cycle(project, "2020.12.1", candidates)
+    assert prior is not None
+    assert prior.version == "2020.11.13"
+
+
+def test_prior_release_calver_falls_back_to_released_without_a_mask():
+    project = SimpleNamespace(
+        key="example",
+        cycle_match=None,
+        calver_format=None,
         version_method=sql.VersionMethod.CALVER,
     )
     candidates = [_release("2025.1", _ts(1)), _release("2025.2", _ts(5))]
-    assert cycles.prior_release_in_cycle(project, "2025.3", candidates) is None
+    prior = cycles.prior_release_in_cycle(project, "2025.3", candidates)
+    assert prior is not None
+    assert prior.version == "2025.2"
+
+
+def test_prior_release_calver_returns_none_when_target_does_not_fit_mask():
+    project = SimpleNamespace(
+        key="example",
+        cycle_match=None,
+        calver_format="YYYY.MM.DD",
+        version_method=sql.VersionMethod.CALVER,
+    )
+    candidates = [_release("2025.01.01", _ts(1))]
+    assert cycles.prior_release_in_cycle(project, "garbage", candidates) is None
 
 
 def test_prior_release_filters_to_same_cycle_for_semver():
diff --git a/tests/unit/test_policy_writer.py b/tests/unit/test_policy_writer.py
index 7471ab1d..b1eabf05 100644
--- a/tests/unit/test_policy_writer.py
+++ b/tests/unit/test_policy_writer.py
@@ -16,6 +16,7 @@
 # under the License.
 
 import datetime
+import re
 import unittest.mock as mock
 from types import SimpleNamespace
 
@@ -263,6 +264,45 @@ async def test_edit_version_scheme_saves_all_fields_normalised():
     data.commit.assert_awaited_once()
 
 
+async def test_edit_version_scheme_compiles_calver_mask_cycle_span_into_cycle_match():
+    project = _project()
+    data = _MockData(project=project)
+    writer = _make_committee_member(data)
+    form = _version_scheme_form(version_method=sql.VersionMethod.CALVER, calver_format="(YY.MM).N")
+
+    await writer.edit_version_scheme(form)
+
+    assert project.version_method is sql.VersionMethod.CALVER
+    assert project.calver_format == "(YY.MM).N"
+    # The parenthesised span becomes the cycle_match capture group.
+    assert project.cycle_match is not None
+    matched = re.compile(project.cycle_match).fullmatch("09.04.01")
+    assert matched is not None
+    assert matched.group(1) == "09.04"
+
+
+async def test_edit_version_scheme_leaves_cycle_match_unset_for_linear_calver():
+    project = _project()
+    data = _MockData(project=project)
+    writer = _make_committee_member(data)
+    form = _version_scheme_form(version_method=sql.VersionMethod.CALVER, calver_format="YYYY.MM.DD")
+
+    await writer.edit_version_scheme(form)
+
+    assert project.calver_format == "YYYY.MM.DD"
+    assert project.cycle_match is None
+
+
+async def test_edit_version_scheme_rejects_invalid_calver_mask():
+    project = _project()
+    data = _MockData(project=project)
+    writer = _make_committee_member(data)
+
+    with pytest.raises(pydantic.ValidationError, match="at least one"):
+        form = _version_scheme_form(version_method=sql.VersionMethod.CALVER, calver_format="N.N")
+        await writer.edit_version_scheme(form)
+
+
 async def test_edit_version_scheme_skips_release_already_in_correct_cycle():
     project = _project()
     releases = [_release("0.1", cycle_key="example-0")]
@@ -344,6 +384,7 @@ def _version_scheme_form(
     version_method=sql.VersionMethod.SIMPLE,
     version_pattern="",
     cycle_match="",
+    calver_format="",
     branch_template="",
 ):
     return shared_projects.EditVersionSchemeForm(
@@ -353,5 +394,6 @@ def _version_scheme_form(
         version_method=version_method,
         version_pattern=version_pattern,
         cycle_match=cycle_match,
+        calver_format=calver_format,
         branch_template=branch_template,
     )


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org