Skip to content

feat(shared): add safe Hugging Face cache primitives - #1385

Merged
shanselman merged 1 commit into
mainfrom
shanselman-hf-cache-primitives
Sep 10, 2026
Merged

shanselman merged 1 commit into
mainfrom
shanselman-hf-cache-primitives

Conversation

@shanselman

Copy link
Copy Markdown
Collaborator

Related: #1288

What Problem This Solves

The Local AI replacement train needs a safe, reusable way to locate and read standard Hugging Face hub-cache entries before setup, migration, manifests, or runtime behavior can move to that cache.

Why This Change Was Made

This is layer 1 replacing the shared portion of #1288 (feat(local-ai): store downloaded models in the standard HF hub cache). It lands only independently valuable OpenClaw.Shared path and verified-read primitives. Later layers will own model acquisition, cross-volume materialization, legacy migration, manifest compatibility, setup reconciliation, and runtime routing.

The API deliberately does not expose a validate-then-mutate path contract. A returned string cannot authorize a race-free later mutation. Instead, verified reads return the same rewound file handle that was safely opened and hashed, so a later layer can copy from that handle across volumes without reopening the path.

User Impact

No product behavior changes in this layer. Developers gain a tested foundation for standard Hugging Face cache interoperability without committing setup or migration code to a same-volume hard-link strategy.

Evidence

  • Standard cache-root precedence covers HF_HUB_CACHE, HUGGINGFACE_HUB_CACHE, HF_HOME, XDG_CACHE_HOME, and the user-profile default.
  • Focused tests exercise nested relative paths, repository/revision validation, Windows reserved device aliases, component limits, real snapshot symlinks, sibling/outside-target rejection, and pinned size/SHA-256 verification.
  • Live cross-volume proof copied 27 bytes from a verified handle on C:\ to D:\; the destination hash matched the pin.
  • Autoreview accepted and drove fixes for superscript COM/LPT aliases and component/.partial length limits.
  • Rubber-duck review drove Windows environment expansion and removal of the unsafe validate-then-mutate API.
  • Final review suggestions for CONIN$/CONOUT$ and CON .gguf were rejected after Microsoft documentation review and live Windows file-creation proof showed they are valid ordinary path components.

Change Type

  • Bug fix
  • Feature
  • Refactor
  • Docs or instructions
  • Tests or validation
  • Security hardening
  • Chore or infrastructure

Scope

  • Tray or WinUI UX
  • Windows node capability
  • Local MCP or winnode
  • Gateway, connection, or pairing
  • Setup or onboarding
  • Permissions, privacy, or security
  • Tests, CI, or docs

Required proof pools

  • none: this Shared-only path and verified-read layer requires no capacity-dependent host class. Focused tests create and validate real Windows symbolic links, and the live proof copies from the verified handle across local volumes.

Validation

  • .\build.ps1: passed, all 5 projects built.
  • dotnet test .\tests\OpenClaw.Shared.Tests\OpenClaw.Shared.Tests.csproj --no-restore --filter "FullyQualifiedName~HuggingFaceHubCacheTests|FullyQualifiedName~WindowsPathSafetyTests": passed, 47/47.
  • dotnet test .\tests\OpenClaw.Shared.Tests\OpenClaw.Shared.Tests.csproj --no-restore: passed, 3,991 passed and 32 skipped.
  • dotnet test .\tests\OpenClaw.Tray.Tests\OpenClaw.Tray.Tests.csproj --no-restore: passed, 2,865/2,865.
  • Autoreview command: python .agents\skills\autoreview\scripts\autoreview --mode local --prompt <layer-1 scope>.
  • Rubber-duck review: completed twice, with accepted findings fixed and final unsupported device-name suggestion rejected using Microsoft documentation plus live Windows behavior.

Real Behavior Proof

  • Environment tested: Windows 11 x64, .NET SDK 10.0.401.
  • PR head or commit tested: 6cd0f147.
  • Exact steps or command run: loaded the built OpenClaw.Shared.dll, created a pinned snapshot under a temporary C:\ cache, called TryOpenVerifiedCacheFileAsync, then copied from the returned rewound stream to a temporary D:\ destination.
  • Evidence after fix: SourceVolume=C:\, DestinationVolume=D:\, Bytes=27, HashMatches=True, CopiedFromVerifiedHandle=True.
  • Observed result: the same safely opened and SHA-256-verified handle supported a cross-volume copy without reopening or trusting the pathname.
  • Screenshot or artifact links verified? N/A
  • Not verified or blocked: setup, migration, manifest, runtime, and tray behavior are intentionally deferred to later replacement layers.

Security Impact

  • New permissions or capabilities? No
  • Secrets or tokens handling changed? No
  • New or changed network calls? No
  • Command or tool execution surface changed? No
  • Data access scope changed? No
  • If any answer is Yes, explain the risk and mitigation: N/A

Compatibility and Migration

  • Backward compatible? Yes
  • Config or environment changes? No
  • Migration needed? No
  • If yes, list the exact upgrade steps: N/A

Review Conversations

  • I replied to or resolved every bot review conversation addressed by this PR.
  • I left unresolved only conversations that still need maintainer judgment.

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: ba1185b3-ebb0-40d0-a225-5391956934b6
@shanselman shanselman added the status: 🚢 actively landing A maintainer or agent is actively driving this item through implementation, validation, or merge. label Sep 10, 2026
@clawsweeper

clawsweeper Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@clawsweeper clawsweeper Bot added P2 Normal priority bug or improvement with limited blast radius. merge-risk: 🚨 security-boundary 🚨 Merging this PR could weaken sandboxing, authorization, credentials, or sensitive data. proof: sufficient Contributor real behavior proof is sufficient. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 10, 2026
@clawsweeper

clawsweeper Bot commented Sep 10, 2026

Copy link
Copy Markdown

Codex review: blocked before merge. Reviewed September 9, 2026, 9:10 PM ET / September 10, 2026, 01:10 UTC.

ClawSweeper review

What this changes

Adds shared helpers for locating Hugging Face model-cache files, checking Windows paths, and returning an open stream after size and SHA-256 verification.

Merge readiness

⛔ Blocked before merge - 5 items remain

This is a useful, bounded foundation that is absent from main, but two introduced validation defects need correction before merge. The supplied Windows copy proof supports the intended handle-based design.

Priority: P2
Reviewed head: 6cd0f147e110c01f58d662f2af7f63d2700d7794

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The scoped implementation and real Windows proof are useful, but two concrete validation defects prevent a merge-ready rating.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied current-head Windows output exercises TryOpenVerifiedCacheFileAsync from the built Shared assembly and records a successful 27-byte C:-to-D: copy from its returned stream with a matching digest. This proves the scoped cross-volume behavior; it does not resolve the independently identified replacement race.
Patch quality 🦐 gold shrimp (3/6) Security review found an item that needs attention.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The supplied current-head Windows output exercises TryOpenVerifiedCacheFileAsync from the built Shared assembly and records a successful 27-byte C:-to-D: copy from its returned stream with a matching digest. This proves the scoped cross-volume behavior; it does not resolve the independently identified replacement race.
Evidence reviewed 8 items Pinned scope and current-main necessity: The verified base-to-head change adds four files, with 825 production lines and 446 test lines. Main's catalog tree has no HuggingFaceHubCache helper, and the existing installer still uses LocalAiPathPolicy.TryGetModelPaths. The helper is also absent at the supplied latest release tag.
Path-policy race: The target attributes are read before FileStream opens the path. Only those earlier attributes determine whether same-repository blob validation runs; the unconditional handle check establishes containment within the whole hub root only.
Upstream interoperability contract: The PR explicitly promises standard Hugging Face cache interoperability. Its repository validation limits the entire owner/repository string to 96 characters, and cache-directory validation repeats that limit. This establishes the dependency signal for checking the upstream repository-name contract.
Findings 2 actionable findings [P2] Validate the opened destination without trusting pre-open attributes
[P2] Apply the 96-character limit to the repository name
Security Needs attention Stale attributes bypass repository confinement: A process able to replace a cache entry before it opens can redirect the reader elsewhere inside the hub root without triggering same-repository blob validation. SHA-256 verification still limits which contents can be returned.

How this fits together

Local AI currently installs models into app-owned storage. These new shared helpers prepare future cache reuse by accepting cache locations and artifact pins, then returning verified file streams without changing installation or migration behavior.

flowchart TD
 A[Environment and cache location] --> B[Resolve cache root]
 C[Repository and artifact path] --> D[Validate cache entry]
 B --> D
 D --> E[Open and check resolved path]
 F[Pinned size and digest] --> G[Verify file contents]
 E --> G
 G --> H[Rewound stream or rejection]
Loading

