Skip to content

fix(safetensors): harden shard-index resolution and canonical manifests - #74

Open
rmems wants to merge 1 commit into
mainfrom
cursor/harden-safetensors-shard-index-bda0
Open

rmems wants to merge 1 commit into
mainfrom
cursor/harden-safetensors-shard-index-bda0

Conversation

@rmems

@rmems rmems commented Sep 15, 2026

Copy link
Copy Markdown
Owner

User description

Fixes RM-1360.

Harden the feature-gated Safetensors shard-index path so a manifest is only returned when shard references stay inside the checkpoint root, every indexed tensor maps to exactly one existing shard, and repeated inspection is byte-identical.

Changes

  • Resolve weight_map shard paths relative to the checkpoint root; reject absolute paths and .. traversal that escapes the root; allow in-root nested/../file normalization.
  • Canonicalize existing paths so symlink escape is rejected on platforms that can follow links.
  • Fail closed on missing referenced shards with ParserError::MissingShard before a manifest is returned.
  • Reject duplicate/conflicting tensor ownership with ParserError::DuplicateTensorOwnership (tensor name + sorted shard list).
  • Keep unreferenced on-disk shards as reported metadata (index:unreferenced_shards), not a hard error.
  • Sort directory listings and tensor records so shuffled discovery order cannot change output.

Tests

  • Absolute path and parent-dir escape
  • In-root .. normalization
  • Unix symlink escape, with a documented lexical fallback on non-unix
  • Duplicate directory and index tensor ownership (typed diagnostics)
  • Missing referenced shard
  • Orphan/unreferenced shards (existing coverage retained)
  • Shuffled directory creation order and repeated JSON equality
  • Committed single-file and sharded fixtures remain compatible

Local evidence

cargo fmt --check
cargo clippy --all-targets --all-features -- -D warnings
cargo test --features safetensors
cargo test --all-features

All passed.

GitHub CI

All required checks on cb569b6 passed:

  • Build & Test
  • MSRV (1.97.1)
  • Build Docker Image (CPU-only)
  • Amazon Q Developer

https://github.com/rmems/engram-parser/actions/runs/34931643984

Linear Issue: RM-1360

Open in Web Open in Cursor 

Summary by cubic

Fixes RM-1360 by hardening the safetensors shard-index path so a manifest is only returned when shard references stay inside the checkpoint root, every indexed tensor maps to exactly one existing shard, and repeated inspection is byte-identical. Previously, missing referenced shards and duplicate tensor ownership could surface as generic load errors or invalid manifests.

Behavior

  • Resolves weight_map shard paths relative to the checkpoint root; in-root nested/../file paths normalize, while absolute paths and parent-dir escapes are rejected.
  • Canonicalizes existing shard paths so symlink escapes are rejected on platforms that can follow links; non-unix targets keep the lexical path guards.
  • Fails with ParserError::MissingShard when an indexed shard is absent and ParserError::DuplicateTensorOwnership when multiple shards declare the same tensor.
  • Keeps unreferenced on-disk shards in index:unreferenced_shards metadata instead of failing.
  • Sorts directory listings and tensor records so shuffled discovery order cannot change the emitted JSON.

Validation

  • Adds tests for absolute and .. escapes, in-root normalization, unix symlink escape, missing shards, duplicate ownership, shuffled creation order, and byte-stable fixture output.

Written for commit cb569b6. Summary will update on new commits.

Review in cubic


CodeAnt-AI Description

Harden Safetensors shard validation and produce deterministic manifests

What Changed

  • Rejects absolute, root-escaping, symlink-escaping, missing, or non-file shard references in checkpoint indexes
  • Rejects tensors that appear in multiple shards or in a shard different from the one assigned by the index, with specific diagnostics
  • Accepts normalized paths such as nested/../model.safetensors when they remain inside the checkpoint
  • Keeps unreferenced on-disk shards in manifest metadata instead of treating them as errors
  • Sorts discovered files and tensor records so repeated inspections produce identical output

Impact

✅ Safer checkpoint shard loading
✅ Clearer missing-shard and duplicate-tensor errors
✅ Stable manifest output across repeated inspections

💡 Usage Guide

Checking Your Pull Request

Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.

Talking to CodeAnt AI

Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

Preserve Org Learnings with CodeAnt

You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

Check Your Repository Health

To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.

Reject absolute and root-escaping shard paths, fail closed on missing
referenced shards, and report duplicate tensor ownership with typed
diagnostics. Keep unreferenced shards in reserved metadata and sort
directory/tensor records so repeated inspection is byte-identical.

RM-1360

Co-authored-by: Raul Cardenas Montoya <montoyaraul34@gmail.com>
@linear-code

linear-code Bot commented Sep 15, 2026

Copy link
Copy Markdown

RM-1360

@coderabbitai

coderabbitai Bot commented Sep 15, 2026

Copy link
Copy Markdown

Warning

Review limit reached

Next included review available in 59 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Advanced

Run ID: a9708017-a24c-4f25-9875-af4f22dce6ff

📥 Commits

Reviewing files that changed from the base of the PR and between 9bc66ff and cb569b6.

📒 Files selected for processing (8)
  • CHANGELOG.md
  • README.md
  • src/error.rs
  • src/safetensors/manifest.rs
  • src/safetensors/mod.rs
  • src/safetensors/paths.rs
  • src/safetensors/tests.rs
  • tests/safetensors_smoke.rs

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@rmems
rmems marked this pull request as ready for review September 15, 2026 05:10
@codeant-ai

codeant-ai Bot commented Sep 15, 2026

Copy link
Copy Markdown

🤖 CodeAnt AI — Review Status

Status Commit Started (UTC) Finished (UTC)
✅ Reviewed your PR cb569b6 Sep 15, 2026 · 05:10 05:13

@codeant-ai

codeant-ai Bot commented Sep 15, 2026

Copy link
Copy Markdown

Thanks for using CodeAnt! 🎉

We're free for open-source projects. if you're enjoying it, help us grow by sharing.

Share on X ·
Reddit ·
LinkedIn

@cursor

cursor Bot commented Sep 15, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_004e7115-23a7-4a4f-891a-dea86abcb991)

@amazon-q-developer amazon-q-developer 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.

This PR successfully hardens Safetensors shard-index resolution with comprehensive security improvements and deterministic manifest generation. The changes effectively address path traversal vulnerabilities through lexical and canonical validation, enforce tensor ownership integrity, and ensure deterministic behavior through sorted operations.

Security Enhancements Verified:

  • Path traversal protection correctly rejects absolute paths and parent-directory escapes via lexical analysis before file access
  • Symlink escape prevention through canonicalization on platforms that support it, with documented lexical fallback
  • Early failure on missing referenced shards with typed error diagnostics
  • Duplicate tensor ownership detection prevents conflicting shard claims
  • Deterministic directory listing and tensor record ordering eliminates non-deterministic manifest generation

Test Coverage:
The PR includes comprehensive test coverage for all security-critical paths including absolute path rejection, parent directory escape, symlink escape (platform-specific), duplicate ownership detection, missing shard handling, and deterministic ordering. The implementation is production-ready.


You can now have the agent implement changes and create commits directly on your pull request's source branch. Simply comment with /q followed by your request in natural language to ask the agent to make changes.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 15, 2026

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review Completed 2026-09-15T05:14:05.627620Z cb569b6 Draft marked ready
🔒 Security Review Completed 2026-09-15T05:19:30.011798Z cb569b6 Draft marked ready
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@codeant-ai codeant-ai Bot added the size:L This PR changes 100-499 lines, ignoring generated files label Sep 15, 2026
Comment thread src/error.rs
Comment on lines +55 to +70
/// A tensor name is claimed by more than one Safetensors shard.
DuplicateTensorOwnership {
/// Tensor name with conflicting owners.
name: String,
/// Checkpoint-relative shard paths that declare the tensor, sorted.
shards: Vec<String>,
/// Path of the checkpoint or index being inspected.
path: String,
},
/// An index-referenced Safetensors shard is missing on disk.
MissingShard {
/// Shard path as declared in the index (checkpoint-relative).
shard: String,
/// Path of the index or checkpoint that referenced the shard.
path: String,
},

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Suggestion: Adding variants to this public enum breaks downstream users that exhaustively match ParserError, contradicting the documented matching contract. [api mismatch]

Assessment: 🟠 Major · 🔁 Occurrence: Sometimes

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** src/error.rs
**Line:** 55:70
**Comment:**
	*Api Mismatch: Adding variants to this public enum breaks downstream users that exhaustively match `ParserError`, contradicting the documented matching contract.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

@codeant-ai

codeant-ai Bot commented Sep 15, 2026

Copy link
Copy Markdown

CodeAnt Nitpicks

1 code suggestion

1. After this metadata check succeeds, a deleted shard makes inspect_shard return Io, not the documented MissingShard error.

Api mismatch · src/safetensors/paths.rs:234-238

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:L This PR changes 100-499 lines, ignoring generated files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants