Skip to content

fix model hub recent sorting for on-device models - #9642

Merged
mahiatlinux merged 26 commits into
unslothai:mainfrom
Imagineer99:fix/model-hub-recent-sort
Aug 28, 2026
Merged

mahiatlinux merged 26 commits into
unslothai:mainfrom
Imagineer99:fix/model-hub-recent-sort

Conversation

@Imagineer99

@Imagineer99 Imagineer99 commented Aug 24, 2026 •

Copy link
Copy Markdown
Member

Summary

  • make Model Hub → On Device → Recent sort by normalized model timestamps instead of preserving backend/source order
  • normalize cached-model timestamps to milliseconds and timestamp active downloads immediately
  • keep models without timestamps stable at the end of the list
  • add regression coverage for mixed Unsloth cache and LM Studio inventory

Fixes #9617

Validation

  • node --experimental-strip-types --test tests/hub-inventory-recent-sort.test.ts tests/training-cache-reconciliation.test.ts tests/pinned-models-reorder.test.ts tests/hub-recovery-paths.test.ts — 58 passed
  • npm run typecheck
  • npm run build
  • Playwright Chromium comparison against exact commits:
    • BEFORE: 0998656891170ce53abef1f1f4383d88e2d5a7ae
    • AFTER: f1f51901072be222d953910e0705e764ec549824
    • identical mixed Unsloth-cache and LM Studio inventory on both sides
    • exact DOM order asserted; zero page errors

UI evidence

Both sides use the same four timestamps, all before the capture date (2026-08-24). BEFORE preserves alphabetical/source order; AFTER orders newest to oldest across sources.

Playwright BEFORE and AFTER comparison

Individual captures

BEFORE

BEFORE: Recent preserves source order

AFTER

AFTER: Recent sorts newest to oldest

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f1f5190107

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed the recent branch in studio/frontend/src/features/hub/catalog/models-catalog-lists.tsx only applied pin rank and source order, and cached rows kept raw seconds while local rows were milliseconds. Will get this reviewed.

@danielhanchen

Copy link
Copy Markdown
Member

Verified this end to end and it holds up. Summary first, evidence below.

The bug is real and the root cause is right. Two defects were stacked:

  1. DownloadedList's recent branch sorted by pinRank(a) - pinRank(b) || a.index - b.index. There was no date term at all, so "Recent" was a no-op that reproduced source order.
  2. Even with one, the two row kinds were on different scales. buildLocalInventoryRows already ran updated_at through normalizeTimestamp (milliseconds), while buildCachedInventoryRow passed last_modified through raw (seconds), so every LM Studio row would have outranked every Unsloth-cache row regardless of date.

The backend really does emit seconds: cache_inventory.py:152-171 derives last_modified from CachedFileInfo.blob_last_modified, which huggingface_hub documents as a float of epoch seconds and warns is OS-dependent for reliability. Reusing the existing normalizeTimestamp rather than inventing a second convention is the right call.

Before and after, on the real component

I rendered the actual DownloadedList out of two worktrees, the merge base 0998656 and the head f1f5190, driving one identical fixture through each. The recency term is written inline inside the component's useMemo, so a test that re-implements pinRank || recent || index would only prove the re-implementation works; this renders the component.

scenario base head
#9617 repro bert, gemma, Qwen, llama-3, mistral Qwen, llama-3, gemma, bert, mistral fixed
sort = name identical identical no collateral
sort = size identical identical no collateral
search active identical identical no collateral
old backend, no timestamps identical identical byte-for-byte unchanged
pinned drag order Qwen, bert, gemma, llama-3, mistral Qwen, bert, llama-3, gemma, mistral pins held, only the tail re-sorted
datasets a, b, recipe-output recipe-output, a, b the P2 below

The base row reproduces the report exactly: bert-base-uncased pinned at the top, LM Studio rows stranded at the bottom. Pinned rows keep their manual order because makePinRank assigns a distinct rank per pinned id, so pinned rows never tie and the new comparator never reaches them.

Nothing else breaks

  • Only two reads of lastModified exist in the whole frontend: inventory-sort.ts:19-22, and the two forwarders in use-chat-picker-inventory.ts:38,52.
  • No inventory timestamp is ever persisted. I checked every localStorage/sessionStorage.setItem in src/ programmatically, not by eye. unsloth.model-load-times.v1 and unsloth.last-local-model-load.v1 are Date.now()-sourced and never meet an inventory value. So an install upgraded from a seconds-era build cannot compare a stored seconds value against a fresh milliseconds one. That was my main worry going in and it is simply not reachable.
  • sortCachedRepos is scale-invariant within a homogeneous list, and its loadedAt term is compared separately, never subtracted from last_modified.
  • soleQuantFingerprint changes, but it is an in-memory map that starts empty each mount and records-only on first sight, so no spurious cache invalidation after upgrade.
  • formatLocalUpdated re-normalizes internally, and no UI currently renders a cached row's lastModified at all, so there is no display regression surface.
  • Dedup runs on identity before the sort, so recency cannot change which duplicate survives.

Two things to fix

1. A completed download drops to the bottom of Recent. Codex was right; details and a repro table in that thread.

2. Datasets Recent is inert. Codex was right about the premise; I fixed it in the backend instead of gating the comparator, detail here.

3. Minor: chat-api.ts:437 and :581 document last_modified as "Epoch seconds", which is now false on the picker path. The same type name carries seconds from listCachedGguf and milliseconds from the picker inventory. Nothing reads it on the raw path today (chat-adapter.ts:3424 and agents-tab.tsx:879 use only ids), so it is a documentation hazard rather than a live bug, but it is how the next bug gets written.

What I ran

suite result
normalizeTimestamp boundary table: undefined, null, 0, negative, NaN, +/-Infinity, strings, fractional mtime, 9_999_999_999, 10_000_000_000, ms passthrough 17 pass
OS-shaped payloads: ext4, APFS, NTFS, FAT32 2-second granularity plus a DST-shifted twin, WSL DrvFs, Windows no-symlink HF cache, broken symlink, network share mtime 0, old backend omitting the key, future backend already in ms, mixed seconds/ms fleet 17 pass
Comparator algebra: reflexivity, anti-symmetry, transitivity over all ordered triples, no NaN, and all 720 permutations of a 6-element list matching a stable reference sort 2 pass
Download lifecycle: running, progress ticks, complete, TTL expiry, rescan, cancelled/errored 1 failed before the fix, 7 pass after
Old-install upgrade and model-picker propagation 8 pass
Browser matrix, chromium / firefox / webkit identical order in all three, zero page errors
npm test 4872 pass, 0 fail
npm run typecheck, npm run build, npm run bundle:check, biome, eslint clean
backend hub/tests/test_dataset_cache_timestamps.py (new) 8 pass
backend test_cached_gguf_routes.py 190 pass, 1 skipped, models path untouched

The lifecycle suite was written to fail before the fix and pass after; a green-on-both test would not have been testing anything.

What this run cannot tell you

  • I ran on Linux. The OS axis is covered by replaying the payloads each filesystem produces, not by booting Windows or macOS. Worth noting CI already runs npm test on Windows (studio-frontend-ci.yml:570), so the new suites get real Windows coverage there.
  • Chromium stands in for Chrome and Edge, WebKit for Safari. Those are the engines, not the shipped browsers.
  • There is no GPU or hardware axis here: this PR is TypeScript in studio/frontend plus, with my change, Python in studio/backend. No CUDA, ROCm or device-selection code is touched, so an NVIDIA/AMD/CPU matrix would be identical cells by construction.
  • One caveat found and documented rather than hidden: normalizeTimestamp's 10_000_000_000 pivot is a heuristic, not a converter. It is idempotent only for values landing at or above the pivot, so a raw seconds value below 10_000_000 (before 1970-04-26) would be multiplied twice. Unreachable for any real mtime, but it is why the helper must stay a single-boundary ingestion step.

Patch

Cannot push to the branch (maintainerCanModify is false on this fork), so here it is to apply directly.

git apply for all three fixes
diff --git a/studio/backend/hub/schemas/datasets.py b/studio/backend/hub/schemas/datasets.py
index c72623d97..4e06a4b40 100644
--- a/studio/backend/hub/schemas/datasets.py
+++ b/studio/backend/hub/schemas/datasets.py
@@ -94,6 +94,9 @@ class LocalDatasetsResponse(BaseModel):
 class CachedDatasetItem(BaseModel):
     repo_id: str
     size_bytes: int = 0
+    # Epoch SECONDS, matching the cached-model scan. Unset when no cache path had
+    # a readable mtime, so the UI can tell "unknown" from "the epoch".
+    last_modified: Optional[float] = None
     cache_path: Optional[str] = None
     load_cache_path: Optional[str] = None
     processed_cache: bool = False
diff --git a/studio/backend/hub/services/datasets/cache_inventory.py b/studio/backend/hub/services/datasets/cache_inventory.py
index a4a8fb3b7..a216a9c8e 100644
--- a/studio/backend/hub/services/datasets/cache_inventory.py
+++ b/studio/backend/hub/services/datasets/cache_inventory.py
@@ -81,6 +81,45 @@ def _directory_size(path: Path) -> int:
     return total
 
 
+def _safe_mtime(path: Path) -> float:
+    """Directory mtime as POSIX seconds, or 0.0 when it cannot be read.
+
+    Uses only mtimes, so it is portable across Windows, macOS and Linux. A
+    broken snapshot symlink, a deleted cache mid-scan, or a share with no usable
+    clock all land on 0.0, which callers drop rather than reporting as 1970.
+    """
+    try:
+        mtime = path.stat().st_mtime
+    except OSError:
+        return 0.0
+    return float(mtime) if isinstance(mtime, (int, float)) and mtime > 0 else 0.0
+
+
+def _dataset_last_modified(candidate, *paths: Optional[Path]) -> float:
+    """Newest change time for a cached dataset row, as POSIX seconds.
+
+    Prefers the value huggingface_hub already computed, then falls back to
+    stat()ing the cache directories. Matches the unit the cached-model scan
+    emits, which is what the frontend's normalizeTimestamp expects.
+    """
+    newest = float(candidate) if isinstance(candidate, (int, float)) and candidate > 0 else 0.0
+    for path in paths:
+        if path is None:
+            continue
+        newest = max(newest, _safe_mtime(path))
+    return newest
+
+
+def _merge_last_modified(existing: dict, row: dict) -> None:
+    """Keep the newer of two timestamps when two scans describe one dataset."""
+    newest = max(
+        float(existing.get("last_modified") or 0.0),
+        float(row.get("last_modified") or 0.0),
+    )
+    if newest > 0:
+        existing["last_modified"] = newest
+
+
 def _prefer_dataset_cache_row(candidate: dict, existing: Optional[dict]) -> bool:
     if existing is None:
         return True
@@ -294,6 +333,7 @@ def _scan_hub_dataset_cache_dirs() -> list[dict]:
                 or hf_cache_scan.is_snapshot_partial("dataset", repo_id, entry)
                 or not _raw_dataset_cache_has_data(repo_id, entry)
             )
+            last_modified = _dataset_last_modified(None, entry / "snapshots", entry)
             row = {
                 "repo_id": repo_id,
                 "size_bytes": size_bytes,
@@ -319,6 +359,8 @@ def _scan_hub_dataset_cache_dirs() -> list[dict]:
                     else False
                 ),
             }
+            if last_modified > 0:
+                row["last_modified"] = last_modified
             if _prefer_dataset_cache_row(row, existing):
                 seen_lower[key] = row
     return sorted(seen_lower.values(), key = lambda c: c["repo_id"])
@@ -389,13 +431,17 @@ def _scan_processed_dataset_caches() -> list[dict]:
             key = repo_id.lower()
             existing = seen_lower.get(key)
             if existing is None or size_bytes > existing["size_bytes"]:
-                seen_lower[key] = {
+                processed_row = {
                     "repo_id": repo_id,
                     "size_bytes": size_bytes,
                     "cache_path": str(entry.resolve()),
                     "processed_cache": True,
                     "partial": False,
                 }
+                processed_mtime = _dataset_last_modified(None, entry)
+                if processed_mtime > 0:
+                    processed_row["last_modified"] = processed_mtime
+                seen_lower[key] = processed_row
     return sorted(seen_lower.values(), key = lambda c: c["repo_id"])
 
 
@@ -409,7 +455,7 @@ def _scan_app_processed_dataset_caches() -> list[dict]:
         )
         existing = grouped.get(key)
         if existing is None:
-            grouped[key] = {
+            app_row = {
                 "repo_id": entry.repo_id,
                 "size_bytes": size_bytes,
                 "cache_path": str(entry.path),
@@ -418,8 +464,13 @@ def _scan_app_processed_dataset_caches() -> list[dict]:
                 "app_processed_hub_cache": str(entry.hub_cache),
                 "partial": True,
             }
+            app_mtime = _dataset_last_modified(None, entry.path)
+            if app_mtime > 0:
+                app_row["last_modified"] = app_mtime
+            grouped[key] = app_row
         else:
             existing["size_bytes"] += size_bytes
+            _merge_last_modified(existing, {"last_modified": _dataset_last_modified(None, entry.path)})
     return sorted(
         grouped.values(),
         key = lambda row: (row["repo_id"].casefold(), row["app_processed_hub_cache"]),
@@ -456,6 +507,11 @@ def _scan_hf_dataset_caches() -> list[dict]:
                     repo_info.repo_id,
                     cache_dir,
                 ) or not _raw_dataset_cache_has_data(repo_info.repo_id, cache_dir)
+                repo_last_modified = _dataset_last_modified(
+                    getattr(repo_info, "last_modified", None),
+                    cache_dir / "snapshots",
+                    cache_dir,
+                )
                 row = {
                     "repo_id": repo_info.repo_id,
                     "size_bytes": total_size,
@@ -480,6 +536,8 @@ def _scan_hf_dataset_caches() -> list[dict]:
                         else False
                     ),
                 }
+                if repo_last_modified > 0:
+                    row["last_modified"] = repo_last_modified
                 if _prefer_dataset_cache_row(row, existing):
                     seen_lower[key] = row
             except Exception as exc:
@@ -492,6 +550,7 @@ def _scan_hf_dataset_caches() -> list[dict]:
             seen_lower[key] = row
         elif existing is not None and bool(existing.get("partial")) == bool(row.get("partial")):
             existing["size_bytes"] = max(existing["size_bytes"], row["size_bytes"])
+            _merge_last_modified(existing, row)
             existing["cache_path"] = existing.get("cache_path") or row.get("cache_path")
             if (
                 existing.get("partial")
@@ -508,6 +567,7 @@ def _scan_hf_dataset_caches() -> list[dict]:
             seen_lower[key] = row
             continue
         existing["size_bytes"] = max(existing["size_bytes"], row["size_bytes"])
+        _merge_last_modified(existing, row)
         # Preserve the raw path for scoped deletion and expose the processed Arrow path separately.
         if row.get("processed_cache"):
             existing["processed_cache"] = True
@@ -532,6 +592,7 @@ def _scan_hf_dataset_caches() -> list[dict]:
             existing["size_bytes"] = int(existing.get("size_bytes") or 0) + int(
                 row.get("size_bytes") or 0
             )
+            _merge_last_modified(existing, row)
             existing["processed_cache"] = True
             existing["app_processed_cache"] = True
     logger.info(
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 1d04c8f0b..e0774770f 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -434,8 +434,11 @@ export interface CachedGgufRepo {
   load_id?: string | null;
   size_bytes: number;
   cache_path: string;
-  /** Epoch seconds of the newest downloaded quant; sorts Downloaded
-   * newest-first. Optional for older-backend compatibility. */
+  /** Newest downloaded quant, sorting Downloaded newest-first. Epoch SECONDS
+   * off the wire from `listCachedGguf`, but epoch MILLISECONDS when the picker
+   * inventory builds this from a `CachedInventoryRow` -- `buildCachedInventoryRow`
+   * normalizes there. Compare these only against each other, never against a
+   * `Date.now()` clock. Optional for older-backend compatibility. */
   last_modified?: number;
   /** True when the repo ships an mmproj adapter (image inputs). Optional for
    * older-backend compatibility. */
@@ -575,8 +578,12 @@ export interface CachedModelRepo {
   /** Weights format; "adapter" is a LoRA with no base weights of its own.
    * Optional for older-backend compatibility. */
   model_format?: string | null;
-  /** Epoch seconds of the newest downloaded weight file; sorts Downloaded
-   * newest-first. Optional for older-backend compatibility. */
+  /** Newest downloaded weight file, sorting Downloaded newest-first. Epoch
+   * SECONDS off the wire from `listCachedModels`, but epoch MILLISECONDS when
+   * the picker inventory builds this from a `CachedInventoryRow` --
+   * `buildCachedInventoryRow` normalizes there. Compare these only against each
+   * other, never against a `Date.now()` clock. Optional for older-backend
+   * compatibility. */
   last_modified?: number;
   /** HF pipeline task: "text-to-image" for a cached diffusers pipeline repo (model_index.json present), so the chat picker can hide it. Absent = chat. */
   task?: string | null;
diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-types.ts b/studio/frontend/src/features/hub/download-manager/download-manager-types.ts
index a549f4faa..3e78c8822 100644
--- a/studio/frontend/src/features/hub/download-manager/download-manager-types.ts
+++ b/studio/frontend/src/features/hub/download-manager/download-manager-types.ts
@@ -33,6 +33,7 @@ export interface ManagedDownload {
   /** Seconds remaining, from the same estimator as {@link bytesPerSec}; 0 hides it. */
   etaSeconds: number;
   error: string | null;
+  /** Epoch milliseconds, from Date.now() at every write site. */
   startedAt: number;
   serverGeneration?: number;
   /** Files a scoped job is fetching, when known. Every file set of one repo rides the same scope slot (see `scopedVariant`), so this separates "my transfer is already running" from "a different quant of this repo is running": adopting the latter would report ready for files nobody fetched. Unknown stays adoptable only for an UNSCOPED job. */
diff --git a/studio/frontend/src/features/hub/inventory/api.ts b/studio/frontend/src/features/hub/inventory/api.ts
index 132bd193b..364ed7280 100644
--- a/studio/frontend/src/features/hub/inventory/api.ts
+++ b/studio/frontend/src/features/hub/inventory/api.ts
@@ -49,6 +49,8 @@ export interface CachedGgufRepo {
   capabilities?: BackendModelCapabilities | null;
   size_bytes: number;
   cache_path?: string;
+  /** Raw backend value: epoch SECONDS. buildCachedInventoryRow normalizes it to
+   * milliseconds; nothing else should read it without doing the same. */
   last_modified?: number | null;
   partial?: boolean;
   partial_transport?: string | null;
@@ -70,6 +72,8 @@ export interface CachedModelRepo {
   capabilities?: BackendModelCapabilities | null;
   size_bytes: number;
   cache_path?: string;
+  /** Raw backend value: epoch SECONDS. buildCachedInventoryRow normalizes it to
+   * milliseconds; nothing else should read it without doing the same. */
   last_modified?: number | null;
   partial?: boolean;
   partial_transport?: string | null;
@@ -123,6 +127,9 @@ export interface LocalModelListResponse {
 export interface CachedDatasetRepo {
   repo_id: string;
   size_bytes: number;
+  /** Raw backend value: epoch SECONDS. Absent when no cache path had a readable
+   * mtime, which the Recent sort reads as unknown rather than as the epoch. */
+  last_modified?: number | null;
   cache_path?: string;
   load_cache_path?: string;
   partial?: boolean;
diff --git a/studio/frontend/src/features/hub/inventory/inventory-hints.ts b/studio/frontend/src/features/hub/inventory/inventory-hints.ts
index 5e202e315..74a8f290f 100644
--- a/studio/frontend/src/features/hub/inventory/inventory-hints.ts
+++ b/studio/frontend/src/features/hub/inventory/inventory-hints.ts
@@ -13,6 +13,10 @@ export type InventoryHintRow = {
   size_bytes: number;
   partial?: boolean;
   optimistic?: boolean;
+  /** Raw backend value: epoch SECONDS for a server row, but epoch MILLISECONDS
+   * for the optimistic row below, which carries the hint's own clock.
+   * buildCachedInventoryRow normalizes either. */
+  last_modified?: number | null;
 };
 
 export type InventoryHintReconciliation = {
@@ -43,6 +47,14 @@ function optimisticRow(hint: InventoryHint): InventoryHintRow {
     size_bytes: hint.bytes ?? 0,
     partial: false,
     optimistic: true,
+    // Carry the hint's own clock. A finished download stops being surfaced as a
+    // live row, so this synthetic one is all the Recent sort has to go on until
+    // a backend scan lands, and an undated row sorts below every dated one --
+    // dropping the model you just downloaded to the bottom of the list for a
+    // failed refresh or the whole hint TTL.
+    ...(hint.createdAt && hint.createdAt > 0
+      ? { last_modified: hint.createdAt }
+      : {}),
   };
 }
 

Alongside it I have five test suites (studio/frontend/tests/pr9642-*.test.ts, tests/helpers/pr9642-sort-algebra.ts, and studio/backend/hub/tests/test_dataset_cache_timestamps.py) covering everything in the table above, including the lifecycle regression that catches #1. Happy to post those too, or open a PR against this branch if you enable maintainer edits.

Unrelated, but noticed while doing this and worth separate issues: studio/backend/hub/tests/ (210 tests) does not appear to be collected by any workflow, and dataset-panel-helpers.ts:28-33 hardcodes new Date(timestamp * 1000), which would render year ~56000 if an inventory value ever reached it.

A completed download stops being surfaced as a live row, and the optimistic
row that replaces it carried no timestamp, so the model that just finished
sorted below every dated row until a backend scan landed. Carry the inventory
hint's own creation time through optimisticRow.

Cached datasets carried no timestamp at all, so selecting Recent on the
datasets tab put every cached Hub dataset after every local one. Emit
last_modified from the dataset cache scanners, in the same POSIX seconds the
cached model scan already uses.

Also correct the last_modified unit docs: the picker inventory path now
forwards milliseconds while the raw endpoints still return seconds.
@danielhanchen

Copy link
Copy Markdown
Member

Opened Imagineer99#73 against this branch with the two fixes and their tests, since I cannot push here directly. Merging it lands the commits inside this PR and keeps your authorship on the original work.

It covers the completed-download drop and gives cached datasets a last_modified, plus corrects the unit docs. Details and the before/after tables are on that PR.

Separately, CI here shows Repo tests (CPU) failing, but that run is from the 24th, its logs have expired and it can no longer be re-run. I replicated this PR onto a staging repo against fresh main to get a clean read, including ubuntu, macos and windows plus browser tests. Will report what comes back.

Follow-ups to the follow-up, all found by simulating the merged tree rather
than reading it. Three real defects and two documentation gaps.

A non-finite mtime could take out the whole cached-datasets endpoint.
_safe_mtime guarded on `mtime > 0`, and inf passes that test. Starlette
encodes responses with allow_nan = False, so one inf reaching a row raises
ValueError inside the encoder and /api/hub/datasets/cached returns 500 rather
than one bad date. The value is not a stat() result we control: it is whatever
huggingface_hub put on the repo object. _usable_mtime now requires isfinite,
and every entry point routes through it. The cached-model scan has the same
hole in _blob_mtime today, on main, independent of this branch; that one is
reported separately rather than widened into this diff.

Deduplication discarded the newer of two timestamps. Which of two rows
describing one dataset survives is decided on completeness then size, neither
of which has anything to do with recency, so a bigger but older copy legitimately
won and took the newer copy's date with it. The dataset sank in Recent, which is
the exact bug this branch exists to fix. The cached-model scan already keeps the
max across duplicate roots; _adopt_newer_last_modified is the dataset twin, wired
into all three replacement paths.

The new backend test was in a directory no workflow collects. studio-backend-ci
runs pytest tests/ from studio/backend, and hub/tests is a sibling of that path,
so the guard would never have run. Moved to studio/backend/tests/ with a note
saying why it sits away from its subject. The wider hub/tests gap, 629 tests
that no workflow collects, is worth its own fix.

normalizeTimestamp now states its supported domain. The 1e10 pivot is a
heuristic, not a converter: it is idempotent only at or above the pivot, and it
reads epoch seconds from November 2286 onward as milliseconds. Real mtimes sit
far inside those bounds, but the next person deserves to be told where the edges
are instead of inferring that the helper is general.

The unit seam is now pinned by a test. After the recency fix, last_modified is
epoch seconds off listCachedGguf and epoch milliseconds when the picker builds
the same shape from an inventory row. Nothing renders wrongly today because every
consumer subtracts like for like or stringifies. pr9642-unit-boundary-guard
fails when a new reader appears without declaring its unit, when a caller of
formatUpdatedDate appears, or when a scale conversion shows up outside
normalizeTimestamp.

pr9642-dedup-and-stale records two cases the lifecycle suite does not reach,
both about re-downloading something already held complete. Dedup keeps the
complete row over the live one, and a complete server row keeps its own
timestamp over the completion hint. Both are right, both mean Recent lags until
the next scan, and neither is a regression since Recent had no date term at all
before this branch. Pinned so they are a decision rather than an accident.
Opening comment-reduction pass over the 256 comment lines this branch adds.
Scoped to those, not to every comment in a touched file: rewriting pre-existing
prose in chat-api.ts would balloon the diff for no reader's benefit.

Kept every 'why' that is not recoverable from the code, cut the restatement
around it. The normalizeTimestamp and unit-seam blocks stay longest on purpose,
since the supported date domain and the two-unit hazard are the parts a reader
cannot infer.

AST-gated comment-only, 12 of 12 files, with docstring edits allowed: the two
Python docstrings touched belong to internal helpers, not to anything FastAPI or
argparse surfaces.
@danielhanchen

Copy link
Copy Markdown
Member

Ran the full verification on the combined change and pushed the results into #73. Summary first, then what it cannot tell you.

The fix works, shown on the real component

I rendered the actual DownloadedList in a real browser out of three worktrees, driving one identical fixture through each: the merge base 0998656, this branch f1f5190, and the follow-up with my fixes. The recency term lives inline inside the component's useMemo, so a test that re-implements pinRank || recent || index would only prove the re-implementation works.

scenario base 0998656 this PR + #73 + fixes
#9617 repro bert, gemma, Qwen, llama-3, mistral Qwen, llama-3, gemma, bert, mistral same fixed
ties, unknown, already-ms tie-a, tie-b, undated, already-ms, local-tie already-ms, tie-a, tie-b, local-tie, undated same fixed
sort = name identical identical identical no collateral
sort = size identical identical identical no collateral
search active identical identical identical no collateral
old backend, no timestamps identical identical identical byte for byte unchanged
pinned bert, Qwen, gemma, llama-3, mistral bert, Qwen, llama-3, gemma, mistral same pins held, tail re-sorted

The base row reproduces the report exactly. Pinned rows keep their manual order because makePinRank gives each pinned id a distinct rank, so they never tie and the new comparator never reaches them.

Cross-browser and cross-OS

Nine cells, chromium / firefox / webkit against UTC, America/Los_Angeles and Asia/Kolkata: byte-identical order, zero page errors. The comparator algebra runs inside each engine too, not just under node: reflexivity, totality, no NaN, anti-symmetry, transitivity over every ordered triple, and all 720 permutations of a six element list matching a stable insertion-sort oracle of that same permutation. ES2019 guarantees a stable sort, but only for a well-formed comparator; given anything less, V8, JSC and SpiderMonkey may each return a different order, so the algebra is what makes this engine-independent and the three browsers only confirm it.

For the OS axis I replicated onto a staging repo and ran ubuntu-latest, macos-15 and windows-latest, with a base control on fresh main carrying nothing from either PR, because a head-only run cannot attribute a failure:

job base control head
Frontend (ubuntu / macos / windows) success, success, success
Backend dataset timestamps (ubuntu / macos / windows) success, success, success
Cached-model control (ubuntu / macos) success, success success, success
Cached-model control (windows) 1 failed, 268 passed 1 failed, 268 passed

Identical on both sides, so that one is pre-existing on main and not attributable here. It is test_state_scan_survives_a_state_filename_with_an_undecodable_byte, which builds a path containing a raw 0xff byte and hits UnicodeDecodeError in ntpath.join; a POSIX-only construction. It is invisible today because nothing collects it, which is the next point.

Three defects found by simulating rather than reading

All fixed on unslothai:pr-9642-followups and folded into #73. Detail in the two threads above.

  1. A non-finite mtime could 500 /api/hub/datasets/cached.
  2. Deduplication discarded the newer of two timestamps, re-introducing the exact bug this PR fixes.
  3. The new backend test sat in studio/backend/hub/tests/, which no workflow collects — studio-backend-ci.yml runs pytest tests/ from studio/backend, and hub/tests is a sibling of that path. A guard that never runs is not a guard, so it moved.

Nothing else breaks

  • Only two reads of lastModified exist in the frontend, plus the two picker forwarders. Every consumer subtracts like for like or stringifies, and no single list mixes the two origins.
  • No inventory timestamp is ever persisted. I checked the actual serialized storage, not source lines. The one persisted timestamp that now meets an inventory one, unsloth.studio.downloads's startedAt, is Date.now() milliseconds before and after, so an install upgraded from a seconds-era build has nothing to compare wrongly.
  • Cached rows render no date anywhere in the UI, so the seconds to milliseconds change has no display surface at all.
  • soleQuantFingerprint shifts scale once, but it is an in-memory map that starts empty each mount and records on first sight, so no spurious invalidation after upgrade.
  • sortCachedRepos is scale-invariant within a homogeneous list, and loadedAt is compared separately, never subtracted from last_modified.
  • The new stat() calls cost 11 microseconds per repo, 4.2% on a synthetic 500-repo cache, against a scan already dominated by a recursive _directory_size walk.
  • npm test 5811 pass on the merge with current main and 4884 on this branch's own base; typecheck, build and bundle budget clean; 48 backend simulation tests plus the branch's own suites pass.

What this run cannot tell you

  • Chromium stands in for Chrome and Edge, WebKit for Safari. Those are the engines, not the shipped browsers, and the browser matrix is not checked into CI, so a future engine change would not be caught automatically.
  • There is no GPU or hardware axis here. I scanned all 18 changed files for CUDA, ROCm, torch and device-selection tokens and found none, so an OS by accelerator matrix would be identical cells by construction.
  • normalizeTimestamp's 1e10 pivot is a heuristic, not a converter. It is idempotent only at or above the pivot, and reads epoch seconds from November 2286 onward as milliseconds. Real mtimes sit far inside those bounds. Documented in the helper rather than left to be inferred.

Two things blocking the merge, neither about the code

This branch conflicts with main, which is now 161 commits ahead of it. Exactly one conflict, and both sides are keeps: main added audioType?: string | null; to LocalInventoryRow and this PR added the /** Last changed time as epoch milliseconds. */ doc comment above updatedAt. Resolution is to keep both lines, in that order.

maintainerCanModify is false, so I cannot push the rebase or the fixes here. If you tick "Allow edits by maintainers" I will land both directly and re-run the matrix. Otherwise merging #73 brings the follow-ups in with your authorship intact on the original work, and the rebase is still yours to do.

The Repo tests (CPU) red above is from the 24th with expired, non-re-runnable logs; the staging matrix is what replaces it.

@mahiatlinux
mahiatlinux self-requested a review August 28, 2026 10:35
@mahiatlinux mahiatlinux changed the title Fix Model Hub Recent sorting for on-device models fix model hub recent sorting for on-device models Aug 28, 2026
@mahiatlinux

Copy link
Copy Markdown
Contributor

Verified #9617 against the current code and reproduced the failure. The prior recent branch only applied pin rank and source index, so changing the selector to Recent did not compare dates. The PR's comparator is the right layer: it now applies one timestamp comparison after pin rank and preserves source order for ties and unknown values (sort call, comparator).

Concrete issues found and fixed:

  1. A completed download lost its live row before the cache rescan. The replacement inventory hint had no timestamp, so the model moved from first to last for up to the five-minute hint TTL. The optimistic row now carries hint.createdAt (inventory-hints.ts). The regression test follows a completed download through reconciliation and asserts it stays first (hub-inventory-recent-sort.test.ts).

  2. Cached datasets had no usable date while local recipe and upload rows did. Recent therefore placed every cached dataset after every dated local row. The backend DTO and every raw, processed, and app-processed dataset scanner now emit epoch seconds when a readable mtime exists. Invalid, missing, non-finite, and non-positive values remain unknown instead of becoming 1970 (cache_inventory.py).

  3. The first dataset fix still lost recency across duplicate cache roots. Row selection prefers completeness and size, so a smaller but newer copy could lose and its newer timestamp disappeared. All HF, fallback, and processed-cache dedup paths now keep the maximum timestamp independently of the winning payload row (merge helpers, fallback scan, HF scan). Focused regressions cover smaller/newer duplicates in all three scanner families (tests).

  4. Fallback raw and processed scanners dated their top-level directories. Adding or replacing a blob or nested Arrow artifact does not necessarily update those ancestors, so a newly changed dataset could retain an old date. The existing size walks now also collect the newest payload-file mtime at no extra traversal cost (raw stats, processed stats). Tests pin newer blob and nested Arrow mtimes against older directory mtimes (raw test, processed test).

  5. Inventory view models correctly normalize dates to epoch milliseconds, but the chat picker reconstructed backend-shaped DTOs from those normalized rows. Passing milliseconds through a field documented and consumed as epoch seconds weakened the boundary and risked a second normalization in downstream code. The picker now converts cached and local timestamps back to seconds at that DTO boundary (use-chat-picker-inventory.ts, conversion helper).

  6. The PR conflicted with current main in the inventory row type. I merged current main and kept both the new audio metadata and timestamp contract. I also replaced over 1,000 lines of PR-specific source-pattern and comparator-reimplementation tests with four focused behavior cases.

Verification:

ESLint still reports existing violations in use-hub-inventory.ts and restricted imports already present on main; the lines changed here did not introduce them.

@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 19416fd259

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@mahiatlinux

Copy link
Copy Markdown
Contributor

Fresh convergence review found and fixed three related redownload cases in cf69c3c0c:

  1. A later completion for the same repo inherited the first hint's timestamp and five-minute expiry. Each job now captures one immutable completion time, includes it in the published hint signature, and replaces a pending hint when that completion generation is newer (download-manager-state.ts, inventory-hint-store.ts).

  2. A deleted repo remained in historical observed-key state. A legitimate redownload completed before the next scan, was mistaken for a stale old hint, and disappeared. Starting a new non-external download now clears that repo's observed tombstone before the completion handoff (download-manager-state.ts, inventory-hint-store.ts).

  3. GGUF server rows aggregate every cached quant. An existing 500-byte repo row could therefore satisfy a newly completed 200-byte variant hint by size alone, discard its completion timestamp, and drop the repo in Recent until a successful rescan. Reconciliation now requires post-completion timestamp evidence, with two-second filesystem granularity tolerance, and merges the completion timestamp into stale same-repo rows until that evidence arrives (inventory-hints.ts, satisfaction check).

Focused coverage now has seven frontend cases, including repeated completion TTL, stale aggregate rows, and delete-then-redownload history (tests). Local TypeScript typecheck, ESLint, production build, 13 backend timestamp tests, and Ruff all pass.

@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: cf69c3c0cf

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@mahiatlinux

Copy link
Copy Markdown
Contributor

Post-push convergence found and fixed four more correctness issues in 8478815:

  1. Valid inventory mtimes can precede terminal UI completion while backend metadata recovery finishes. InventoryHint now carries job startedAt for freshness, while createdAt remains the displayed recent time and five-minute expiry. Evidence: studio/frontend/src/features/hub/download-manager/download-manager-state.ts:214-249 and studio/frontend/src/features/hub/inventory/inventory-hints.ts:131-159,197-209.

  2. Download totals and inventory row sizes are different domains. Model downloads count the whole snapshot and GGUF downloads count managed companions; inventory rows count runnable weights. Timestamped hints now settle on a complete post-start artifact timestamp without requiring row bytes to equal download bytes. A row one second before the job remains stale, with no causal tolerance. Evidence and regression: studio/frontend/src/features/hub/inventory/inventory-hints.ts:197-209 and studio/frontend/tests/hub-inventory-recent-sort.test.ts:170-211.

  3. A stale row could repopulate historical observation state while a replacement download was active. A later empty rescan then suppressed the legitimate completion hint. Active download keys and pending completion hints are now excluded from observation history until a fresh row consumes the hint. Evidence and regression: studio/frontend/src/features/hub/inventory/inventory-hint-store.ts:164-188,217-250; studio/frontend/src/features/hub/inventory/use-hub-inventory.ts:138-160,395-450; studio/frontend/tests/hub-inventory-recent-sort.test.ts:213-304.

  4. Companion-only vision updates did not advance GGUF recent time because the backend dated rows only from primary GGUF blobs. Row timestamps now include managed mmproj and MTP artifacts while classification and size still require primary GGUF weights. Evidence and regression: studio/backend/hub/services/models/cache_inventory.py:136-181 and studio/backend/hub/tests/test_model_services.py:85-107.

Focused local verification:

  • frontend recent-sort tests: 7 passed
  • frontend typecheck: passed
  • frontend production build: passed
  • targeted frontend ESLint: passed
  • backend timestamp tests: 14 passed
  • targeted Ruff: passed

@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8478815f89

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@mahiatlinux

Copy link
Copy Markdown
Contributor

Convergence follow-up ce3c09d fixes the remaining lifecycle and freshness gaps:

  • Completion now writes its hint into the inventory store synchronously. The six-second completed-job removal no longer loses a download when no Hub or picker consumer is mounted.
  • Running, cancelling, and complete jobs stay out of historical observation until the completion hint is reconciled. This closes the render-to-passive-effect race that could suppress a redownload.
  • Successful full model and dataset deletion now discards pending hints and suppresses the completed-job source, so an optimistic row cannot reappear for the rest of the five-minute TTL. Variant-only deletion does not clear the repo-level hint.
  • Each successful inventory response records when its scan began. A scan started after terminal completion is a causal handoff even when an adopted job began after its blobs were written or the filesystem rounded mtime down. A request started before completion cannot consume the hint.

Evidence: studio/frontend/src/features/hub/download-manager/download-manager-state.ts, studio/frontend/src/features/hub/inventory/inventory-hint-store.ts, studio/frontend/src/features/hub/inventory/inventory-hints.ts, studio/frontend/src/features/hub/inventory/use-device-inventory.ts, studio/frontend/src/features/hub/inventory/use-hub-inventory.ts, studio/frontend/src/features/hub/inventory/api.ts, and studio/frontend/tests/hub-inventory-recent-sort.test.ts.

Focused local verification: 7 frontend tests, typecheck, targeted ESLint, and production build all pass.

@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ce3c09d916

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@mahiatlinux

Copy link
Copy Markdown
Contributor

Final convergence fixes are pushed through 9028c27.

Concrete findings and fixes:

  1. The backend published a complete job before invalidating its cached Hugging Face scan. A frontend refresh could therefore start after completion and still receive the pre-download TTL result. finalize_worker_exit now invalidates inventory before registry.set_job(..., "complete"), with an ordering regression in hub/tests/test_download_lifecycle.py.

  2. _shared_cached_inventory_scan deliberately serves its last confirmed rows after eight invalidation races. The frontend previously treated any successful request started after completion as fresh, so an explicitly stale response could consume the optimistic hint and restore the old Recent timestamp. Cached model and GGUF responses now expose scan_confirmed; use-device-inventory.ts records a causal refresh marker only for confirmed-current scans. The backend retry tests and frontend reconciliation test cover both confirmed and fallback responses.

  3. Full deletion suppression was released when the first of several lingering completed variant jobs expired. The remaining job then republished the deleted repo. Job removal no longer releases deletion suppression, and successful full deletion removes every completed contribution for the repo.

  4. Successful variant deletion skipped GGUF hint cleanup. Deleting the only newly completed quant could recreate an optimistic row for the five-minute TTL. deleteCachedModel now calls variant-aware cleanup, removes the deleted quant's completed job, and leaves an already-running peer eligible to publish when it completes. The regression covers complete Q4, active Q8, Q4 deletion, empty hint state, then Q8 completion.

Focused verification on 9028c27:

  • frontend recent-sort and lifecycle tests: 9 passed
  • frontend typecheck: passed
  • frontend production build: passed
  • targeted frontend ESLint: passed
  • backend cache, scan, lifecycle, GGUF companion, and dataset timestamp tests: 20 passed
  • targeted Ruff: passed

Final cross-platform focused CI is running on Linux, Windows, and macOS: https://github.com/mahiatlinux/unsloth/actions/runs/33167576075

@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 9028c27825

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@mahiatlinux

Copy link
Copy Markdown
Contributor

Fixed the Windows frontend unit-test failure from job 98836974034. Current upstream main renamed the sidebar constant from scrollRowPadding to unrailedRowPadding, but the source assertion still expected the old name. Commit 16a685cfc updates that one assertion. The focused file passes 6/6 locally.

@mahiatlinux mahiatlinux left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the implementation, fixes, regression coverage, and focused cross-platform CI.

@mahiatlinux

Copy link
Copy Markdown
Contributor

All reviewed and fixed, LGTM. CI results

@mahiatlinux
mahiatlinux merged commit ebac1d4 into unslothai:main Aug 28, 2026
36 of 40 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Model Hub: On Device: List by date non functional

3 participants