← Back to Pull requests

Display 'file added late' badge on release history page #20608

Closed
nlhkabu closed this pull request without merging on Oct 08, 2026 18:53 UTC
View on GitHub
nlhkabu nlhkabu commented on Sep 25, 2026 20:00 UTC
Author

Closes #20555

Python code generated by Claude, following patterns established in https://github.com/pypi/warehouse/pull/20420 - requires thorough review

CSS and HTML generated, but reviewed and edited by me :)

Desktop


<img width="1290" height="472" alt="Screenshot 2026-09-25 at 20-53-13 tor_async_util · Warehouse" src="https://github.com/user-attachments/assets/3dd0f414-0394-4d9b-8016-4b95a0001335" />

Mobile


<img width="300" alt="image" src="https://github.com/user-attachments/assets/71df1337-0867-4643-b6c7-24ef5a655fb0" />

Diff: 174 lines (+159 / -15) across 5 files Reviewer: JacobCoffee Review duration: 18653m
All Vouch review confidence checks passed
Residual risk 0.08 = Change Risk (0.45) × (1 − Review Confidence (0.83)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.45 · 174 lines diff across 5 files
0.45
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.74 · 4 substantive comment(s)
0.74
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
83%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.309
Ai Authored ai_authored
0.050
Real PR Conversation Timeline
6 items
JacobCoffee JacobCoffee commented on code on Sep 30, 2026 22:20 UTC
Code Review
tests/unit/packaging/test_models.py:1
@@ -906,6 +947,53 @@ def _release(version, days):
         for release in (no_prov, full, partial, inconsistent, changed, lost):
             assert statuses[release.version].states == release.provenance_status.states
 
+    def test_late_file_statuses_agree_with_each_release(self, db_session):
+        """
+        The batched statuses are the per-release ones, for every release.
+
+        Pinning them to each other is what lets the release history page read
+        the project-wide mapping while a release page reads its own status,
+        without the two drifting apart. The count is asserted first, so that
+        both sides returning nothing cannot satisfy the equality.
+        """
+        project = _late_file_history()
+
+        statuses = project.late_file_statuses
+
+        assert len(statuses) == 2
+        assert statuses == {
+            release.version: release.late_file_status
+            for release in project.releases
+            if release.late_file_status is not None
+        }
+
+    def test_late_file_statuses_costs_one_query_once(self, db_session, query_recorder):
+        """
+        Every release's status comes back in a single query, run only once.
+
+        This is the whole point of the property. The release history page
+        renders one card per release and reads `late_files` off each status,
+        so neither the release count nor the number of reads may cost
+        another query.
+        """
+        project = _late_file_history()
+        db_session.flush()
+        assert project.id is not None  # load the project row before counting
+
+        query_recorder.clear()
+        with query_recorder:
+            statuses = [project.late_file_statuses for _ in range(3)]
+
+        assert len(statuses[0]) == 2
+        assert all(repeat is statuses[0] for repeat in statuses)
+        assert len(query_recorder.queries) == 1, query_recorder.queries
+
+    def test_late_file_statuses_omits_releases_without_files(self, db_session):

is this test sitll needed? we assert 2 tests in test_late_file_statuses_agree_with_each_release so it should cover? unsure

JacobCoffee JacobCoffee commented on code on Sep 30, 2026 22:26 UTC
Code Review
warehouse/packaging/models.py:1
@@ -692,6 +692,50 @@ def provenance_statuses(self) -> dict[str, ProvenanceStatus]:
             if counts.total_files
         }
 
+    @cached_property
+    def late_file_statuses(self) -> dict[str, LateFileStatus]:
+        """
+        Every release's late-file status, keyed by version.
+
+        The release history page needs a status per release. Reading
+        `Release.late_file_status` in a loop costs one query for each one;
+        this takes one, grouping the project's files by the release they
+        belong to.
+
+        A release with no files is absent from the mapping, matching
+        `Release.late_file_status` returning `None`. Read it with `.get()`:
+        a project can hold a release whose files have all been removed.
+
+        Cached for the life of the `Project`, so a caller holding one across
+        a commit sees the statuses as they were when it first asked. That
+        suits a request, which reads them once and renders; a long-lived
+        task wanting fresh counts should ask a `Release` instead.
+        """
+        rows = (
+            orm_session_from_obj(self)
+            .execute(
+                select(
+                    Release.version, Release.created, File.filename, File.upload_time
+                )
+                .select_from(Release)
+                .outerjoin(File, File.release_id == Release.id)
+                .where(Release.project_id == self.id)
+            )
+            .all()
+        )

        rows = (
            orm_session_from_obj(self)
            .execute(
                select(
                    Release.version, Release.created, File.filename, File.upload_time
                )
                .select_from(Release)
                .join(File, File.release_id == Release.id)
                .where(
                    Release.project_id == self.id,
                    File.upload_time - Release.created > MAXIMUM_AGE_FOR_NEW_UPLOADS,
                )
            )
            .all()
        )

since the templat only uses late_files we can prob clean up this query to not pull in every file. adding some kind of filtering like File.upload_time - Release.created > MAXIMUM_AGE_FOR_NEW_UPLOAD here would be good but youll have to update your tests

JacobCoffee JacobCoffee requested changes on Sep 30, 2026 22:28 UTC
Changes Requested Reviewer

Requested changes.

JacobCoffee JacobCoffee commented on code on Sep 30, 2026 22:32 UTC
Code Review
warehouse/packaging/models.py:1
@@ -692,6 +692,50 @@ def provenance_statuses(self) -> dict[str, ProvenanceStatus]:
             if counts.total_files
         }
 
+    @cached_property
+    def late_file_statuses(self) -> dict[str, LateFileStatus]:
+        """
+        Every release's late-file status, keyed by version.
+
+        The release history page needs a status per release. Reading
+        `Release.late_file_status` in a loop costs one query for each one;
+        this takes one, grouping the project's files by the release they
+        belong to.
+
+        A release with no files is absent from the mapping, matching
+        `Release.late_file_status` returning `None`. Read it with `.get()`:
+        a project can hold a release whose files have all been removed.
+
+        Cached for the life of the `Project`, so a caller holding one across
+        a commit sees the statuses as they were when it first asked. That
+        suits a request, which reads them once and renders; a long-lived
+        task wanting fresh counts should ask a `Release` instead.
+        """
+        rows = (
+            orm_session_from_obj(self)
+            .execute(
+                select(
+                    Release.version, Release.created, File.filename, File.upload_time
+                )
+                .select_from(Release)
+                .outerjoin(File, File.release_id == Release.id)
+                .where(Release.project_id == self.id)
+            )
+            .all()
+        )

actually, i threw this suggestion at the robot and it came up with a maybe better solution, too - making things a little cleaner and getting rid of some of the lines in the model if you want to review.

<details>
<summary>Details</summary>

diff --git a/tests/unit/packaging/test_models.py b/tests/unit/packaging/test_models.py
index 25a2091c4..02f6bed46 100644
--- a/tests/unit/packaging/test_models.py
+++ b/tests/unit/packaging/test_models.py
@@ -141,13 +141,7 @@ def _provenance_history(publisher=None):
 
 
 def _late_file_history():
-    """
-    A project with three releases: late files, punctual files, and none.
-
-    Mirrors `_provenance_history`'s shape for `provenance_statuses`, giving
-    `late_file_statuses` a release on every branch its per-release
-    counterpart, `Release.late_file_status`, can take.
-    """
+    """A project with late files, punctual files, and a release without files."""
     project = DBProjectFactory.create()
     late = DBReleaseFactory.create(project=project, version="1.0", created=_RELEASED_AT)
     DBFileFactory.create(
@@ -162,6 +156,12 @@ def _late_file_history():
         packagetype="sdist",
         upload_time=_RELEASED_AT + datetime.timedelta(days=30),
     )
+    DBFileFactory.create(
+        release=late,
+        filename=f"{project.name}-1.0-2.whl",
+        packagetype="bdist_wheel",
+        upload_time=_RELEASED_AT + datetime.timedelta(days=31),
+    )
     punctual = DBReleaseFactory.create(
         project=project,
         version="2.0",
@@ -947,52 +947,49 @@ class TestProject:
         for release in (no_prov, full, partial, inconsistent, changed, lost):
             assert statuses[release.version].states == release.provenance_status.states
 
-    def test_late_file_statuses_agree_with_each_release(self, db_session):
-        """
-        The batched statuses are the per-release ones, for every release.
-
-        Pinning them to each other is what lets the release history page read
-        the project-wide mapping while a release page reads its own status,
-        without the two drifting apart. The count is asserted first, so that
-        both sides returning nothing cannot satisfy the equality.
-        """
+    def test_late_file_counts_agree_with_each_release(self, db_session):
         project = _late_file_history()
+        _late_file_history()  # Another project's files must not affect these counts.
 
-        statuses = project.late_file_statuses
+        counts = project.late_file_counts
 
-        assert len(statuses) == 2
-        assert statuses == {
-            release.version: release.late_file_status
+        assert counts == {"1.0": 2}
+        assert counts == {
+            release.version: len(status.late_files)
             for release in project.releases
-            if release.late_file_status is not None
+            if (status := release.late_file_status) is not None and status.late_files
         }
 
-    def test_late_file_statuses_costs_one_query_once(self, db_session, query_recorder):
-        """
-        Every release's status comes back in a single query, run only once.
-
-        This is the whole point of the property. The release history page
-        renders one card per release and reads `late_files` off each status,
-        so neither the release count nor the number of reads may cost
-        another query.
-        """
+    def test_late_file_counts_costs_one_query_once(self, db_session, query_recorder):
         project = _late_file_history()
         db_session.flush()
         assert project.id is not None  # load the project row before counting
 
         query_recorder.clear()
         with query_recorder:
-            statuses = [project.late_file_statuses for _ in range(3)]
+            counts = [project.late_file_counts for _ in range(3)]
 
-        assert len(statuses[0]) == 2
-        assert all(repeat is statuses[0] for repeat in statuses)
+        assert all(count == {"1.0": 2} for count in counts)
         assert len(query_recorder.queries) == 1, query_recorder.queries
 
-    def test_late_file_statuses_omits_releases_without_files(self, db_session):
-        """A release with no files has no status, the same as on the release."""
-        project = _late_file_history()
+    @pytest.mark.parametrize(
+        ("delay", "expected"),
+        [
+            (MAXIMUM_AGE_FOR_NEW_UPLOADS, {}),
+            (
+                MAXIMUM_AGE_FOR_NEW_UPLOADS + datetime.timedelta(seconds=1),
+                {"1.0": 1},
+            ),
+        ],
+    )
+    def test_late_file_counts_use_release_date_and_strict_window(
+        self, db_session, delay, expected
+    ):
+        release = DBReleaseFactory.create(version="1.0", created=_RELEASED_AT)
+        # No original file remains: the cutoff must still use the release date.
+        DBFileFactory.create(release=release, upload_time=release.created + delay)
 
-        assert set(project.late_file_statuses) == {"1.0", "2.0"}
+        assert release.project.late_file_counts == expected
 
 
 class TestDependency:
diff --git a/warehouse/packaging/models.py b/warehouse/packaging/models.py
index 6dab0406d..c9dff4ff5 100644
--- a/warehouse/packaging/models.py
+++ b/warehouse/packaging/models.py
@@ -693,48 +693,24 @@ class Project(SitemapMixin, HasEvents, HasObservations, db.Model):
         }
 
     @cached_property
-    def late_file_statuses(self) -> dict[str, LateFileStatus]:
+    def late_file_counts(self) -> dict[str, int]:
         """
-        Every release's late-file status, keyed by version.
+        Count late files by version in one query for the release history.
 
-        The release history page needs a status per release. Reading
-        `Release.late_file_status` in a loop costs one query for each one;
-        this takes one, grouping the project's files by the release they
-        belong to.
-
-        A release with no files is absent from the mapping, matching
-        `Release.late_file_status` returning `None`. Read it with `.get()`:
-        a project can hold a release whose files have all been removed.
-
-        Cached for the life of the `Project`, so a caller holding one across
-        a commit sees the statuses as they were when it first asked. That
-        suits a request, which reads them once and renders; a long-lived
-        task wanting fresh counts should ask a `Release` instead.
+        Releases without late files are omitted; read with `.get(version, 0)`.
+        Counts are cached for the life of the Project instance.
         """
-        rows = (
-            orm_session_from_obj(self)
-            .execute(
-                select(
-                    Release.version, Release.created, File.filename, File.upload_time
-                )
-                .select_from(Release)
-                .outerjoin(File, File.release_id == Release.id)
-                .where(Release.project_id == self.id)
+        rows = orm_session_from_obj(self).execute(
+            select(Release.version, func.count(File.id))
+            .select_from(Release)
+            .join(File, File.release_id == Release.id)
+            .where(
+                Release.project_id == self.id,
+                File.upload_time - Release.created > MAXIMUM_AGE_FOR_NEW_UPLOADS,
             )
-            .all()
+            .group_by(Release.version)
         )
-        grouped: dict[str, tuple[datetime.datetime, list[Row]]] = {}
-        for row in rows:
-            if row.version not in grouped:
-                grouped[row.version] = (row.created, [])
-            if row.filename is not None:
-                grouped[row.version][1].append(row)
-
-        return {
-            version: status
-            for version, (created, files) in grouped.items()
-            if (status := late_file_status_from_files(created, files)) is not None
-        }
+        return {version: count for version, count in rows}
 
     @property
     def latest_version(self):
diff --git a/warehouse/templates/includes/packaging/project-release-history.html b/warehouse/templates/includes/packaging/project-release-history.html
index f71d45d40..f27829702 100644
--- a/warehouse/templates/includes/packaging/project-release-history.html
+++ b/warehouse/templates/includes/packaging/project-release-history.html
@@ -15,7 +15,7 @@
     {% set blue_cube = request.static_url('warehouse:static/dist/images/blue-cube.svg') %}
     {% set white_cube = request.static_url('warehouse:static/dist/images/white-cube.svg') %}
     {% set provenance_statuses = project.provenance_statuses %}
-    {% set late_file_statuses = project.late_file_statuses %}
+    {% set late_file_counts = project.late_file_counts %}
     {% for hversion in all_versions %}
       {% set is_current = (hversion.version == release.version) %}
       {% if hversion.lifecycle_status == "quarantine-enter" or project.lifecycle_status == "quarantine-enter" %}
@@ -30,7 +30,7 @@
         {% set status_modifier = "" %}
       {% endif %}
       {% set provenance_status = provenance_statuses[hversion.version] %}
-      {% set late_file_status = late_file_statuses[hversion.version] %}
+      {% set late_file_count = late_file_counts.get(hversion.version, 0) %}
       <div class="release{{ ' release--current' if is_current }}{{ ' ' + status_modifier if status_modifier }}">
         <div class="release__current-badge">
           {% if is_current %}
@@ -103,10 +103,10 @@
               {% if is_current %}
                 <span class="badge">{% trans %}This release{% endtrans %}</span>
               {% endif %}
-              {% if late_file_status and late_file_status.late_files %}
+              {% if late_file_count %}
                 <a class="badge badge--warning"
                    href="{{ request.route_path('packaging.release', name=release.project.name, version=hversion.version) }}#files">
-                  {% trans count=late_file_status.late_files|length %}File added late
+                  {% trans count=late_file_count %}File added late
                 {% pluralize %}
                   Files added late{% endtrans %}
                 </a>

</details>

nlhkabu nlhkabu commented on Oct 08, 2026 18:53 UTC
Author

Closing as per discussion with @di

This will take some work to make performant and is not a hard requirement for the display of attestations.

Reviewers
Assignees
nlhkabu nlhkabu
Labels
risk: low confidence: 83% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 44.8% (MEDIUM) · Higher = larger blast radius
44.8%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 83% · Lower = rushed or shallow review
83%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 7.6% · Safe to merge
7.6%
Repository