Before merge

  • Validate the opened destination without trusting pre-open attributes (P2) - If another process replaces a regular snapshot file with a symlink after File.GetAttributes but before new FileStream, attributes still lacks ReparsePoint. A link into another repository under the same hub root passes the unconditional root check and skips TryValidateSnapshotLink. With matching pinned bytes, the public method returns that stream despite the documented same-repository restriction. Validate the opened destination against the allowed entry/blob locations independently of the earlier attributes, and cover this replacement interleaving.
  • Apply the 96-character limit to the repository name (P2) - Hugging Face's REPO_ID_REGEX permits a repository name of up to 96 characters after the optional namespace. This check instead caps owner/repository in total, so owner/ plus a 96-character ordinary name cannot produce snapshot/blob paths or reuse an existing cache entry. Apply the upstream name limit separately and update the matching total-length check in TryValidateRepositoryDirectoryName, retaining the Windows component-size guard.
  • Resolve security concern: Stale attributes bypass repository confinement - A process able to replace a cache entry before it opens can redirect the reader elsewhere inside the hub root without triggering same-repository blob validation. SHA-256 verification still limits which contents can be returned.
  • Resolve merge risk (P1) - Concurrent replacement of a cache entry can bypass the same-repository link restriction; pinned content verification remains enforced.
  • Complete next step (P2) - Fix both validation defects, add focused regression coverage, and rerun the repository-required build, shared tests, and tray tests.

Findings

  • [P2] Validate the opened destination without trusting pre-open attributes — src/OpenClaw.Shared/Inference/Catalog/HuggingFaceHubCache.cs:243-244
  • [P2] Apply the 96-character limit to the repository name — src/OpenClaw.Shared/Inference/Catalog/HuggingFaceHubCache.cs:525-528
  • [medium] Stale attributes bypass repository confinement — src/OpenClaw.Shared/Inference/Catalog/HuggingFaceHubCache.cs:243
Agent review details

Security

Needs attention: The cache reader has a pathname-race policy bypass; no dependency, credential, permission, or content-integrity bypass was found.

Review metrics

Metric Value Why it matters
Production and test growth production +825, tests +446 The added production surface is justified as a standalone cache foundation, with installation and migration explicitly deferred.

Merge-risk options

Maintainer options:

  1. Bind validation to the opened destination (recommended)
    Repair the stale-attribute bypass and add deterministic replacement coverage before exposing this helper to later cache consumers.

Technical review

Best possible solution:

Keep the verified-stream design, enforce destination policy independently of stale pathname attributes, and align repository-name limits with Hugging Face.

Do we have a high-confidence way to reproduce the issue?

Yes, source establishes both triggers: replace a regular entry with an in-root cross-repository symlink between stat and open, or supply owner/ followed by a 96-character repository name. Neither scenario was executed during this read-only review.

Is this the best way to solve the issue?

The verified-handle approach is appropriate, but the proposed implementation needs handle-bound path validation and the upstream repository-name length rule.

Full review comments:

  • [P2] Validate the opened destination without trusting pre-open attributes — src/OpenClaw.Shared/Inference/Catalog/HuggingFaceHubCache.cs:243-244
    If another process replaces a regular snapshot file with a symlink after File.GetAttributes but before new FileStream, attributes still lacks ReparsePoint. A link into another repository under the same hub root passes the unconditional root check and skips TryValidateSnapshotLink. With matching pinned bytes, the public method returns that stream despite the documented same-repository restriction. Validate the opened destination against the allowed entry/blob locations independently of the earlier attributes, and cover this replacement interleaving.
    Confidence: 0.96
  • [P2] Apply the 96-character limit to the repository name — src/OpenClaw.Shared/Inference/Catalog/HuggingFaceHubCache.cs:525-528
    Hugging Face's REPO_ID_REGEX permits a repository name of up to 96 characters after the optional namespace. This check instead caps owner/repository in total, so owner/ plus a 96-character ordinary name cannot produce snapshot/blob paths or reuse an existing cache entry. Apply the upstream name limit separately and update the matching total-length check in TryValidateRepositoryDirectoryName, retaining the Windows component-size guard.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.96

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 3edc9b1b5b6e.

Labels

Label changes:

  • add P2: The helpers have bounded correctness defects and are not yet wired into existing product workflows.
  • add merge-risk: 🚨 security-boundary: A concurrent pathname replacement can evade the new cache reader's declared per-repository restriction.
  • add proof: sufficient: Contributor real behavior proof is sufficient. The supplied current-head Windows output exercises TryOpenVerifiedCacheFileAsync from the built Shared assembly and records a successful 27-byte C:-to-D: copy from its returned stream with a matching digest. This proves the scoped cross-volume behavior; it does not resolve the independently identified replacement race.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (live_output): The supplied current-head Windows output exercises TryOpenVerifiedCacheFileAsync from the built Shared assembly and records a successful 27-byte C:-to-D: copy from its returned stream with a matching digest. This proves the scoped cross-volume behavior; it does not resolve the independently identified replacement race.

Label justifications:

  • P2: The helpers have bounded correctness defects and are not yet wired into existing product workflows.
  • merge-risk: 🚨 security-boundary: A concurrent pathname replacement can evade the new cache reader's declared per-repository restriction.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (live_output): The supplied current-head Windows output exercises TryOpenVerifiedCacheFileAsync from the built Shared assembly and records a successful 27-byte C:-to-D: copy from its returned stream with a matching digest. This proves the scoped cross-volume behavior; it does not resolve the independently identified replacement race.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied current-head Windows output exercises TryOpenVerifiedCacheFileAsync from the built Shared assembly and records a successful 27-byte C:-to-D: copy from its returned stream with a matching digest. This proves the scoped cross-volume behavior; it does not resolve the independently identified replacement race.

Evidence

Security concerns:

  • [medium] Stale attributes bypass repository confinement — src/OpenClaw.Shared/Inference/Catalog/HuggingFaceHubCache.cs:243
    A process able to replace a cache entry before it opens can redirect the reader elsewhere inside the hub root without triggering same-repository blob validation. SHA-256 verification still limits which contents can be returned.
    Confidence: 0.96

What I checked:

  • Pinned scope and current-main necessity: The verified base-to-head change adds four files, with 825 production lines and 446 test lines. Main's catalog tree has no HuggingFaceHubCache helper, and the existing installer still uses LocalAiPathPolicy.TryGetModelPaths. The helper is also absent at the supplied latest release tag. (src/OpenClaw.Shared/Inference/Catalog/HuggingFaceHubCache.cs:20, 6cd0f147e110)
  • Path-policy race: The target attributes are read before FileStream opens the path. Only those earlier attributes determine whether same-repository blob validation runs; the unconditional handle check establishes containment within the whole hub root only. (src/OpenClaw.Shared/Inference/Catalog/HuggingFaceHubCache.cs:243, 6cd0f147e110)
  • Upstream interoperability contract: The PR explicitly promises standard Hugging Face cache interoperability. Its repository validation limits the entire owner/repository string to 96 characters, and cache-directory validation repeats that limit. This establishes the dependency signal for checking the upstream repository-name contract. (src/OpenClaw.Shared/Inference/Catalog/HuggingFaceHubCache.cs:526, 6cd0f147e110)
  • Repository-name length contract: Upstream REPO_ID_REGEX applies the 1–96 character bound to repo_name after an optional namespace. Thus owner plus slash plus a 96-character ordinary repository name is valid upstream but rejected by this patch. (src/huggingface_hub/utils/_validators.py:33, f14866648507)
  • Current-head proof and reported validation: The complete supplied body, sourceRevision 439570759b3295c2499029d242872edc17ca069949f9df778e73b498de1934b6, identifies head 6cd0f14 and Windows 11/.NET 10.0.401. It records a production Shared.dll call returning a verified stream, a C:-to-D: copy of 27 bytes, HashMatches=True, and CopiedFromVerifiedHandle=True. It also reports the full build, 47 focused tests, 3,991 shared tests passed with 32 skipped, and 2,865 tray tests passed. This read-only review did not rerun builds or tests. (6cd0f147e110)
  • Related implementation remains broader and open: feat(local-ai): store downloaded models in the standard HF hub cache #1288 (feat(local-ai): store downloaded models in the standard HF hub cache) also changes installation, manifests, and migration. Its contributor repeatedly supplied proof and requested review. The downloaded screenshot was inspected and shows model verification during setup; it belongs to that broader PR, not this head. The current PR explicitly replaces only its shared foundation.

Likely related people:

  • Joel: Raw commit ccd64bb adds src/OpenClaw.Shared/Inference/Catalog/PinnedArtifact.cs:16 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: ccd64bbb7d68; files: src/OpenClaw.Shared/Inference/Catalog/PinnedArtifact.cs)
  • shanselman: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Repair the pre-open attribute race and add deterministic coverage for cross-repository redirection.
  • Accept valid namespaced repositories with 96-character names in both path construction and cache-entry validation.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@shanselman
shanselman merged commit 4064eb9 into main Sep 10, 2026
39 of 41 checks passed
@shanselman
shanselman deleted the shanselman-hf-cache-primitives branch September 10, 2026 01:27
@shanselman shanselman removed the status: 🚢 actively landing A maintainer or agent is actively driving this item through implementation, validation, or merge. label Sep 10, 2026
shanselman added a commit that referenced this pull request Sep 10, 2026
Layer 2 of #1288 after #1385: add explicit, handle-bound migration of verified legacy Local AI model weights into the standard Hugging Face cache while preserving the active legacy model path. Layer 3 owns downloads and active selection.`n`nCo-authored-by: Copilot App <[email protected]>`nCopilot-Session: e7ffdfcb-cd94-420d-9f35-b268846a60fc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 security-boundary 🚨 Merging this PR could weaken sandboxing, authorization, credentials, or sensitive data. P2 Normal priority bug or improvement with limited blast radius. proof: sufficient Contributor real behavior proof is sufficient. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant