xet-core
AGENTS.md625 starsChanged 15 days agoApache-2.0View on GitHub
Rust libraries for Xet Storage: chunk-based deduplication, uploads, and file reconstruction for the Hugging Face Hub. hf_xet exposes them to Python through huggingface_hub. Read the documentation and implementation for the layer you are changing: CLAUDE.md links to this file. Keep shared agent guidance here. Component-specific build and test instructions live in hf_xet/AGENTS.md, git_xet/AGENTS.md, and wasm/AGENTS.md. Run from the repository root unless noted. Use Cargo for binding tests/lints and maturin for importable extensions. Keep PyO3's auto-initialize feature in test dependencies only.
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.
Of the AGENTS.md files we read, the 31,542 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository3 other files it gives its agents.
- git_xet/AGENTS.mdAGENTS.md
- hf_xet/AGENTS.mdAGENTS.md
- wasm/AGENTS.mdAGENTS.md
The file
Show its rules and text
We split this AGENTS.md into the rules it gives an agent
38 rules. About 1 is common, 14 are distinctive, and 23 are very specific to this project.
≈1
Common · estimate
Many files like this have a rule of this kind.
≈14
Distinctive · estimate
This author's own choices. Worth a look.
23
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 26
Rust: follow the version pinned in CI.
- Distinctive: line 33
Run from the repository root unless noted.
- Very specific: line 51
Use Cargo for binding tests/lints and maturin for importable extensions.
- Common: line 57
Run the checks that cover what you changed before claiming work is done.
- Distinctive: line 117
Follow nearby conventions.
- Distinctive: line 121
No premature abstractions or unnecessary generalization.
- Distinctive: line 122
Don't implement features until needed.
- Distinctive: line 123
Don't accept parameters, type parameters, or configuration flags without a use case.
- Distinctive: line 124
Prefer concrete types, early returns, and straightforward control flow.
- Distinctive: line 125
Prefer strictness now, relax later: narrow visibility, valid states encoded in types, explicit rejection of unsupported inputs.
- Very specific: line 129
Follow rustfmt.toml: 120-column code/comments, 100-column calls, 80-column chains, field-init shorthand, trailing commas after block match …
- Very specific: line 131
Prefer explicit imports. Existing exceptions include test use super::*, binding preludes, and module re-exports.
- Very specific: line 132
Use //! for module docs and /// for public items.
- Distinctive: line 133
Keep comments, examples, defaults, and public names synchronized.
- Very specific: line 139
Use lib.rs / mod.rs for declarations and re-exports.
- Very specific: line 143
Use new, with_*, build, and _blocking for sync counterparts.
- Distinctive: line 149
Place type definitions before implementations, with unit tests at the bottom.
- Distinctive: line 152
Keep implementation fields private or narrowly visible.
- Very specific: line 154
Use enums for mutually exclusive states, such as Sha256Policy::{Compute, Provided, Skip}.
- Very specific: line 160
Use #[from] for direct conversions.
- Very specific: line 164
Keep typed library errors.
- Very specific: line 165
Keep JsValue / N-API error conversions at binding boundaries.
- Very specific: line 166
Use .unwrap() / .expect() in tests or for explicit, justified invariants.
- Very specific: line 168
Don't assume error cloning preserves its cause: reconstruction errors use Arc, while ClientError has a lossy clone fallback.
- Very specific: line 185
Use tracing in libraries; reserve println!
- Very specific: line 186
Prefer structured fields: %value for Display, ?value for Debug, plain values for scalar fields.
- Very specific: line 187
Follow local severity policy.
- Very specific: line 188
Use #[instrument(skip_all, fields(...))] with selected metadata and .instrument(span) for async context.
- Very specific: line 190
Use inspect_err for logging without conversion.
- Very specific: line 196
Keep synchronous lock scopes short and never across .await.
- Very specific: line 197
Update related state atomically.
- Very specific: line 200
Use config_group! under xet_runtime/src/config/groups/, documented defaults, and HF_XET_<GROUP>_<FIELD> names.
- Distinctive: line 209
Keep diffs focused; exclude unrelated dependency bumps and generated changes.
- Distinctive: line 212
Follow api_changes/README.md for downstream-facing API changes.
- Distinctive: line 219
Check affected Windows, WASM, Python, and optional-feature builds.
- Very specific: line 224
Follow nearby runtime setup.
- Distinctive: line 227
Keep fixtures and coverage claims accurate: fixed seeds repeat data, cached versions affect fallback paths, and parser tests don't exercise …
- Very specific: line 240
Use RUST_BACKTRACE=full, RUST_LOG=info (or debug / trace), and HF_XET_LOG_DEST=/tmp/xet.log.
≈ “Common” is an estimate: at least 1 in 5 of the 40,246 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Agent Guide for xet-core
Project overview
Rust libraries for Xet Storage: chunk-based deduplication, uploads, and file reconstruction for the Hugging Face Hub. hf_xet exposes them to Python through huggingface_hub.
Architecture documentation
Read the documentation and implementation for the layer you are changing:
- Project overview — setup and usage.
- Session API — public Rust API and crate relationships.
- Data processing — chunking, deduplication, and reconstruction.
- Client — CAS and Hub communication.
- Core structures — hashes, shards, and Xorb objects.
- Runtime — async runtime, configuration, and logging.
- Python extension — hf-xet Python package.
- Git extension — Git LFS transfer agent.
- Browser WASM wrapper — upload/download WASM APIs and smoke tests; an example, not a published SDK.
- Thin WASM extension — chunking and hashing for JavaScript; benchmarks.
CLAUDE.md links to this file. Keep shared agent guidance here. Component-specific build and test instructions live in hf_xet/AGENTS.md, git_xet/AGENTS.md, and wasm/AGENTS.md.
Setup
- Rust: follow the version pinned in CI. Use nightly
rustfmt. - Python: activate a virtualenv and install
maturinandpytest. Build/install withmaturin develop; produce wheels withmaturin build. - Git tests: install Git LFS and run
git lfs install. - Separate manifests:
hf_xet,simulation,wasm/*, andexamples/xet_pkg_napiare excluded from the root workspace. Check them separately when affected.
Key commands
Run from the repository root unless noted.
| Command | Purpose |
cargo build | Build the root workspace |
cargo test | Test the root workspace with default features |
cargo test --package hf-xet | Test one package; substitute the affected package |
cargo test --package xet-client test_name | Run matching tests |
cargo build --package hf-xet --example example --features internal-tools | Build the async example; use example_sync for sync |
cargo clippy -r --verbose -- -D warnings | Lint the root workspace |
cargo clippy -r --verbose --manifest-path hf_xet/Cargo.toml -- -D warnings | Lint Python bindings |
cargo +nightly fmt --manifest-path Cargo.toml --all | Format the root workspace |
cargo +nightly fmt --manifest-path hf_xet/Cargo.toml --all | Format Python bindings |
cargo test --manifest-path hf_xet/Cargo.toml --verbose --no-fail-fast | Test Python bindings in Rust |
(cd hf_xet && maturin develop) | Build/install the Python extension |
pytest hf_xet/tests/ -v | Test the rebuilt Python extension |
cargo bench --no-run --workspace --exclude git_xet | Check benchmark compilation |
Use Cargo for binding tests/lints and maturin for importable extensions. Keep PyO3's auto-initialize feature in test dependencies only.
The simulation feature enables workspace support, not the excluded simulation/ package. The cargo smoke-test alias currently references that excluded package; use targeted tests instead.
Verification
Run the checks that cover what you changed before claiming work is done. Documentation-only changes need no builds or tests. These mirror CI; everything here runs locally without network access or Hub credentials.
Every Rust change:
cargo +nightly fmt --manifest-path Cargo.toml --all -- --check
cargo +nightly fmt --manifest-path hf_xet/Cargo.toml --all -- --check
cargo clippy -r --verbose -- -D warnings
cargo clippy -r --verbose --manifest-path hf_xet/Cargo.toml -- -D warnings
cargo test --package <changed-package>Full root workspace with CI features (required for Git, simulation, or cross-crate changes):
cargo test --verbose --no-fail-fast --features "strict simulation internal-tools git-xet-for-integration-test"Per-component checks; each directory has its own AGENTS.md with setup details:
| Changed area | Run | Details |
hf_xet/ or anything it depends on | cargo test --manifest-path hf_xet/Cargo.toml --no-fail-fast, then (cd hf_xet && maturin develop) && pytest hf_xet/tests/ -v | hf_xet/AGENTS.md |
git_xet/ | cargo test --package git_xet --features git-xet-for-integration-test | git_xet/AGENTS.md |
wasm/* or the crates they depend on | (cd xet_pkg && ./build_wasm.sh), (cd wasm/hf_xet_thin_wasm && ./build_wasm.sh), (cd wasm/hf_xet_wasm && ./build_wasm.sh) | wasm/AGENTS.md |
benches/ or bench dependencies | cargo bench --no-run --workspace --exclude git_xet | |
| Dependency changes | cargo machete, cargo audit -D warnings, then confirm git status --porcelain '*Cargo.lock' is empty |
Lockfiles are committed for the root workspace, hf_xet, and both wasm/* crates; CI fails if a build leaves them modified.
Report which checks ran, which failed, and which were skipped.
Code structure
API layers: hf_xet Python extension → hf-xet Rust crate → xet-data, supported by xet-client, xet-core-structures, and xet-runtime.
| Path | Cargo package | Responsibility |
xet_pkg/ | hf-xet | Public Rust API; library name xet |
xet_data/ | xet-data | Chunking, deduplication, uploads, reconstruction |
xet_client/ | xet-client | CAS/Hub clients, retries, connections, chunk cache |
xet_core_structures/ | xet-core-structures | Hashes, shard/Xorb formats, shared structures |
xet_runtime/ | xet-runtime | Runtime, configuration, logging, utilities |
git_xet/ | git_xet | Git LFS integration |
git_extension_common/ | git_extension_common | Shared Git support: repositories, remote URLs, credentials, SSH, subprocesses |
hf_xet/ | hf_xet | PyO3 bindings; separate manifest |
simulation/ | simulation | Simulations/benchmarks; separate manifest |
wasm/ | Separate crates | Browser/WASM builds |
Where to make changes
- Sessions:
xet_pkg/src/xet_session/— commits, groups, handles, background tasks. - Uploads:
xet_data/src/processing/anddeduplication/. - Downloads:
xet_data/src/file_reconstruction/. - Networking/cache:
xet_client/src/cas_client/,hub_client/,chunk_cache/. - Runtime/configuration:
xet_runtime/src/core/,config/,logging/. - Python:
hf_xet/src/; update related examples andhf_xet/tests/.
Code style
Follow nearby conventions. Do not rename existing APIs or reformat unrelated code for uniformity.
Simplicity is the #1 priority
- No premature abstractions or unnecessary generalization. Traits, generics, and macros need a concrete use case.
- Don't implement features until needed.
- Don't accept parameters, type parameters, or configuration flags without a use case.
- Prefer concrete types, early returns, and straightforward control flow.
- Prefer strictness now, relax later: narrow visibility, valid states encoded in types, explicit rejection of unsupported inputs.
Formatting, imports, and comments
- Follow rustfmt.toml: 120-column code/comments, 100-column calls, 80-column chains, field-init shorthand, trailing commas after block match arms.
- Group imports: standard library, external/workspace crates, then
crate/super. Group imports from the same module with braces. - Prefer explicit imports. Existing exceptions include test
use super::*, binding preludes, and module re-exports. - Use
//!for module docs and///for public items. Explain purpose, invariants, units, lifecycle, and failures; don't restate code. - Keep comments, examples, defaults, and public names synchronized. Remove dead code and redundant checks; extract substantial validation into named helpers.
Naming and modules
- Files/modules, functions, fields, and variables:
snake_case. Types/traits/variants:UpperCamelCase. Constants/statics:SCREAMING_SNAKE_CASE. - Name files by responsibility (
file_upload_session.rs); related types can share a module. - Use
lib.rs/mod.rsfor declarations and re-exports. Expose needed types without making implementation modules public. - Errors usually live in
error.rsorerrors.rs. Helpers useutils,common, ortest_utils; keep domain helpers near consumers. - Name types by role:
FileUploadSession,ShardFileManager,DataWriter. Traits have noIprefix. UseBuilder,Inner,Report,Info, andStatesuffixes where meaningful. - Session types use
Xet...; Python wrappers usePyXet...inpy_*.rs, with#[pyclass(name = "...")]. Thin WASM wrappers useJs.... - Use
new,with_*,build, and_blockingfor sync counterparts. Predicates useis_*/has_*; accessors describe their value (progress,task_id). - Preserve existing acronym spelling (
XorbObject,MDBShardFile,URLProvider,IOError). Include units in numeric names; useDuration/ByteSizewhere appropriate. xet_pkg/is packagehf-xet, libraryxet; Python bindings alias it asxet-pkg, imported asxet_pkg.
Types and ownership
- Place type definitions before implementations, with unit tests at the bottom.
- Derive useful standard traits; reserve
Copyfor suitable value types and serde derives for serialized data. - Shared handles use
Arc<FooInner>; cloning shares state. Keep locks and lifecycle state inside the inner type. - Keep implementation fields private or narrowly visible. Public data/configuration fields follow local conventions.
- Builders usually consume and return
Self. Borrow strings, paths, and slices when ownership is unnecessary; useimpl Into<String>/impl AsRef<Path>where useful. - Use enums for mutually exclusive states, such as
Sha256Policy::{Compute, Provided, Skip}. Prefer named structs over opaque tuples. - Reuse domain types and conversions. CAS response types belong in
cas_types; useHexMerkleHashfor serialized hash strings.
Errors and Result
- Extend crate/subsystem error enums deriving
thiserror::ErrorandDebug, with readable#[error("...")]messages. - Use
#[from]for direct conversions; manualFromimplementations for classification, context, redaction, orArcwrapping. Follow existing#[non_exhaustive]policy. - Lower layers commonly define
pub type Result<T> = std::result::Result<T, TheirError>. Use the local alias or explicit error type; avoid new aliases such asCoreResult. - Session APIs use
Result<T, SessionError>/Result<T, XetError>;SessionErroraliasesXetError. Python boundaries usePyResult<T>. - Propagate with
?/.await?. Usemap_errfor conversion/context andok_or_elsefor missing required values. Return final result expressions directly when possible. - Keep typed library errors;
anyhowis common in tools and test helpers. Preserve XetError categories and Python mappings throughconvert_xet_error/From<XetError> for PyErr. - Keep
JsValue/ N-API error conversions at binding boundaries. - Use
.unwrap()/.expect()in tests or for explicit, justified invariants. Return errors for fallible I/O, parsing, network operations, and caller input. - Ignore results only for intentionally best-effort work. Preserve original task errors across channels; distinguish cancellation from panic.
- Don't assume error cloning preserves its cause: reconstruction errors use
Arc, whileClientErrorhas a lossy clone fallback.
Example from DataError:
#[derive(thiserror::Error, Debug)]
pub enum DataError {
#[error("I/O error: {0}")]
IOError(#[from] std::io::Error),
// Other variants omitted.
}
pub type Result<T> = std::result::Result<T, DataError>;Logging
- Use
tracingin libraries; reserveprintln!/eprintln!for CLI output and diagnostics. - Prefer structured fields:
%valueforDisplay,?valueforDebug, plain values for scalar fields. - Follow local severity policy. Expected retries are not terminal errors. Preserve CAS
INFORMATION_LOG_LEVELbehavior and avoid duplicate logging across layers. - Use
#[instrument(skip_all, fields(...))]with selected metadata and.instrument(span)for async context. Don't capture credentials or full payloads. - ErrorPrinter provides
log_error,warn_error,debug_error, andinfo_error. They log failures and return the result unchanged; append?to propagate._fnvariants build messages lazily.OptionPrinterprovides*_nonehelpers. - Use
inspect_errfor logging without conversion. Preserve URL redaction inClientError::from(reqwest::Error); don't log raw signed URLs first. - Emit one-time diagnostics after subscriber initialization. Distinguish logical, network/compressed, and deduplicated bytes in metrics. Show user operations, not shard bookkeeping, in progress output.
Concurrency and configuration
- Reuse
XetRuntime,XetContext, task helpers, and progress types. - Keep synchronous lock scopes short and never across
.await. Use async locks when guards must span awaits. Centralize lock ordering and check for nested acquisition. - Update related state atomically. Concurrent deletion must not erase a fresh upload's metadata. Use
SafeFileCreatoror temp-file/rename patterns for atomic file replacement. - Define failure, cancellation, drop, and shutdown behavior for all child tasks. Cancel/drain siblings as required before returning; cleanup failures must not skip remaining children.
- Release the Python GIL with
py.detachfor blocking work. Follow existingblocking_call_with_signal_checkusage for responsive Ctrl-C. - Use
config_group!underxet_runtime/src/config/groups/, documented defaults, andHF_XET_<GROUP>_<FIELD>names. Avoid scattered environment reads and duplicate constants. - Validate configuration at construction and activation after mutation; avoid hidden changes inside consumers.
- Preserve platform/feature gates. WASM async traits may need
?Send. Keep lint exceptions narrow;strictbuilds deny warnings.
Development guidelines
Scope and compatibility
- Trace the real call path and active configuration before changing behavior. Establish the affected use case, including optional features.
- Keep diffs focused; exclude unrelated dependency bumps and generated changes. Design public APIs from concrete caller examples.
- Preserve wire/storage layouts, serde attributes, discriminants, canonical chunking, and hashes. Validate lengths, counts, and checked arithmetic before allocation/composition; don't let
zipsilently truncate protocol data. - Coordinate endpoint/format changes with server rollout and test fallback behavior. Simulation clients must match observable production behavior, including streamed failures.
- Follow api_changes/README.md for downstream-facing API changes. Scan relevant entries during merges/rebases; document migration steps.
- Reuse workspace dependencies, keep test/tool dependencies out of normal builds, and follow root manifest notes for WASM version synchronization.
Performance
- Measure relevant workloads before optimizing. Prefer buffer/client reuse and fewer allocations before unsafe or architecture-specific complexity.
- Bound aggregate memory, tasks, requests, and teardown waits across concurrent transfers. Budgets must accommodate the largest valid work item and make progress at low settings.
- Check affected Windows, WASM, Python, and optional-feature builds; gate platform-specific dependencies.
Tests
- Unit tests:
#[cfg(test)] mod tests, usually at file end. Integration tests:tests/test_<behavior>.rs. Benchmarks:benches/. - Follow nearby runtime setup. Reuse
tempfile, seeded data, simulation clients, and local servers. UseEnvVarGuardto restore environment changes. - Regression tests should fail on the original bug. Assert exact deterministic values, ordering, content types, and relevant error variants.
- Cover relevant boundaries, retries, duplicate/out-of-order events, interruption, and cleanup. Use realistic payload sizes for streaming tests.
- Keep fixtures and coverage claims accurate: fixed seeds repeat data, cached versions affect fallback paths, and parser tests don't exercise the retry pipeline.
- Python tests use pytest fixtures,
tmp_path, local CAS,Test...classes, andtest_...methods. Rebuild bindings first. - WASM smoke tests use
.mjs, camelCase identifiers, and kebab-case scenario files; follow local script style. - Report checks run, failures, and checks not completed.
Review and communication
- Focus on correctness, compatibility, data integrity, lifecycle, resource limits, and coverage.
- Explain concrete impacts; distinguish confirmed defects from questions and optional
nit:suggestions. - Describe the problem, resulting behavior, validation, and affected configuration. Include examples/measurements where useful; flag breaking changes, coordination needs, and limitations.
Debugging
Use RUST_BACKTRACE=full, RUST_LOG=info (or debug / trace), and HF_XET_LOG_DEST=/tmp/xet.log.
See diagnostic scripts for symbol/trace capture. The smoke tests exercise a released or locally built hf_xet wheel against the real Hub and need an HF_TOKEN; they are a release check, not part of routine verification.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

