Skip to content

Gate the sentence-transformers module types on the routes that delegate the load - #12446

Merged
danielhanchen merged 16 commits into
mainfrom
st-validate-before-delegating
Oct 1, 2026
Merged

danielhanchen merged 16 commits into
mainfrom
st-validate-before-delegating

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

FastSentenceTransformer.from_pretrained has three routes, and only one of them reaches the modules.json gate.

  • for_inference = True returns a stock SentenceTransformer and returns immediately.
  • The fast encoder route does the same, and it is the default for every model type in ENCODER_MODEL_TYPES, so bge, MiniLM, mpnet, gte and the rest of the common embedders take it.
  • Only the fallback assembly route reaches _load_modules, which is where the gate on a repo-declared module class lives.

Delegating is fine when the installed sentence-transformers gates for itself, which it does from 6.0. Below that it resolves a modules.json type with no gate at all, so on those installs the dotted path a repo named is imported and its top level code runs, through the route most embedding models take by default. Measured on sentence-transformers 5.5.0, loading a local bge-small copy whose Pooling entry names a marker module, end to end through from_pretrained:

module imported outcome
main yes TypeError: marker_mod.Thing is not a Module subclass, after the import had already run
this branch no ValueError: ... which is not part of Sentence Transformers

So main today reports a type error from sentence-transformers, which looks like a broken model rather than code having been run.

What changed

_check_modules_json_types validates the type of every entry before the load is handed over, reusing the same _resolve_module_class the assembly route already uses, so there is one gate and one message rather than a second copy of the rules. It resolves nothing and loads nothing beyond that check: entries naming sentence-transformers' own Transformer are skipped by the existing string test, and the rest go through the gate, which is a no-op for an in-namespace class and a refusal for anything else without trust_remote_code=True.

It is called at the two delegating sites, so all three routes now agree. For an install on 6.0 or newer this only moves the identical refusal slightly earlier, with Unsloth's message instead of upstream's.

Compatibility

  • bge-small, all-MiniLM-L6-v2 and embeddinggemma-300m load through from_pretrained with embeddings identical to main, down to the values, covering both the fast encoder route and the fallback route.
  • A repo with no modules.json, which is every transformers-native encoder, is unaffected: the validator returns immediately.
  • An unreadable or non-list modules.json is left to the loader to report, as before, rather than becoming a new failure mode here.
  • tests/test_st_modules_json_trust_gate.py gains the refusal on the delegated route, a stock three-module list passing untouched, and the no-modules.json case.
  • The cost is one already-cached modules.json read on a path that is about to download a model.

Not covered

A Router or Asym module declares its children in its own config, and those children have configs of their own; the config check looks at one module directory and does not recurse, so a child naming an outside class is not covered. No repo I looked at ships a Router or Asym module, and it needs a separate change to do properly.

…rmers

from_pretrained has three routes and only the fallback assembly one reaches
_load_modules, where the modules.json gate lives. for_inference and the fast
encoder route return a stock SentenceTransformer straight away, and the fast
encoder route is the default for every type in ENCODER_MODEL_TYPES, so bge,
MiniLM, mpnet and gte take it.

That is fine from sentence-transformers 6.0, which gates a repo-declared module
class itself. Below that it resolves the type with no gate, so those routes
imported the dotted path a repo named. On 5.5.0, loading a bge-small copy whose
Pooling entry names a marker module through from_pretrained imports it and then
reports TypeError from sentence-transformers, which reads as a broken model
rather than as code having run.

Validate the types before handing the load over, through the same
_resolve_module_class the assembly route uses, so there is one gate and one
message. Nothing is loaded by the check, and on 6.0 and newer it only moves the
same refusal slightly earlier.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 1, 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-10-01T22:50:44.746028Z db1cfa0 Manual request
🔒 Security Review ✅ Completed 2026-10-01T15:13:17.599545Z 80d2897 Manual request
ℹ️ 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@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: 0ca6b97f5f

ℹ️ 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".

Comment thread unsloth/models/sentence_transformer.py Outdated
Comment on lines +1353 to +1355
modules_json_path = FastSentenceTransformer._module_path(
model_name, token, cache_dir = cache_dir, revision = revision
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Validate the same sentence-transformers cache

When only SENTENCE_TRANSFORMERS_HOME is configured, both delegated SentenceTransformer loads resolve that environment variable, while this helper receives cache_dir=None and _module_path consequently searches the default Hugging Face cache. If the model exists only in the sentence-transformers cache and the Hub is unavailable (for example, an offline deployment), _module_path swallows the cache miss, validation returns, and sentence-transformers < 6 then loads the cached modules.json and imports its untrusted type without this gate. Resolve SENTENCE_TRANSFORMERS_HOME here (as the prefetch already does) so validation and the delegated load inspect the same artifact.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 83a408d: resolved in the helper, so both delegating sites inspect the artifact the load will read. You are right that it failed open rather than loudly, which is the worse direction for a guard: _module_path turns a cache miss into "no modules.json" and validation then returned. The regression test pins it by stubbing _module_path and asserting the cache_dir it receives, and it fails without the change.

The delegated SentenceTransformer loads honour SENTENCE_TRANSFORMERS_HOME and
hf_hub_download does not, so with only that variable set the validator looked in
the default Hugging Face cache, _module_path swallowed the miss, and the gate
passed on a modules.json it had never read. Offline, sentence-transformers below
6 then loaded the cached file and imported its type ungated.

Resolve the variable in the helper, so both sites inspect the same artifact the
load will.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@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: 83a408dbcf

ℹ️ 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".

Comment thread unsloth/models/sentence_transformer.py Outdated
Comment on lines +1381 to +1384
FastSentenceTransformer._resolve_module_class(
class_ref,
model_name,
trust_remote_code,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve repo-local custom modules on sentence-transformers < 6

When trust_remote_code=True with sentence-transformers < 6, a Hub model can legitimately declare a repo-local module that is not installed on sys.path; stock sentence-transformers resolves it with get_class_from_dynamic_module. This added validation instead reaches _resolve_module_class, whose pre-6 fallback is import_from_string, so both delegated routes now raise ModuleNotFoundError before SentenceTransformer gets a chance to load the consented module. The validator needs to use the same pre-6 dynamic-module resolution as the delegated loader.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 80d2897. Confirmed in the 5.2.0 source: _load_module_class_from_ref resolves a non-namespace ref through get_class_from_dynamic_module when trust_remote_code is set, so the validator would indeed have raised ModuleNotFoundError first. The fix is to return early under consent rather than to copy the dynamic resolution: consent means the code may run, so there is nothing for this to gate, and it also stops the validator importing anything as a side effect of validating.

Comment thread unsloth/models/sentence_transformer.py Outdated
Comment on lines +1360 to +1361
if not modules_json_path:
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Fail closed when fetching modules.json fails

When the prefetch or this first Hub request encounters a transient error, _module_path catches every exception and returns None, and this early return treats that failure as if the repository had no modules.json. The immediately following SentenceTransformer request can then succeed and, on sentence-transformers < 6, import an unchecked custom type. Fresh evidence beyond the resolved cache mismatch is this exception-driven path: validation and loading may target the same cache yet differ because the first access failed, so the guard must distinguish a confirmed missing file from an inability to validate it.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 80d2897, and you were more right than the first attempt at it. A confirmed absence is now a local folder without the file, a cache entry recording a 404, or a 404 now; anything else is an inability to check, and that refuses where sentence-transformers would not gate the type itself, while staying quiet from 6.0 where it does, so an unreachable check cannot turn a working load into a failure there. Worth recording that my first version still failed open: LocalEntryNotFoundError subclasses EntryNotFoundError, so catching the parent first turned unreachable into absent. Caught it by testing offline against 5.2.0, and both directions are now pinned by tests.

Two things wrong with the validator.

Consent means the code may run, so there is nothing to gate, and resolving
anyway broke a legitimate case: below 6 the delegated loader fetches a
repo-local class with get_class_from_dynamic_module, which this helper's
fallback cannot, so a consented repo-local module raised ModuleNotFoundError
before sentence-transformers got the chance. Return early instead, which also
stops the validator importing anything.

_module_path turns every failure into absent, so a transient or offline failure
read as "no modules.json" and the load that followed could still import the
type. Separate a confirmed absence, which is a local folder without the file, a
cache entry recording a 404, or a 404 now, from an inability to check, and
refuse on the latter only where sentence-transformers would not gate the type
itself. LocalEntryNotFoundError needs handling before EntryNotFoundError, which
it subclasses: catching the parent first turned unreachable into absent, so the
first attempt at this was still fail-open.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security 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: 80d289788b

ℹ️ 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".

Comment thread unsloth/models/sentence_transformer.py Outdated
Comment on lines +1463 to +1466
class_ref = module_config.get("type")
if FastSentenceTransformer._is_transformer_module_ref(class_ref):
continue
FastSentenceTransformer._resolve_module_class(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Gate class references in delegated module configs

On either delegated route with sentence-transformers < 6 and trust_remote_code=False, this loop validates only each modules.json type. A permitted type such as sentence_transformers.models.Dense can still provide 2_Dense/config.json with an arbitrary activation_function; the 5.2 loader resolves and instantiates that dotted path, so repository code executes despite this gate. The existing _load_modules route calls _check_module_config_class_refs for exactly this case, but these newly delegated routes never do, so their module configs need equivalent validation before constructing SentenceTransformer.

Useful? React with 👍 / 👎.

Comment thread unsloth/models/sentence_transformer.py Outdated
Comment on lines +1373 to +1377
cached = try_to_load_from_cache(
model_name,
"modules.json",
cache_dir = cache_dir or HUGGINGFACE_HUB_CACHE,
revision = revision,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Consult the active Hugging Face cache

When callers leave cache_dir unset but configure the standard HF_HUB_CACHE, this fallback searches the legacy HUGGINGFACE_HUB_CACHE path instead. In an offline sentence-transformers < 6 deployment where the active cache records that a transformers-native model has no modules.json, _module_path first returns None, this lookup misses that cached absence, and the subsequent download raises LocalEntryNotFoundError, causing a new ValueError rather than allowing the cached model to load. Use the Hub's HF_HUB_CACHE default (or omit cache_dir) so the confirmation lookup targets the same cache as hf_hub_download.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: 80d289788b

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

… cache

Two gaps in the delegated gate.

An allowed type was the whole check. Dense is a permitted sentence_transformers
class, and below 6.0 its loader resolves and calls whatever activation_function its
config names; Router and Asym do the same with types, WordEmbeddings with
tokenizer_class. _load_modules already checks that from the files it downloaded,
but the delegated routes hand the load to sentence-transformers and never reached
it, so a repo could pass the type check and still have its dotted path imported.

_check_delegated_module_config fetches the module's own config and runs the same
check. It is scoped to the four classes that actually resolve a class ref, so an
ordinary embedder of Transformer, Pooling and Normalize adds no request at all,
which a test pins by failing on any fetch. A local model directory is read in
place rather than downloaded.

The cached-absence lookup named HUGGINGFACE_HUB_CACHE as its default. That is the
legacy constant and does not follow HF_HUB_CACHE, so with HF_HUB_CACHE set it
searched a different cache from the one hf_hub_download writes, missed a recorded
absence, and turned a cached transformers-native model offline into a refusal.
Passing None lets the hub apply one default to both.

Measured against the previous head: the config-ref case did not raise and now
raises, and the cache lookup passed the legacy path and now passes None. The real
embeddinggemma Dense config, which names torch.nn.modules.linear.Identity, is
untouched on both.
@danielhanchen

Copy link
Copy Markdown
Member Author

Both fixed in 1e51d45fd.

Module configs on the delegated routes. Correct, and it is the same gap this PR exists for, one level down: the type check passed and the dotted path inside the module's own config was never looked at. _check_delegated_module_config now fetches that config and runs _check_module_config_class_refs on it, so the delegated routes check what _load_modules checks.

It is scoped to the four classes that actually resolve a class ref out of their config, Dense via activation_function, Router and Asym via types, WordEmbeddings via tokenizer_class. Every other shipped class reads plain values, so an ordinary embedder of Transformer, Pooling and Normalize adds no request at all; a test pins that by failing on any fetch. A local model directory is read in place instead of downloaded.

Measured against the previous head: the config-ref case was DID NOT RAISE, it now raises. The real embeddinggemma-300m Dense config, which names torch.nn.modules.linear.Identity, loads untouched on both.

The cache the download reads. Also correct, and worse than a missed cached absence: HUGGINGFACE_HUB_CACHE does not follow HF_HUB_CACHE at all. With HF_HUB_CACHE=/tmp/x the two constants resolve to different directories, so the lookup searched a cache hf_hub_download never writes. Fixed by passing None and letting the hub apply one default to both, rather than naming a default of our own. The test asserts the argument is None; before, it was the legacy path.

Worth noting for this branch specifically: the config check still keys off import_module_class, so on sentence-transformers 5.5 and later 5.x it is skipped, which is wrong for the reason #12444 fixes by removing the version fork. The new tests hide that attribute to exercise the pre-6 loader. With both branches merged the fork is gone and the check runs on every version.

@danielhanchen

Copy link
Copy Markdown
Member Author

@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: 1e51d45fdb

ℹ️ 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".

Comment on lines +1519 to +1521
folder = module_config.get("path")
if not isinstance(folder, str) or not folder:
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Validate configs for modules stored at the repository root

When an untrusted modules.json declares an allowed class such as sentence_transformers.models.Dense with "path": "", this return skips the module-config gate entirely. Sentence-transformers 5.2 accepts an empty subfolder and loads the root config.json, where Dense.load imports and instantiates activation_function; consequently a root-level config can still resolve an unchecked dotted path with trust_remote_code=False. Fresh evidence beyond the earlier config-gating comment is this newly added empty-path early return.

Useful? React with 👍 / 👎.

Comment thread unsloth/models/sentence_transformer.py Outdated
Comment on lines +1547 to +1548
except Exception:
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Fail closed when the module-config fetch is unverifiable

On sentence-transformers < 6, if this request for a Dense config encounters a transient Hub/cache error, the exception is discarded and validation proceeds as though there were no config. The immediately following SentenceTransformer load performs another request that can succeed, then imports and instantiates the unchecked activation_function; confirming that modules.json was readable does not establish that this separate file was validated. Fresh evidence beyond the resolved modules.json failure path is that the newly added module-config downloader independently swallows every fetch error.

Useful? React with 👍 / 👎.

Two holes in the module-config check added in the previous commit.

An empty path was skipped. sentence-transformers accepts "path": "" and loads the
repository's root config.json, so declaring Dense at the root put the class ref
somewhere the check never looked, which made the whole check bypassable. An empty
path is now the repository root for both the local and the Hub case.

The fetch swallowed every error. That recorded "this module ships no config" for a
transient failure, while the load that follows makes its own request, which can
succeed and resolve the unchecked name: the same fail-open shape as reading an
unverifiable modules.json as an absent one. A genuine 404 still means there is no
class ref to check and passes; anything else refuses. LocalEntryNotFoundError is
caught before EntryNotFoundError, which it subclasses, so unreachable is not read as
absent.

The check now returns before fetching anything when the installed
sentence-transformers is 6.0 or later, which gates these names itself. That removes
the request on versions that do not need it, and means a transient error there
cannot turn into a refusal. The test is the version and not
hasattr(import_module_class): 5.5 exports that helper while its module loaders still
resolve the name ungated.

Measured on sentence-transformers 5.2.0: both new cases did not raise before and
raise now. bge-small-en-v1.5 and embeddinggemma-300m, whose two Dense configs this
check now reads, load with the same modules and byte-identical embedding
fingerprints on both sides.
@danielhanchen

Copy link
Copy Markdown
Member Author

Both fixed in 22395cf88, and both were real.

Root-level module config. "path": "" is the repository root, sentence-transformers accepts it, and skipping it made the entire module-config check bypassable: declare Dense at the root and the class ref sits in the root config.json, where nothing looked. An empty path is now the repository root in both the local and the Hub branch. It did not raise before and raises now.

Fail closed on an unreadable module config. Also right, and it is the same shape as reading an unverifiable modules.json as an absent one, which this PR already fixed one level up: confirming modules.json was readable says nothing about a separate file. A genuine 404 still passes, because a module that ships no config has no class ref to check. Anything else refuses, with LocalEntryNotFoundError caught ahead of EntryNotFoundError since it subclasses it.

One thing I changed beyond the two comments, because fixing the second one as written would have introduced a regression: the check now returns before fetching anything when the installed sentence-transformers is 6.0 or later. Upstream gates these names itself from 6.0, so there was nothing to add there, and without this an unrelated transient error on a current install would have become a refusal. The test is the version rather than hasattr(import_module_class), because 5.5 exports that helper while its module loaders still resolve the name ungated, which is the fork #12444 removes.

Measured on sentence-transformers 5.2.0, with the real models rather than stubs alone: bge-small-en-v1.5 and embeddinggemma-300m, whose two Dense configs this check now reads, load with the same module lists and byte-identical embedding fingerprints before and after.

@danielhanchen

Copy link
Copy Markdown
Member Author

@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: 22395cf889

ℹ️ 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".

Comment thread unsloth/models/sentence_transformer.py Outdated
config_file_name = getattr(module_class, "config_file_name", None)
if isinstance(config_file_name, str):
config_names.append(config_file_name)
config_names.append("config.json")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Fetch config.json only when it is a real fallback

For a remote WordEmbeddings module on sentence-transformers < 6, the validator successfully reads wordembedding_config.json and then unconditionally requests config.json, although WordEmbeddings.load never uses that second file. If the model is cached for offline use without a cached 404 for the unused file, this extra request raises LocalEntryNotFoundError and rejects a model that the delegated loader could load entirely from cache. Only request config.json for classes that actually use it, and for Router request it only when router_config.json is confirmed absent.

Useful? React with 👍 / 👎.

Fetching config.json after a successful read of the module's own file was a
liability once the fetch failed closed: WordEmbeddings.load never opens config.json,
so an unnecessary request against a cache that is complete for the load but carries
no recorded 404 for the unused name turned a model the delegated loader could load
entirely from cache into a refusal.

Only Router and Asym fall back to config.json when their own file is absent. Every
other class opens exactly one file, and the loop now stops at the first config it
reads, because the loader does too.

Measured against the previous head: the WordEmbeddings case raised that spurious
refusal and now requests one file and passes. Router still reads config.json when
router_config.json is absent and still refuses the class ref in it, which is a
negative control that passes on both sides.
@danielhanchen

Copy link
Copy Markdown
Member Author

Fixed in the latest commit, and this one was a regression I introduced rather than a pre-existing gap: making the fetch fail closed turned an unnecessary request into a refusal.

WordEmbeddings.load opens wordembedding_config.json and never looks at config.json, so requesting the second file bought nothing and could fail against a cache that is complete for the load but carries no recorded 404 for a name the loader never asks for. Only Router and Asym have config.json as a real fallback. Every other class opens exactly one file, and the loop now stops at the first config it reads, because the loader does too.

Measured against the previous head: the WordEmbeddings case raised Could not read config.json ... refuses rather than loading unchecked, and now requests 0_WordEmbeddings/wordembedding_config.json only and passes. A second test keeps Router honest: with router_config.json absent it still reaches config.json and still refuses the class ref in it, and that one passes on both sides.

@danielhanchen

Copy link
Copy Markdown
Member Author

@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: 9a8fd7fa1b

ℹ️ 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".

Comment thread unsloth/models/sentence_transformer.py Outdated
Comment on lines +1595 to +1598
folders.append(os.path.dirname(downloaded))
# The loader opens the first of these it finds, so once one is read there
# is no second file to check and no reason to ask for one.
break

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Follow Router's content-based config fallback

When snapshot prefetch is unavailable or fails and sentence-transformers < 6 loads a remote Router, an existing but falsey router_config.json (for example {}) reaches this unconditional break. Upstream Router.load instead checks if not config and then fetches config.json; because that fallback is not yet cached, _check_module_config_class_refs only examines the empty official file. A repository can therefore place an unchecked external class in the fallback's types, which the subsequent delegated load imports despite trust_remote_code=False. Parse the first config and continue to the fallback whenever its content is falsey.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Confirmed against the 5.1.0 source rather than from the diff: Router.load is config = cls.load_config(...) then if not config: config = cls.load_config(config_filename = "config.json", ...), at sentence_transformers/models/Router.py:343-348, and Router is the only shipped class with both its own config_file_name and that fallback. Fixed in 1a40d22: the download loop parses what it fetched and only stops on truthy content, which is the same condition upstream uses.

The reader had the mirror-image bug, which your example surfaced while I was writing the test for it. _check_module_config_class_refs took the union of every config present in the folder, so a repository whose router_config.json is clean was refused because an unrelated config.json sat beside it, which is a load upstream completes. It now stops at the first real config as well, so both loops and upstream agree in both directions.

test_an_empty_router_config_still_checks_the_fallback keeps the remote files and the cache in separate directories on purpose: writing both into one folder lets the reader find the fallback on disk and refuse for a reason that has nothing to do with whether it was ever fetched. With them separated the previous head does not raise at all, which is the bypass. test_a_non_empty_config_asks_for_nothing_extra holds the cost down, asserting that an ordinary Router load still requests exactly one file.

@danielhanchen

Copy link
Copy Markdown
Member Author

unsloth_zoo vllm/grpo/peft/st modules import under CUDA spoof fails on this PR's new tests in tests/test_st_modules_json_trust_gate.py, e.g. test_an_ordinary_embedder_fetches_no_module_configs:

monkeypatch.py:95: in annotated_getattr
    obj = getattr(obj, name)
E   AttributeError: module 'unsloth' has no attribute 'models'

That job is the only one that runs this file, since it has sentence-transformers installed (#12447). There, monkeypatch.setattr("unsloth.models....") with a dotted string resolves unsloth.models as an attribute of the package, which is not bound until the submodule is imported. Importing the module and patching the object fixes it: import unsloth.models.sentence_transformer as st_mod, then monkeypatch.setattr(st_mod, "...", ...).

Six tests in this file failed in the "unsloth_zoo vllm/grpo/peft/st modules import
under CUDA spoof" job. They patched hf_hub_download by dotted string, and
monkeypatch raised AttributeError resolving unsloth.models under the spoof.

Taking the module out of sys.modules instead is not enough either.
tests/vllm_compat/test_extended_module_imports.py pops
unsloth.models.sentence_transformer out of sys.modules and re-imports it, so by the
time these tests run that name is a second module object with its own globals dict,
while the class imported at the top of this file still reads the first one. Patching
the later object leaves the real hf_hub_download in place: three tests went out to
the Hub and asserted against a 404 rather than against their fake, which is also why
they only failed when run after that file.

The patch target is now the method's own __globals__, which is that dict by
definition however many times anything else is re-imported. The two tests that
reached for the module via `import ... as st_mod` had the same latent problem and go
through the same helper.

Before: 6 failed, 62 passed. After: 68 passed, and still 68 with HF_HUB_OFFLINE=1,
so nothing in the file touches the network.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

Two holes, both of which let a repository be validated and then load something else.

sentence-transformers 5.x Router.load reads its own config and falls back on falsey
content, not on an absent file: Router.py has `config = cls.load_config(...)` then
`if not config: config = cls.load_config(config_filename = "config.json")`. The check
stopped at the first config that downloaded, so an existing but empty router_config.json
was validated, the fallback was never fetched, and the `types` the loader does resolve
went unchecked. It now parses what it downloaded and only stops on truthy content, which
is the same condition upstream uses. A real config is a non-empty dict, so an ordinary
load still asks for one file.

The reader had the mirror-image bug. It took the union of every config present in the
folder, which refused a repository whose router_config.json is clean because an unrelated
config.json sat beside it, a load upstream completes. It now stops at the first real
config too, so both loops and upstream agree.

Second, the gate and the load resolved the repository separately. With no revision, or a
branch, a repository that advances between the two requests is checked on one snapshot
and loaded from another, which passes the gate on files that are not the files that run.
_check_modules_json_types now returns the commit it validated and both delegated routes
pin the load to it. This costs no request: _module_path already resolves through
hf_hub_download, so the commit is in the path it returned, and it is the snapshot the
load would have reached anyway. It reports "" for a local directory, for a revision that
is not an immutable commit, and when there is no modules.json, and the load is then left
exactly as it was. An explicit revision is never overridden.

Evidence. Base and head on the same host, loading sentence-transformers/all-MiniLM-L6-v2
through FastSentenceTransformer.from_pretrained with the revision ST receives traced:
base passes None, head passes 1110a243fdf4706b3f48f1d95db1a4f5529b4d41, which is the
repository's current commit, and the embeddings are identical in both arms
(digest a1159543dc99e128, shape (2, 384)). Against the real Hub the reported commit
matches the tip on a cold cache and on a warm one, and that pinned snapshot loads and
encodes.

Eleven new tests. The fallback test keeps the remote files and the cache in separate
directories, because writing both into one folder lets the reader find the fallback on
disk and refuse for a reason that has nothing to do with whether it was fetched: with
that separated, the previous head does not raise at all. 47 pass here, 82 under the CUDA
spoof alongside the vllm_compat files, and the other two sentence-transformers suites are
unchanged at 57.
@danielhanchen

Copy link
Copy Markdown
Member Author

@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: 1a40d22948

ℹ️ 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".

Comment on lines +1668 to +1671
for load_path in dict.fromkeys(folders):
FastSentenceTransformer._check_module_config_class_refs(
load_path, class_ref, model_name, False, module_class
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Run config validation on sentence-transformers 5.5

On sentence-transformers 5.5, this newly added call does not actually validate the downloaded config: _check_module_config_class_refs returns immediately whenever sentence_transformers.util.import_module_class exists, even though 5.5 exports that helper while its Dense, Router, and related loaders still resolve config class references without a gate. The tests conceal this by deleting the attribute in _simulate_pre_six; with an actual 5.5 installation, an external activation_function or types entry therefore still executes with trust_remote_code=False.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct, and it is the one of the three I am not fixing here, because #12444 already does and it merges first.

That branch replaces the hasattr(st_util, "import_module_class") early return in _check_module_config_class_refs with a version test, for the reason you give: 5.5 exports the helper while Dense and Router still resolve config class references ungated. _check_delegated_module_config on this branch already uses the version rather than the attribute, with a comment saying why, so the inconsistency is that I fixed it in one of the two places. This PR is stacked behind #12444 for exactly this, and I will merge main in once that lands rather than duplicate the change here and create a conflict with it.

Your point about the tests concealing it stands on its own and I will act on it in the same pass. _simulate_pre_six deletes the attribute as well as setting the version, which on this branch is what makes the test work at all, so the test passes for a reason production does not have. Once the gate keys off the version, the deletion is unnecessary and misleading, and dropping it is what makes these tests exercise the real condition.

Comment thread unsloth/models/sentence_transformer.py Outdated
Comment on lines +1536 to +1538
token = token,
cache_dir = cache_dir,
revision = revision,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Validate module configs from the resolved snapshot

When revision is omitted or names a mutable branch, modules.json may resolve to commit A, but this passes the original revision into the subsequent config downloads, allowing them to resolve commit B. The caller then pins the delegated load to A, so a clean config from B can be validated while A's unchecked activation_function or types value is loaded and executed. Pass the resolved commit used for modules.json into these config checks as well.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Right, and this one is my own doing: the pin I added last commit closed one half of the race and left this half worse than it found it. Fixed in fa4e57e.

Every read after modules.json now goes to the commit that resolution produced. modules.json itself is still fetched on the caller's revision, because that is the request that resolves the commit in the first place; config_revision carries it from there into _resolve_module_class and _check_delegated_module_config.

test_the_module_configs_are_read_from_the_validated_snapshot asserts the revision every single download receives, not just that the call succeeds. On the previous head the first entry is ("modules.json", "main") and so is every entry after it, which is the inversion you describe.

Comment thread unsloth/models/sentence_transformer.py Outdated
Comment on lines +2053 to +2054
if _validated and not revision:
st_kwargs["revision"] = _validated

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Pin explicitly named mutable revisions too

When a caller supplies a mutable revision such as revision="main", this condition discards the resolved commit returned by validation, so SentenceTransformer resolves the branch again and can load a different modules.json; the fast-encoder route has the same condition. Fresh evidence after the earlier pinning fix is that both call sites explicitly restrict pinning to falsey revisions, leaving the explicit mutable-branch case vulnerable to the same validation/load race.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Agreed, and my reasoning for that condition was wrong rather than merely incomplete. I had restricted the pin on the grounds that an explicit revision is the user's choice to respect. But the commit the gate reports IS what their revision resolved to, so pinning to it does not override anything; it only removes the second resolution. An explicit commit resolves to itself and the pin is a no-op.

Fixed in fa4e57e on both routes, delegated and fast-encoder.

Traced base against head on the same host, loading sentence-transformers/all-MiniLM-L6-v2 with revision = "main": base passes "main" to SentenceTransformer, head passes 1110a243fdf4706b3f48f1d95db1a4f5529b4d41, and the embeddings are identical in both arms (digest a1159543dc99e128). That half is not unit-testable without a full load, so the unit test I added alongside it guards the contract the call site depends on, and says so rather than implying it covers the condition.

Both of these were created by the pinning change in the last commit, which closed one
half of the race and left the other half worse than it found it.

The module config reads were still issued on the caller's revision. So modules.json could
resolve commit A while each module config resolved commit B, and since the load is pinned
to A, a clean config in B was validated while A's unchecked activation_function or types
value was the one that ran. Every read after modules.json now goes to the commit that
resolution produced. modules.json itself is still fetched on the caller's revision,
because that is what resolves the commit in the first place.

The pin was also restricted to a falsey revision, on the reasoning that an explicit one is
the user's choice. That left revision = "main" racing exactly as a missing revision did,
and the reasoning was wrong: the commit reported by the gate IS what the caller's own
revision resolved to, so pinning to it does not override anything, it only removes the
second resolution. An explicit commit resolves to itself and the pin is a no-op.

Evidence for the second one is a traced base-against-head run on the same host, loading
sentence-transformers/all-MiniLM-L6-v2 with revision = "main": base passes "main" to
SentenceTransformer, head passes 1110a243fdf4706b3f48f1d95db1a4f5529b4d41, and the
embeddings are identical in both arms (digest a1159543dc99e128). The first one is covered
by test_the_module_configs_are_read_from_the_validated_snapshot, which asserts the
revision every download receives and fails on the previous head with "main" where the
commit belongs.

Three tests. One fails on the previous head. The other two pass on it, and are labelled as
what they are: the branch-resolves-to-a-commit case guards the contract the call site
depends on rather than the condition that was wrong, since that half needs a full load,
and the immutable-revision case is a negative control. 50 pass in this file, 107 across
the three sentence-transformers suites, 87 under the CUDA spoof.
@danielhanchen

Copy link
Copy Markdown
Member Author

@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: fa4e57efa6

ℹ️ 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".

Comment thread unsloth/models/sentence_transformer.py Outdated
Comment on lines +1423 to +1425
if cached is not None:
# The sentinel recording that the hub already answered "no such file".
return None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Pin the snapshot when modules.json is absent

When a mutable revision currently has no modules.json, this cached-absence branch returns without recording the commit in resolved. Validation of commit A therefore returns an empty revision, and if the branch advances to commit B that adds a malicious modules.json before the delegated load, sentence-transformers < 6 imports B's unchecked module type. Fresh evidence after the earlier pinning fix is that the negative-cache path never populates resolved; preserve the resolved cache ref/commit and pin confirmed-absence results too.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 5693840, and the cached branch turned out to be worse than a missing pin.

It ran before the download and answered "this repository has no modules.json" out of the local cache, where a recorded absence is keyed to whatever commit the refs file points at. For a branch that is a stale pointer, so the question was decided against a snapshot nobody had checked was current, and no commit was reported either. The cache is now consulted only from the unreachable handler, which is the case it is actually needed for: offline with a recorded absence is still not a refusal, and still reads the same cache hf_hub_download reads.

With that reordering the 404 comes from the hub against a named revision, which is what makes resolving that revision to its commit sound. One request, only on the path where a repository has no modules.json, and a failure degrades to not pinning rather than to a broken load, since the guard had already decided there was nothing to check and must not start raising.

test_a_confirmed_absent_modules_json_still_pins_the_load fails on the previous head with an empty commit where the resolved one belongs. The other two I added hold on the previous head too and are labelled as such: one is a negative control that the new request cannot break a load, and the recorded-absence one guards the offline contract rather than the reordering.

Separately, 81a45d4 merges main now that #12444 has landed, which closes out the version-fork item above. Two things worth noting in it. _simulate_pre_six no longer deletes util.import_module_class, so these tests exercise the real condition rather than one the deletion manufactured, which is your point and it was a good one. And test_the_installed_sentence_transformers_gate_is_not_second_guessed is removed: it asserted the check is a no-op on 6, which was true while the early return existed, and #12444 applies the prefix rules on every version instead, so it encoded behaviour that was deliberately changed. The conflict was in the test file where both branches had appended; I took this branch's file, main's version of the three tests #12444 rewrote for the per-class dispatch, and the ten tests only main had, so nothing was dropped as a merge artefact.

danielhanchen added a commit that referenced this pull request Oct 1, 2026
Four more under-reports, two of them left behind by the previous round's own fixes.

Call resolution returned the first target that resolved. The alias fix made one name mean
several modules for the source and sink tables, but not here, so with `codec` bound to a
clean parser in one function and a dirty one in another, the clean one was chosen for
both and a value from the dirty parser reached a sink unreported. Resolution returns every
candidate now and all of them are analysed, which is the same fail-closed choice the
tables already make. That also removed the single-target helper rather than leaving it
beside the list version for someone to reach for by accident.

The qualname was stripped using `files[file]`, which keeps only the shorter of the two
names a file indexed under both roots has. So `from studio.backend.utils.parser import
parse` produced an empty qualname, the callee resolved to no function at all, and taint
returned by a backend helper never reached a caller that imported it by the full path.
Resolution now reports the spelling that actually matched, which is the only thing that
can be stripped correctly.

`execute(*json.loads(blob))` was treated as a single positional and tainted only the first
parameter, so a parsed second element reaching subprocess.run was reported nowhere. A
starred argument binds every parameter from its position on, for the same reason a
starred dictionary binds every named one.

`Parser.parse(blob)` could not resolve at all. The method is already indexed as
`Parser.parse`, but the head is neither an import nor self, so the callee was rejected
and a local static or class method sat outside the analysis entirely.

Three baseline additions in unsloth, all in _resolve_module_class, where the modules.json
type reaches import_from_string. These are the flow #12446 hardens and they are guarded:
the first is reached only for a class_ref already starting with "sentence_transformers.",
and the other two sit after the consent check, so they run only with trust_remote_code.
This checker does not model validators by design, so a guarded sink is expected to appear
and be justified rather than disappear. Worth noting that it took four rounds of fixes
before the analysis could see the very flow the other PRs in this series exist for.
unsloth_zoo needs no baseline change.

Four tests, each verified to fail on the previous head by assertion. The reused-alias one
names its modules a_clean and z_dirty so the clean binding sorts first, which is the order
that used to lose. 63 pass in each repo, both self-tests pass, both gates are clean.
A repository with no modules.json validated clean and reported no commit, so the load
went unpinned and a branch that gains one before the load brings in a module type nothing
checked. Absence is the thing being validated here, so it has to be pinned exactly like a
presence.

The cached-absence branch was worse than that. It ran before the download and answered
"this repository has no modules.json" out of the local cache, where a recorded absence is
keyed to whatever commit the refs file points at, which for a branch is a stale pointer.
So the question was decided against a snapshot nobody had checked was current, and no
commit was reported either. The cache is now consulted only from the unreachable handler,
which is the case it is actually needed for: offline with a recorded absence is still not
a refusal and still reads the same cache hf_hub_download reads, so an offline load behaves
as it did.

With that reordering the 404 comes from the hub against a named revision, which makes
resolving that revision to its commit sound. That costs one request, only on the path
where a repository has no modules.json, and a failure degrades to not pinning rather than
to a broken load: the guard had already decided there was nothing to check, so it must not
start raising.

Three tests. test_a_confirmed_absent_modules_json_still_pins_the_load fails on the
previous head with an empty commit where the resolved one belongs. The other two hold on
the previous head as well and are what they look like: one is a negative control that the
new request cannot break a load, and the recorded-absence one guards the offline contract
and the cache_dir rather than the reordering. The existing cache test moved with the code
it was testing, and covers more now, since it drives the unreachable path rather than a
lookup that happened before anything else.

52 pass in this file, 109 across the three sentence-transformers suites, 89 under the CUDA
spoof.
#12444 landed, so the config check no longer keys its early return off
util.import_module_class and the dependency this branch was stacked behind is gone.

Conflict was in tests/test_st_modules_json_trust_gate.py, where both branches appended
tests to the same file. Resolved by taking this branch's file, taking main's version of
the three tests #12444 rewrote for the per-class dispatch, and appending the ten tests
only main has. No test was dropped as a merge artefact.

Two deliberate changes on top of the resolution.

_simulate_pre_six no longer deletes util.import_module_class. That deletion was how these
tests passed at all while the check keyed off the attribute, which meant they passed for a
reason production did not have and hid exactly the 5.5 gap that made the attribute a bad
test in the first place. Setting only the version is what makes them exercise the real
condition.

test_the_installed_sentence_transformers_gate_is_not_second_guessed is removed. It
asserted the check is a no-op on sentence-transformers 6, which was true when the early
return existed. #12444 applies the prefix rules on every version instead, so the test now
encodes behaviour that was deliberately changed, and main's
test_the_check_does_not_key_off_the_import_module_class_attribute asks the same question
the right way round.

Also folded the two stacked comments above _MODULE_CONFIG_CLASS_REFS into one. The merge
left #12444's explanation of why the rules are unconditional directly above this branch's
explanation of why they are keyed by class, which is one decision described twice.

63 pass in this file, 120 across the three sentence-transformers suites, 100 under the
CUDA spoof.
@danielhanchen

Copy link
Copy Markdown
Member Author

@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: 81a45d42ab

ℹ️ 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".

Comment thread unsloth/models/sentence_transformer.py Outdated
Comment on lines +1538 to +1541
from huggingface_hub import HfApi
sha = HfApi(token = token).model_info(model_name, revision = revision).sha
if isinstance(sha, str) and len(sha) == 40:
resolved["revision"] = sha.lower()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Pin the commit that actually returned the 404

When revision is a mutable branch, this separate model_info request can resolve a newer commit than the preceding modules.json request: commit A can return the validated 404, the branch can advance to commit B containing an unchecked custom module, and this code then pins the delegated load to B. Fresh evidence after the prior absence-pinning fix is that the selected SHA comes from a second branch resolution rather than the response that established absence; use the 404 response's commit metadata or resolve a commit first and perform the absence check against that immutable revision.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Right, and it is the same mistake as the one two rounds ago: I closed a race by resolving the commit a second time, which just moved the window rather than removing it. Fixed in 1e4a5dc.

The commit now comes off the 404 response itself. I checked this against the real hub rather than assuming: hf_hub_download for a missing file raises RemoteEntryNotFoundError, which subclasses HfHubHTTPError and so carries .response, and the 404 headers include x-repo-commit with the repository's commit. So the response names exactly the commit whose answer was "no modules.json", there is no second resolution to disagree with it, and it costs no request at all, which is one fewer than the version you are commenting on.

Only the remote variants of the error carry a response, and a proxy can strip the header, so a missing one leaves the load unpinned rather than guessing. test_a_confirmed_absent_modules_json_still_pins_the_load now fails the run if anything resolves the commit a second time, so it pins the mechanism and not just the value, and that is how it fails on the previous head.

Comment on lines +1705 to +1709
config_file_name = getattr(module_class, "config_file_name", None)
if isinstance(config_file_name, str):
config_names.append(config_file_name)
else:
config_names.append("config.json")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Fetch the legacy module config filename

On sentence-transformers 3.x/4.x, a remote WordEmbeddings class has no config_file_name attribute but its loader opens wordembedding_config.json; this fallback instead requests only config.json. If that unused file returns 404, folders stays empty and validation succeeds, after which the delegated loader reads wordembedding_config.json and imports its unchecked tokenizer_class with trust_remote_code=False. Apply _LEGACY_MODULE_CONFIG_FILES here as the local config checker already does.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct, and a good catch given the table was sitting right there. Fixed in 1e4a5dc: the delegated path consults _LEGACY_MODULE_CONFIG_FILES in the no-config_file_name branch, which is the same thing the local checker already did.

The asymmetry is what made it easy to miss. config_file_name exists from 5, so on a current install the attribute is always present and that branch is dead; it only matters on 3.x and 4.x, which is exactly where the gate has the most work to do because upstream does none.

test_the_delegated_check_fetches_the_legacy_config_filename uses a class with no config_file_name and a repository carrying only wordembedding_config.json, with the remote files and the cache in separate directories so the reader cannot find the file some other way. It does not raise at all on the previous head.

Two holes, one of them in the absence pin added last commit.

That pin resolved the commit with a second model_info request, which resolves the branch
again and can answer with a newer commit than the one whose 404 established the absence.
Pinning to that loads a snapshot nothing checked: the same inversion as validating one
commit and loading another, moved one step along. The commit now comes off the 404
response itself. hf_hub_download's 404 carries x-repo-commit, verified against the real
hub, so the response names exactly the commit that answered "no modules.json" and it costs
no request at all, one fewer than before. Only the remote variants of the error carry a
response and a proxy can strip the header, so a missing one leaves the load unpinned
rather than guessing.

Second, the delegated config check built its filename list from config_file_name and fell
back to config.json alone. That attribute only exists from sentence-transformers 5, so on
3.x and 4.x a WordEmbeddings has no such attribute while its loader still opens
wordembedding_config.json. The check asked for config.json, got a 404, had nothing to
look at, and passed, after which the loader read the legacy file and imported its
tokenizer_class with trust_remote_code=False. _LEGACY_MODULE_CONFIG_FILES already existed
for exactly this and the local checker already consulted it; the delegated path did not.

Three tests. The absence-pin one now fails the run if anything resolves the commit a
second time, so it pins the mechanism and not just the value, and on the previous head it
fails on that. The legacy-filename one does not raise at all on the previous head, which
is the bypass. The third is a negative control: a 404 with no commit header, or an older
hub whose error carries no response, must leave an unpinned load rather than raise out of
a guard that had already decided there was nothing to check.

64 pass in this file, 121 across the three sentence-transformers suites, 101 under the
CUDA spoof.
@danielhanchen

Copy link
Copy Markdown
Member Author

@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: 1e4a5dce48

ℹ️ 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".

Comment thread unsloth/models/sentence_transformer.py Outdated
modules_json_path,
exception,
)
return validated

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Fail closed when the downloaded manifest cannot be parsed

On sentence-transformers < 6 with trust_remote_code=False, a transient OSError or JSON read failure reaches this return and treats the manifest as validated. The delegated SentenceTransformer immediately opens the same manifest again; if that retry or re-download succeeds, it can import an unchecked custom type. Fresh evidence beyond the resolved fetch-error path is this separate post-download exception handler, which should refuse the load rather than return the resolved revision.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Agreed, and it is the same rule I had already applied to the fetch error and then failed to apply one handler further down. Fixed in dacc89b.

"Could not check" is not "nothing to check": the file is in hand and still unreadable, and the delegated loader opens that same path immediately afterwards, so a transient read error followed by a retry that succeeds there imports a type nothing looked at. It refuses below 6.0 only, since above that upstream gates the type itself and refusing would break a load that is already safe.

While there I wrote down why the neighbouring non-list case stays a pass rather than becoming a refusal: a modules.json that is not a list names no modules, and the loader iterates it too, so upstream cannot build a module from it either. That one is not a bypass, and the comment now says so rather than leaving the asymmetry unexplained. test_an_unparseable_manifest_refuses_rather_than_passing does not raise at all on the previous head, and there are two negative controls beside it.

pytest.importorskip("sentence_transformers")

from unsloth import FastSentenceTransformer # noqa: E402
from unsloth import FastSentenceTransformer

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Restore the optional-dependency skip before importing the tests

When this test file is collected from a core-only installation, sentence-transformers is not guaranteed to be installed, yet multiple tests immediately call helpers that import it, so the suite now fails with ModuleNotFoundError instead of skipping this optional integration. The dedicated CI jobs install the extra, but ordinary core test runs do not necessarily do so; restore the module-level pytest.importorskip("sentence_transformers") before importing FastSentenceTransformer.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct, and this one is a regression I introduced, not a pre-existing gap. Restored in dacc89b with main's comment, before the unsloth import.

Worth being precise about how it happened, because the check I ran was the wrong check. Resolving the merge conflict in this file, I rebuilt it from the three merge stages and verified that no test function had been dropped, comparing the sets of top-level function definitions on each side. That says nothing about module-level statements, and the guard is one, so it disappeared silently and every local run still passed because sentence-transformers is installed here. Comparing module-level statements as well is what that resolution needed.

danielhanchen added a commit that referenced this pull request Oct 1, 2026
Lint CI was failing for a real reason, not a flake. The check runs against main merged
with this branch, and #12444 has since landed changes to sentence_transformer.py, so the
three reviewed sinks in that file no longer matched their allowances: the enclosing
functions changed, and the enclosing function's digest is part of the key by design, so
editing around a reviewed sink reopens it. That is the gate behaving as intended, pointed
at its own baseline.

Merged cleanly, no conflicts. Regenerating moves two entries and adds one.

The addition is _import_sentence_transformers_class, which #12444 introduced and nothing
had looked at. Reviewed rather than waved through: every dotted part is checked to be an
identifier before anything is imported, callers only reach it for a class_ref already
starting with "sentence_transformers.", and the resolved object has to be a torch.nn.Module
subclass defined inside that package and carrying a load attribute. The import itself does
run before that post-check, which is why it is reported, but the prefix pins it to the
installed package, so what can execute is module-level code inside sentence_transformers.

Worth noting for whoever merges this last: a baseline keyed on the enclosing function
means this branch has to be re-merged and regenerated after any PR that touches a file
with a reviewed sink in it. #12446 is still open and touches this same file, so this will
need one more pass once it lands.

69 tests pass, the self-test passes, and the gate exits 0 on the merged tree.
@danielhanchen

Copy link
Copy Markdown
Member Author

Source lint on the new head 1e4a5dce fails on this PR's own change, not on main:

[BLOCKER] tests/test_st_modules_json_trust_gate.py: HOISTED-IMPORT-UNUSED 'types' (['import:types']) added but unused

The import types added to tests/test_st_modules_json_trust_gate.py is never used. Dropping it (or using it where it was meant to be used) should clear the check. unsloth/models/sentence_transformer.py is clean.

Three things, one of them a regression I introduced in the merge.

The post-download read of modules.json swallowed OSError and a JSON error and returned as
though there were nothing to check. The file is in hand and still unreadable, and the
delegated loader opens that same path immediately afterwards, so a transient read error
followed by a retry that succeeds there would import a type nothing ever looked at.
"Could not check" is not "nothing to check", which is the rule the fetch error already
followed; this handler now follows it too. Only below 6.0, where sentence-transformers
does not gate the type itself, so a load that is already safe is not broken.

A modules.json that parses but is not a list stays a pass rather than a refusal, and the
reason is now written down: it names no modules, and the loader iterates it as well, so
upstream cannot build a module from it either.

The module-level pytest.importorskip("sentence_transformers") was missing, and that is on
me. My merge resolution rebuilt this file from the three merge stages and I verified that
no test function had been dropped, which was the wrong check: it said nothing about
module-level statements, and the guard is one. Restored with main's comment, before the
unsloth import.

Also removed an unused `import types`, which Lint CI caught. It was there for a fake
HfApi in the absence-pin test, and that test now reads the commit off the 404 response
instead, so the import outlived its only use.

Three tests. The refusal one does not raise at all on the previous head. The two
tolerance cases pass on it as well and are negative controls: 6.0 and above must not
start refusing, and a non-list must not either.

67 pass in this file, 124 across the three sentence-transformers suites, 104 under the
CUDA spoof.
@danielhanchen

Copy link
Copy Markdown
Member Author

@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: dacc89be17

ℹ️ 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".

Comment thread unsloth/models/sentence_transformer.py Outdated
Comment on lines +1546 to +1551
if cached is not None:
# Unreachable, and the cache already recorded that this repo has no
# modules.json. Offline that is the whole answer and the load can only use
# the cache too, so this is not a refusal. No commit is reported, because
# none was resolved and the recorded one is a stale local pointer.
return None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Refuse a stale cached absence after a failed lookup

On sentence-transformers < 6, when the live modules.json request fails transiently but the cache contains a negative entry for an older commit of a mutable revision, this returns success with no pinned revision. The immediately following SentenceTransformer request can recover and load the current branch, including a newly added unchecked custom module. Fresh evidence after the prior fail-closed fix is this LocalEntryNotFoundError branch explicitly accepting a stale negative entry; recover its cached commit and pin the load, or fail closed when that commit cannot be established.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

You are right, and the broken part was my reasoning rather than an oversight. The comment on that branch said that offline the load can only use the cache too, so returning success with no pin was safe. That premise is false: this request failed, not every request. The delegated load runs immediately afterwards and can recover, fetching the current branch, which may have gained a module type since the cached answer was recorded.

Fixed in bdfdc13, taking the first of your two options with the second as the fallback. The load is pinned to the commit the cache holds for this revision, recovered from a file that lives in the same snapshot through the same try_to_load_from_cache lookup, so no cache internals and no network. That snapshot is the one whose absence was recorded, which makes the load consistent with what was checked, and offline it is what would have been served anyway. When no commit can be recovered there is nothing that makes the load match, so it fails closed below 6.0, which is the rule every other branch that cannot establish an answer already follows.

Three tests replace the one that encoded the old behaviour, and that replacement is the point: the old test asserted an empty revision and no refusal, so it was pinning down exactly the gap you found. The pin case asserts the commit and keeps that test's original purpose, that the lookup reads the cache hf_hub_download reads rather than one of our own choosing. The no-commit case asserts the refusal. The third is a negative control, since from 6.0 upstream refuses the type itself and refusing here would only break a load that is already safe. The first two fail on the previous head, one on the commit and one on not raising.

The unreachable branch returned success with no pin when the cache already recorded that
a repository has no modules.json. My reasoning in that comment was that offline the load
can only use the cache too, and that is wrong: this request failed, not every request. The
delegated load runs immediately afterwards and can recover, fetching the current branch,
which may have gained a module type since the cached answer was recorded. Success with no
pin let exactly that through.

The load is pinned to the commit the cache holds for this revision now, recovered from a
file that lives in the same snapshot through the same public lookup. That snapshot is the
one whose absence was recorded, so the load matches what was checked, and offline it is
what would have been served anyway. When no commit can be recovered there is no way to
make the load match, so it fails closed below 6.0, which is the rule every other branch
that cannot establish an answer already follows.

Three tests replace the one that encoded the old behaviour. The pin case asserts the
commit and keeps the original point of that test, that the lookup reads the cache
hf_hub_download reads rather than one of our own choosing. The no-commit case asserts the
refusal. The third is a negative control: from 6.0 upstream refuses the type itself, so
refusing here would only break a load that is already safe. The first two fail on the
previous head, one on the commit and one on not raising.

69 pass in this file, 126 across the three sentence-transformers suites, 106 under the
CUDA spoof.
@danielhanchen

Copy link
Copy Markdown
Member Author

@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: bdfdc130d9

ℹ️ 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".

Comment on lines +1623 to +1627
else:
logging.debug(
"Unsloth: the 404 for %s carried no commit, so the load is not pinned.",
model_name,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Fail closed when a 404 has no commit header

On sentence-transformers < 6, if a proxy or Hub response omits x-repo-commit, this branch accepts the absence while leaving a mutable revision unpinned. The subsequent SentenceTransformer request can resolve that branch again after it gains a modules.json containing an unchecked custom type. Fresh evidence after the earlier pinning fix is this explicit headerless fallback; it should refuse below 6 or otherwise establish an immutable commit before returning.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in db1cfa0: it refuses below 6.0, with one escape that costs nothing.

When the caller already named an immutable commit, the 404 was answered at that commit and there is nothing for a second resolution to disagree with, so the revision itself is the pin and no header is needed. That keeps a header-stripping proxy from forcing a refusal on anyone who pinned their load properly, and the message tells a caller who named a branch to name a commit instead.

Three tests: the refusal below 6, the explicit-commit escape, and a renamed negative control for 6.0 and above. The first two fail on the previous head, one on not raising and one on the commit.

Comment on lines +1882 to +1885
except (OSError, ValueError):
# Unreadable is not "checked": let the fallback be fetched too, and
# leave the refusal to the reader below, which sees both files.
content = None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Refuse unreadable delegated module configs

On sentence-transformers < 6, a transient read/JSON error here does not actually lead to the claimed refusal: _check_module_config_class_refs catches the same errors and continues. If both validation reads fail but the delegated loader's retry succeeds, a Dense activation, WordEmbeddings tokenizer, or Router type can still be imported without consent. Treat an unreadable downloaded config as unverifiable and fail closed rather than proceeding to the loader.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

You are right, and the specific thing you caught is that my error message promised a refusal the code did not perform. That promise was written for the fetch path; this is the read, one function further on, where _check_module_config_class_refs caught OSError and a JSON error and skipped the file. So a message telling the user this refuses rather than loading unchecked was accurate about one half and false about the other.

Fixed in db1cfa0. Present and unreadable is not absent: the loader opens that same path next and its read may succeed, so it refuses below 6.0. Above that upstream resolves these through its own gate and refusing would only break a load that is already safe, which is the negative control beside it.

test_an_unreadable_module_config_refuses_rather_than_skipping does not raise at all on the previous head.

Two more fail-open paths, both the same shape as the ones already closed: a branch that
could not establish an answer returned as though there were nothing to check.

A 404 whose response carries no x-repo-commit left a mutable revision unpinned, and the
delegated request then resolves that branch again and can get one which has since gained a
modules.json. It refuses below 6.0 now, with one escape that costs nothing: when the
caller already named an immutable commit, the 404 was answered at that commit and there is
nothing for a second resolution to disagree with, so the revision itself is the pin and no
header is needed. A proxy that strips the header therefore only forces a refusal for a
caller who named a branch, and the message says to name a commit.

The unreadable-config path did not refuse at all, despite the message I wrote claiming it
would. That promise was about the fetch; this is the read, one function further on, where
_check_module_config_class_refs caught OSError and a JSON error and skipped the file. The
loader opens that same path next and its read may succeed, so a Dense activation, a
WordEmbeddings tokenizer or a Router type could be imported with nothing having checked
it. Present and unreadable is not absent, so it refuses below 6.0.

Four tests. Three fail on the previous head, two on not raising and one on the commit.
The fourth, and the renamed one beside it, are negative controls for 6.0 and above, where
upstream resolves these through its own gate and refusing would only break a load that is
already safe.

73 pass in this file, 130 across the three sentence-transformers suites, 110 under the
CUDA spoof.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: db1cfa0af0

ℹ️ 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".

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant