Skip to content

perf(models-config): content-hash auth-profiles + models.json drift detection - #73260

Closed
zeroaltitude wants to merge 28 commits into
openclaw:mainfrom
zeroaltitude:perf/models-config-cache-fingerprint
Closed

zeroaltitude wants to merge 28 commits into
openclaw:mainfrom
zeroaltitude:perf/models-config-cache-fingerprint

Conversation

@zeroaltitude

@zeroaltitude zeroaltitude commented Apr 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Splits the cache-fingerprint half of #72869 into a standalone PR.

This PR replaces mtime-based cache key inputs with content-based hashes for the ensureOpenClawModelsJson implicit-provider-discovery cache, plus a second-factor models.json content hash that catches external edits / partial corruption / sibling-process writes between cache hits. Includes the security hardening findings raised by Aisle on the original combined PR.

Why content hashes

The previous mtime-based key invalidated on every OAuth token refresh because auth-profiles.json gets rewritten with new access/refresh timestamps even when the set of available providers does not change. Same for models.json mtime: the file is the OUTPUT of this function, so each call observed its own write and invalidated the next call.

Now:

  • auth-profiles.json: SHA-256 over a stable serialization that strips volatile OAuth session fields (access, refresh, expires*, issuedAt, refreshed/lastChecked/lastRefresh/lastValidatedAt). Token rotation no longer invalidates; structural changes (added/removed profiles, rotated static type:token credentials) still do.
  • models.json: NOT included in the input fingerprint (would cause self-invalidation). Instead its content hash is captured at write time and stored alongside the readyCache entry. Every cache check recomputes the file hash and compares; any external edit invalidates and forces re-plan.

Security hardening (Aisle review on PR #72869)

Severity Finding Fix
🟠 High #1 CWE-59 symlink-following chmod ensureModelsFileMode now lstats first; refuses to chmod symlinks or non-regular files
🟡 Med #3 CWE-1321 prototype pollution Object.create(null) for stripped result + explicit __proto__/prototype/constructor filter
🟡 Med #4 DoS via unbounded fingerprinting MAX_AUTH_PROFILES_BYTES = 8 MiB (raw-hash above cap), MAX_AUTH_PROFILES_DEPTH = 64 with depth-marker
🟡 Med #5 CWE-312 secrets in cache buildModelsJsonFingerprint returns SHA-256 hex of canonical payload instead of raw stable-stringified

Token-rotation correctness

token is intentionally NOT in AUTH_PROFILE_VOLATILE_FIELDS even though OAuth-style token fields rotate. Profiles with type: "token" use the literal token key as a long-lived static credential, and stripping it would mask real auth-state changes when a user rotates that credential. Documented inline.

Tests

Two tests in models-config.fingerprint-cache.test.ts:

  • does not invalidate the cache when OAuth session fields rotate (rotates access/refresh/expires; cache stays valid)
  • DOES invalidate the cache when a static type:token credential rotates (rotates the literal token field; cache invalidates)

Existing fingerprint-cache test suite still passes.

Compatibility

MODELS_JSON_STATE.readyCache value shape extended with modelsJsonHash: { fingerprint, modelsJsonHash, result }. All three plan return paths (skip/noop/write) capture the post-write hash. The refreshedFingerprint re-key path forwards modelsJsonHash through unchanged.

Related

Real behavior proof

  • Behavior or issue addressed: Models-config cache fingerprint fail-closed behavior for unhashable/oversize models.json and auth-profiles.json from PR perf(models-config): content-hash auth-profiles + models.json drift detection #73260.

  • Real environment tested: Local OpenClaw topic branch perf/models-config-cache-fingerprint at 05fda3d839, isolated temporary agent directory, production ensureOpenClawModelsJson invoked through a tsx runtime driver with no Vitest mocks.

  • Exact steps or command run after this patch: Ran the proof driver after the patch to warm cache on a small auth profile, grow auth-profiles.json past the 8 MiB cap, repeat calls with byte-identical and swapped oversize contents, restore a small file, then exercise oversize and symlinked models.json.

  • Evidence after fix: Full copied runtime trace is in the PR comment: perf(models-config): content-hash auth-profiles + models.json drift detection #73260 (comment)

    Excerpt of copied live output:

    ensureOpenClawModelsJson warm cache hit: ~1 ms
    auth-profiles.json > 8 MiB: re-plan ~150-200 ms on every call
    oversize byte-identical repeat: re-plan, cache size unchanged
    oversize same-byte-length swapped content: re-plan, cache size unchanged
    restored small auth-profiles.json: cache hit restored (~1 ms)
    oversize models.json: full plan + rewrite
    symlinked models.json: full plan + rewrite
    
  • Observed result after fix: Uncacheable models content never matches cached state, oversize auth profiles bypass the ready cache instead of collapsing to a stale fingerprint, and restoring cacheable content re-enables fast hits.

  • What was not tested: Nothing else for this PR's changed behavior beyond the isolated local runtime proof and supplemental automated validation.

Current-head token-profile expiry proof (2026-05-12)

  • Behavior or issue addressed: Token-profile expiry invalidation for PR perf(models-config): content-hash auth-profiles + models.json drift detection #73260. A static type: "token" profile changing from valid to expired must change the models-config ready-cache fingerprint; OAuth session-field rotation, including expires, must remain volatile and keep the same cache key.
  • Real environment tested: Local OpenClaw topic branch perf/models-config-cache-fingerprint at 1d1e11d64d, isolated temporary agent directories under /tmp, production ensureOpenClawModelsJson, production MODELS_JSON_STATE.readyCache, real on-disk auth-profiles.json and models.json; no Vitest and no mocks of the models-config cache seam.
  • Exact steps or command run after this patch: pnpm tsx scripts/proof-73260-token-profile-expiry.ts
  • Evidence after fix:
    Proof root: /tmp/openclaw-73260-token-proof-AsCf46
    [1/3] oauth-session-fields-are-volatile
        cache key stayed stable: dd54f163d6f5ace2
    [2/3] token-expiry-invalidates-cache
        valid-token key:   576ba05d6b45bd0f
        expired-token key: 623b9d4bb64832e5
    [3/3] expired-token-cache-stabilizes
        cache keys after repeat expired call: 2
    
    All runtime assertions passed.
    
  • Observed result after fix: OAuth access/refresh/expiry rotation kept one stable cache key, while static token expiry valid-to-expired produced a distinct cache key and then reused that expired-state key on a repeat call.
  • What was not tested: Live provider network discovery. The proof intentionally scopes provider discovery to an empty provider-id list so it can exercise the production cache/fingerprint/runtime file behavior without external network calls.

…etection

Replaces mtime-based fingerprinting with content-based hashes for the
implicit-provider-discovery cache key, plus a second-factor models.json
content hash that catches external edits / partial corruption / sibling
process writes between cache hits. Includes the security hardening
findings raised by Aisle on the original combined PR (openclaw#72869).

# Why content hashes

The previous mtime-based key invalidated on every OAuth token refresh
because auth-profiles.json gets rewritten with new access/refresh
timestamps even when the set of available providers doesn't change.
Same for models.json mtime: the file is the OUTPUT of this function,
so each call observed its own write and invalidated the next call.

Now:

- auth-profiles.json: SHA-256 over a stable serialization that strips
  volatile OAuth session fields (access, refresh, expires*, issuedAt,
  refreshed/lastChecked/lastRefresh/lastValidatedAt). Token rotation
  no longer invalidates; structural changes (added/removed profiles,
  rotated static type:token credentials) still do.

- models.json: NOT included in the input fingerprint (would cause
  self-invalidation). Instead its content hash is captured at write
  time and stored alongside the readyCache entry. Every cache check
  recomputes the file hash and compares; any external edit /
  corruption / tamper invalidates the cache and forces re-plan.

# Security hardening (Aisle review on PR openclaw#72869)

- 🟠 High #1 (CWE-59 symlink-following chmod): ensureModelsFileMode
  now lstats first and refuses to chmod symlinks or non-regular files.
  Closes the attack where a symlink at ${agentDir}/models.json points
  at a sensitive owned file and our best-effort chmod follows.

- 🟡 Med #3 (CWE-1321 prototype pollution): stripAuthProfilesVolatile
  now uses Object.create(null) for the result and explicitly filters
  __proto__ / prototype / constructor keys (belt-and-suspenders).

- 🟡 Med #4 (DoS via unbounded fingerprinting): MAX_AUTH_PROFILES_BYTES
  = 8 MiB cap (above which we hash raw bytes), MAX_AUTH_PROFILES_DEPTH
  = 64 with a depth-cap marker so deeply-nested JSON cannot stack-
  overflow the gateway.

- 🟡 Med #5 (CWE-312 secrets in cache): buildModelsJsonFingerprint now
  returns SHA-256 hex of the canonical payload instead of the raw
  stable-stringified payload. The readyCache holds no verbatim secret
  material; heap snapshots / debug telemetry / core dumps cannot leak
  apiKey strings via this path.

# Token-rotation correctness

"token" is intentionally NOT in AUTH_PROFILE_VOLATILE_FIELDS even
though OAuth-style 'token' fields rotate. Profiles with type: 'token'
use the literal token key as a long-lived static credential, and
stripping it would mask real auth-state changes when a user rotates
that credential. Documented inline.

# Tests

Two tests in models-config.fingerprint-cache.test.ts:
- 'does not invalidate the cache when OAuth session fields rotate'
  (rotates access/refresh/expires; cache stays valid)
- 'DOES invalidate the cache when a static type:token credential rotates'
  (rotates the literal token field; cache invalidates)

# Compatibility

MODELS_JSON_STATE.readyCache value shape extended with modelsJsonHash:
{ fingerprint, modelsJsonHash, result }. All three plan return paths
(skip/noop/write) capture the post-write hash. The refreshedFingerprint
re-key path forwards modelsJsonHash through unchanged.

This is one of two PRs split out of openclaw#72869. The targetProvider
short-circuit work landed separately.
@aisle-research-bot

aisle-research-bot Bot commented Apr 28, 2026 •

Copy link
Copy Markdown

🔒 Aisle Security Analysis

We found 2 potential security issue(s) in this PR:

# Severity Title
1 🟡 Medium Cache integrity check bypass for oversized models.json/auth-profiles.json (sentinel hash depends only on size)
2 🔵 Low Symlink-following / TOCTOU risk when O_NOFOLLOW is unavailable in models.json handling
1. 🟡 Cache integrity check bypass for oversized models.json/auth-profiles.json (sentinel hash depends only on size)
Property Value
Severity Medium
CWE CWE-345
Location src/agents/models-config.ts:111-116

Description

safeHashRegularFile() returns a deterministic sentinel hash (oversize:${lst.size}) when the file is larger than the configured cap, and does not incorporate any file content into the returned hash.

As a result, when a file remains oversized and an attacker (or any external process) modifies its contents without changing its size, the “hash” remains constant and the cache-integrity mechanism can be bypassed:

  • readModelsJsonContentHash() uses safeHashRegularFile() and returns this sentinel string for oversized models.json.
  • ensureOpenClawModelsJson() treats currentModelsJsonHash === settled.modelsJsonHash as a two-factor cache hit.
  • Therefore, an oversized models.json can be modified in-place (same byte length) and still be treated as a cache hit, skipping re-plan/rewrite.

The same issue applies to readAuthProfilesStableHash() when auth-profiles.json is oversized: changes that preserve byte length will not change the authProfilesHash, so the fingerprint may not update.

Vulnerable code:

if (lst.size > maxBytes) {
  return { hash: `oversize:${lst.size}`, raw: null };
}

This undermines the intended “detect external edits / tampering” property of the readyCache for oversized files.

Recommendation

Ensure the oversize path cannot produce stable cache hits based only on size.

Options (pick one consistent with desired behavior):

  1. Fail closed for oversize: return null for oversize so callers treat it as unreadable and force re-plan/recompute every time.
if (lst.size > maxBytes) {
  return null; // force re-plan / fingerprint change
}
  1. Hash a bounded prefix + size (still memory-safe): open the file and hash up to maxBytes bytes, then incorporate both lst.size and a truncation marker into the digest.
​// pseudo
hash.update(prefixBytes);
hash.update(`|truncated|size:${fst.size}`);
return { hash: hash.digest("hex"), raw: null };
  1. If neither is possible, at minimum include additional metadata such as (mtimeMs, ino) in the sentinel to reduce same-size false hits (still weaker than (1)/(2)).

Approach (1) is simplest and most robust for integrity: oversize becomes an automatic cache miss.

2. 🔵 Symlink-following / TOCTOU risk when O_NOFOLLOW is unavailable in models.json handling
Property Value
Severity Low
CWE CWE-59
Location src/agents/models-config.ts:320-345

Description

safeHashRegularFile() and ensureModelsFileModeForModelsJson() attempt to prevent symlink attacks using O_NOFOLLOW, but fall back to plain O_RDONLY when the constant is unavailable. On such platforms (or Node builds) an attacker who can replace ${agentDir}/models.json (or other files passed to safeHashRegularFile, e.g. auth-profiles.json) with a symlink/reparse-point between checks can cause the gateway to operate on an attacker-chosen target.

In particular:

  • safeHashRegularFile() does an lstat()-based symlink check, but without O_NOFOLLOW a TOCTOU window exists: the path can be swapped to a symlink after lstat() and before open().
  • ensureModelsFileModeForModelsJson() does no lstat() check at all, and on fallback platforms will open() a symlink and then chmod(0o600) the symlink target.

This can lead to unintended reads (hashing) of arbitrary regular files (bounded by maxBytes) and unintended permission changes (chmod 0600) on attacker-chosen files owned by the gateway user.

Vulnerable code (fallback branch):

const flags =
  typeof FS_CONSTANTS.O_NOFOLLOW === "number"
    ? FS_CONSTANTS.O_RDONLY | FS_CONSTANTS.O_NOFOLLOW
    : FS_CONSTANTS.O_RDONLY;

fh = await fs.open(pathname, flags);
​// ... fh.stat() checks the opened target, not whether the path was a symlink
await fh.chmod(0o600);

Recommendation

Treat platforms without O_NOFOLLOW as unsafe for path-based opens and add additional mitigations:

  • Best: use a true no-follow open on all platforms.
    • For Windows, consider a native binding / platform-specific open that uses FILE_FLAG_OPEN_REPARSE_POINT to prevent following reparse points.
  • If no no-follow open is possible, reduce exploitability by:
    • Performing a best-effort lstat() check in ensureModelsFileModeForModelsJson() and returning early if it is a symlink.
    • Enforcing that agentDir (and parents) are owned by the current user and not writable by group/others before operating on files within it.
    • Optionally refusing to chmod/hash when O_NOFOLLOW is unavailable.

Example hardening for ensureModelsFileModeForModelsJson():

const lst = await fs.lstat(pathname).catch(() => null);
if (!lst || lst.isSymbolicLink() || !lst.isFile()) return;

const flags = FS_CONSTANTS.O_RDONLY; // still best-effort on platforms lacking O_NOFOLLOW
const fh = await fs.open(pathname, flags);
try {
  const fst = await fh.stat();
  if (!fst.isFile()) return;
  await fh.chmod(0o600);
} finally {
  await fh.close().catch(() => undefined);
}

Note: without O_NOFOLLOW, TOCTOU cannot be eliminated purely in JS; directory permission/ownership checks become essential to ensure untrusted users cannot modify ${agentDir}.


Analyzed PR: #73260 at commit beb1807

Last updated on: 2026-04-28T05:34:22Z

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ea3ff6c8ab

ℹ️ 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 src/agents/models-config.ts Resolved
@greptile-apps

greptile-apps Bot commented Apr 28, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR replaces mtime-based cache keys with content-based SHA-256 hashes for the ensureOpenClawModelsJson implicit-provider-discovery cache, and adds a second-factor models.json drift check (hash at write time vs hash at read time). It also hardens ensureModelsFileModeForModelsJson against CWE-59 symlink-following via O_NOFOLLOW + fchmod-through-fd, and guards the fingerprint walk against prototype pollution (CWE-1321) and DoS (bounded size + depth).

One P2 to note: the oversize sentinel returned by safeHashRegularFile when a file exceeds the cap uses the file's size only (oversize:${lst.size}), not a bounded content hash. The PR description and the inline comment at line 173 claim "raw-hash above cap," but a same-size oversize file with changed content would produce the same sentinel and would not invalidate the cache. In practice the caps (8 MiB / 1 MiB) make this nearly impossible to trigger, but the documentation-vs-implementation mismatch could mislead future maintainers.

Confidence Score: 5/5

Safe to merge — the single finding is P2 (impractical edge case with no security or data-correctness impact at realistic file sizes).

No P0 or P1 issues found. The security hardening (O_NOFOLLOW, fchmod-through-fd, prototype-pollution guard, depth cap) is correctly implemented. The two-factor cache logic is sound. The only finding is a documentation-vs-implementation gap in the oversize sentinel path that is practically unreachable at the configured thresholds.

src/agents/models-config.ts lines 111–116 (oversize sentinel semantics).

Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/agents/models-config.ts
Line: 111-116

Comment:
**Oversize branch returns size sentinel, not a content hash**

The PR description and the `readAuthProfilesStableHash` comment both claim "raw-hash above cap," but the oversize branch returns a size-only sentinel (`oversize:${lst.size}`) without reading the file at all. Two files of the same byte-count but different content receive the same "hash," so a content change that leaves the size unchanged would not invalidate the fingerprint.

For the models.json drift path this matters only above 1 MiB (very unusual), but the misleading comment at line 173 — "Caller invalidates cache by mismatch" — is only true if the size also changes. Streaming the first N bytes through SHA-256 when the file exceeds the cap (capping what's fed to the hasher, not what's read into memory) would satisfy both the DoS-resistance goal and the content-sensitivity claim.

How can I resolve this? If you propose a fix, please make it concise.

Reviews (2): Last reviewed commit: "fix(models-config): streaming hash, O_NO..." | Re-trigger Greptile

Re-review progress:

Comment thread src/agents/models-config.ts Resolved
Addresses Codex P1, Greptile P2, and Aisle Med #1/#2/#3 on openclaw#73260:

# Streaming bounded hash (Codex P1 / Aisle Med #2)

The previous oversize-branch in readAuthProfilesStableHash still did
fs.readFile(path) which loaded the entire file into memory \u2014 the
MAX_AUTH_PROFILES_BYTES cap was effectively unenforced.  Same problem
for readModelsJsonContentHash (no cap at all).

New helper safeHashRegularFile():
  - lstat first; reject symlinks and non-regular files
  - bail at lstat-time if size exceeds maxBytes (returns sentinel hash
    so size-change still invalidates the cache)
  - open with O_NOFOLLOW where supported (closes lstat\u2192open TOCTOU)
  - fstat after open to verify it's still a regular file
  - createReadStream(fd) with bounded highWaterMark; destroy if accumulated
    bytes exceed maxBytes (handles the case where attacker grows the
    file between lstat and stream completion)

Both readers now route through safeHashRegularFile.  Models.json gets
a 1 MiB cap (MAX_MODELS_JSON_BYTES); auth-profiles keeps its 8 MiB cap.

# O_NOFOLLOW chmod (Aisle Med #1, CWE-367)

The previous lstat-then-chmod sequence was racy: an attacker who
could rename/replace ${agentDir}/models.json between the two syscalls
could have chmod() follow a swapped-in symlink to an arbitrary file.

Replaced with fs.open(path, O_RDONLY | O_NOFOLLOW) \u2192 fchmod via the
file handle.  The open itself refuses symlinks atomically; the
fchmod operates on the validated fd, eliminating the race.  When
O_NOFOLLOW is unavailable (rare but possible), falls back to plain
O_RDONLY \u2014 the prior lstat protection was already best-effort.

# Symlink-safe reads (Aisle Med #3, CWE-59)

Previous fs.readFile in the hash readers followed symlinks.  With
the safeHashRegularFile refactor above, both auth-profiles.json and
models.json now reject symlinks before reading.

# JSDoc fix (Greptile P2)

readModelsJsonContentHash's prior comment said "forces a re-plan"
when the file is absent, but the call site does null === null
comparison which is a cache hit, not a re-plan (the steady-state
skip case for plan.action === 'skip').  Updated the comment to
explain the actual semantics: stable absence is a stable result;
drift is a re-plan.

# Tests

14/14 existing tests pass.  No new test cases needed \u2014 the existing
file-mode and fingerprint-cache tests cover both the symlink-rejection
paths (via lstat shortcut) and the modelsJsonHash second-factor.
Lint: 0 errors.
@zeroaltitude

Copy link
Copy Markdown
Contributor Author

Three findings landed in beb1807de2:

  • 🟡 fix: add @lid format support and allowFrom wildcard handling #1 (CWE-367 TOCTOU symlink race on chmod): ensureModelsFileModeForModelsJson now uses fs.open(path, O_RDONLY | O_NOFOLLOW) then fchmod through the resulting file handle. The open itself refuses symlinks atomically; the chmod operates on the validated fd. No window between check and act.
  • 🟡 Login fails with 'WebSocket Error (socket hang up)' ECONNRESET #2 (CWE-400 unbounded reads): safeHashRegularFile helper now serves both readAuthProfilesStableHash and readModelsJsonContentHash. Streams the hash via createReadStream(fd) with bounded highWaterMark, accumulator destroyed if it exceeds the cap. MAX_AUTH_PROFILES_BYTES = 8 MiB, MAX_MODELS_JSON_BYTES = 1 MiB.
  • 🟡 WA business, groups & office hours  #3 (CWE-59 symlink-following reads): same safeHashRegularFile helper does lstat + isSymbolicLink() rejection before any read, then uses O_NOFOLLOW on open as a second-line defense.

All three readers (auth-profiles hash, models.json hash, chmod) now go through the same hardened code paths.

@zeroaltitude

Copy link
Copy Markdown
Contributor Author

@greptile-apps: please do re-review/re-score

@clawsweeper

clawsweeper Bot commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed June 4, 2026, 8:37 PM ET / 00:37 UTC.

Summary
The PR rewrites ensureOpenClawModelsJson readiness caching to use content/outcome hashes for auth-profile and models.json drift, adds fingerprint-cache tests and a proof script, and includes small script/test formatting changes.

PR surface: Source +513, Tests +468, Other +197. Total +1178 across 8 files.

Reproducibility: yes. source-reproducible: current main fingerprints the SQLite auth DB/WAL and plugin catalog mtimes, while the PR head hashes legacy auth-profiles.json and checks only root models.json on cache hits. I did not run tests because this review was required to keep the checkout read-only.

Review metrics: 1 noteworthy metric.

  • Cache invalidation inputs: 2 canonical sources dropped or replaced. The PR replaces SQLite auth DB/WAL mtimes with legacy JSON hashing and removes generated plugin catalog mtimes, which are compatibility-sensitive cache inputs.

Merge readiness
Overall: 🧂 unranked krab
Proof: 🧂 unranked krab
Patch quality: 🧂 unranked krab
Result: blocked until stronger real behavior proof is added.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • Fingerprint canonical SQLite auth-profile state and generated plugin catalog sidecars before using the ready cache.
  • [P1] Add focused regression coverage for SQLite-backed OAuth/token changes and plugin catalog sidecar drift.
  • [P1] Update the PR body with redacted SQLite-backed runtime output or logs after the fix; updating the body should trigger a fresh ClawSweeper review, or a maintainer can comment @clawsweeper re-review.

Proof guidance:

  • [P1] Needs stronger real behavior proof before merge: Copied runtime output exists, but the added proof script mutates auth-profiles.json directly instead of exercising the canonical SQLite-backed auth-profile store used by current users. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Risk before merge

  • [P1] Existing users with SQLite-backed OAuth or token profiles can change auth state without changing this PR's legacy JSON fingerprint, so ensureOpenClawModelsJson can return stale cached provider state.
  • [P1] Generated plugin catalog sidecar edits or corruption are no longer part of the cache-hit decision, so plugin-owned provider credentials, baseUrl, or headers may remain stale until another input happens to force planning.

Maintainer options:

  1. Fix Canonical Cache Inputs (recommended)
    Update the cache fingerprint/outcome model to use the SQLite auth-profile store and generated plugin catalog sidecars before merge, then add matching tests and real runtime proof.
  2. Pause For Owner Review
    If maintainers want to accept a narrower invalidation contract, pause until the auth/provider owners explicitly approve the upgrade and security tradeoff.
  3. Rework As Smaller PR
    If the branch keeps accumulating unrelated churn, close or replace it with a smaller PR that preserves the current SQLite and sidecar invalidation contracts.

Next step before merge

  • [P1] The PR has concrete P1 blockers plus insufficient contributor real-behavior proof, so it should stay in human review rather than receive an automated repair marker.

Security
Needs attention: The diff changes credential-derived cache and tamper-detection behavior, and current head can miss canonical SQLite auth changes plus generated plugin catalog sidecar drift.

Review findings

  • [P1] Fingerprint the SQLite auth profile store — src/agents/models-config.ts:716-717
  • [P1] Include plugin catalog sidecars in cache drift detection — src/agents/models-config.ts:441-452
Review details

Best possible solution:

Keep the content-hash/cache-hardening direction only after it hashes the canonical SQLite auth-profile store and generated plugin catalog sidecars, with focused tests and redacted SQLite-backed runtime proof.

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

Yes, source-reproducible: current main fingerprints the SQLite auth DB/WAL and plugin catalog mtimes, while the PR head hashes legacy auth-profiles.json and checks only root models.json on cache hits. I did not run tests because this review was required to keep the checkout read-only.

Is this the best way to solve the issue?

No. Content hashing is a plausible performance/security direction, but the current implementation targets the wrong auth store and omits sidecar drift, so it is not the narrowest maintainable fix yet.

Full review comments:

  • [P1] Fingerprint the SQLite auth profile store — src/agents/models-config.ts:716-717
    This now reads and hashes <agentDir>/auth-profiles.json, but current users' auth profiles are persisted in <agentDir>/openclaw-agent.sqlite (auth_profile_store plus WAL), which current main explicitly includes in the cache fingerprint. In the normal SQLite-only state this outcome stays absent, so OAuth refreshes, token expiry changes, or pasted-token rotations can reuse the old readyCache entry and keep stale provider state. Please hash the canonical SQLite payload/DB outcome or preserve the current SQLite DB/WAL invalidator instead of keying on the legacy JSON file.
    Confidence: 0.95
  • [P1] Include plugin catalog sidecars in cache drift detection — src/agents/models-config.ts:441-452
    The new fingerprint payload drops pluginCatalogMtimes, and the cache-hit check only re-hashes root models.json. Generated plugins/<id>/catalog.json files are provider catalog state written by this same path, so after a warm cache an external edit or stale sidecar can survive without re-planning or rewrite. Please include sidecar content/outcomes in the cache key or retain the current sidecar mtime invalidation.
    Confidence: 0.86

Overall correctness: patch is incorrect
Overall confidence: 0.93

AGENTS.md: found and applied where relevant.

Codex review notes: model gpt-5.5, reasoning high; reviewed against 1bdf210b4383.

Label changes

Label justifications:

  • P1: The PR can stale auth/provider state for current SQLite-backed users, which affects real agent/provider workflows now.
  • merge-risk: 🚨 compatibility: Merging would change upgrade behavior for existing SQLite auth-profile stores and generated plugin catalog sidecars.
  • merge-risk: 🚨 auth-provider: The changed cache key can miss OAuth/token profile changes and plugin provider catalog drift.
  • merge-risk: 🚨 security-boundary: The diff touches credential-derived cache state, provider secrets, symlink/file-mode hardening, and tamper-detection behavior.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🧂 unranked krab.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: Copied runtime output exists, but the added proof script mutates auth-profiles.json directly instead of exercising the canonical SQLite-backed auth-profile store used by current users. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed

PR surface:

Source +513, Tests +468, Other +197. Total +1178 across 8 files.

View PR surface stats
Area Files Added Removed Net
Source 2 610 97 +513
Tests 3 590 122 +468
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 3 217 20 +197
Total 8 1417 239 +1178

Security concerns:

  • [high] SQLite auth changes can miss cache invalidation — src/agents/models-config.ts:716
    Hashing legacy auth-profiles.json does not cover the canonical SQLite auth_profile_store, so credential eligibility or token changes can reuse stale cached provider state.
    Confidence: 0.95
  • [medium] Plugin catalog sidecar tampering can survive cache hits — src/agents/models-config.ts:441
    The PR removes current-main sidecar mtime invalidation and only verifies root models.json, which can leave plugin-owned provider secrets or endpoints stale after sidecar edits.
    Confidence: 0.86

What I checked:

Likely related people:

  • steipete: Current main blame and history show heavy recent work across models-config.ts, auth-profile normalization, docs, and generated catalog behavior. (role: recent area contributor; confidence: high; commits: 867d7898dffc, 651a1d7ed232, c29b09874416; files: src/agents/models-config.ts, src/agents/auth-profiles/store.ts, docs/gateway/authentication.md)
  • vincentkoc: Introduced the models.json readiness cache and has recent auth-profile/runtime cache work that overlaps this PR's behavior. (role: feature owner; confidence: high; commits: 2b210703a3b9, 03231c063387, 2bc031c3571b; files: src/agents/models-config.ts, src/agents/auth-profiles/store.ts)
  • joshavant: Worked on SecretRef-safe models.json persistence and auth/secret runtime behavior that this cache can stale or expose if invalidation is wrong. (role: adjacent owner; confidence: medium; commits: 8e20dd22d890, 36d2ae2a2235, 0bcb95e8fa5e; files: src/agents/models-config.ts, src/agents/auth-profiles/store.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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

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

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels May 5, 2026

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e6a37b84f3

ℹ️ 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 src/agents/models-config.ts Resolved

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7cd2e8af7a

ℹ️ 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 src/agents/models-config.ts Resolved
…w feedback)

Codex P2 / Aisle medium #1 on PR openclaw#73260 flagged that `safeHashRegularFile`
returned a deterministic `oversize:${lst.size}` sentinel when a file
exceeded the cap, so an attacker could swap the *contents* of an oversized
`auth-profiles.json` or `models.json` without changing its byte length and
still hit the readyCache via the size-only sentinel comparison (CWE-345).

Switch to fail-closed:

- `safeHashRegularFile` now returns `null` for oversize at lstat time and
  for grow-past-cap mid-read (the latter was already caught via the
  destroy-with-error path; the JSDoc/comment now states that explicitly).
- The return type narrows from `{ hash; raw: Buffer | null } | null` to
  `{ hash; raw: Buffer } | null` — the `raw === null` branch in
  `readAuthProfilesStableHash` is now unreachable and removed.
- JSDoc on the helper and `readAuthProfilesStableHash` now describes the
  fail-closed semantics and links them back to the threat model.

Also:

- Add a regression test that warms the cache with a small, hashable
  `auth-profiles.json`, then grows it past `MAX_AUTH_PROFILES_BYTES`
  (8 MiB) and asserts the implicit-provider-discovery pipeline re-runs
  (i.e. the fingerprint changed instead of stably hitting an
  `oversize:<size>` sentinel).
- Add the missing `Unreleased` CHANGELOG entry covering the
  content-hashed fingerprint, post-write models.json drift hash, the
  oversize fail-closed change, and the existing `O_NOFOLLOW`/streaming/
  prototype-pollution hardening (Codex P3 on the same review).
- Backfill the new `resolveProviderEnvAuthEvidence`/
  `listProviderEnvAuthLookupKeys`/`resolveProviderEnvAuthLookupKeys`
  exports in the fingerprint test's `model-auth-env-vars.js` mock so the
  suite runs at all after the recent `origin/main` merge added those
  call sites in `model-auth-env.ts` / provider secret-helpers.

Validation (from
~/projects/worktrees/openclaw/perf-models-config-cache-fingerprint):

  pnpm vitest run src/agents/models-config.fingerprint-cache.test.ts
    Test Files  2 passed (2)
         Tests  12 passed (12)
  pnpm tsgo:core            # 0 errors
  pnpm tsgo:core:test       # 0 errors
  pnpm oxlint src/agents/models-config.ts \
              src/agents/models-config.fingerprint-cache.test.ts
    Found 0 warnings and 0 errors.
  git diff --check          # clean

Beads: openclaw-9i0
@zeroaltitude

Copy link
Copy Markdown
Contributor Author

Follow-up addressing clawsweeper review (Codex P2 + P3) and Aisle medium #1 landed in 057024fa46:

Codex P2 / Aisle medium #1 — size-only oversize sentinel could mask same-size content swaps (CWE-345)

The previous oversize:${lst.size} sentinel let an attacker swap the contents of an oversized auth-profiles.json or models.json without changing byte length and still hit the readyCache. safeHashRegularFile now fails closed on oversize:

  • Returns null at lstat time when lst.size > maxBytes.
  • Grow-past-cap mid-read still destroys the stream with an error so the surrounding try/catch returns null (now stated explicitly in a comment).
  • Return type narrows to { hash; raw: Buffer } | null; the unreachable raw === null branch in readAuthProfilesStableHash is removed.
  • JSDoc on the helper and on readAuthProfilesStableHash now describe the fail-closed semantics and reference the threat model.

Codex P3 — missing CHANGELOG.md entry

Added an Unreleased entry under ### Changes covering the content-hashed auth-profiles.json fingerprint, the post-write models.json drift hash, the oversize fail-closed change, and the existing O_NOFOLLOW/streaming/prototype-pollution hardening.

Regression coverage

models-config.fingerprint-cache.test.ts gains an over-cap case: warms the cache with a small profile, grows auth-profiles.json past MAX_AUTH_PROFILES_BYTES (8 MiB), asserts the implicit-provider-discovery pipeline re-runs. (Pre-fix this would have stayed cached behind the oversize:<size> sentinel.) The same fingerprint test file's ./model-auth-env-vars.js mock also gains resolveProviderEnvAuthEvidence/listProviderEnvAuthLookupKeys/resolveProviderEnvAuthLookupKeys so the suite runs at all after the recent origin/main merge added those call sites.

Validation (from ~/projects/worktrees/openclaw/perf-models-config-cache-fingerprint):

pnpm vitest run src/agents/models-config.fingerprint-cache.test.ts
  Test Files  2 passed (2)
       Tests  12 passed (12)
pnpm tsgo:core            # 0 errors
pnpm tsgo:core:test       # 0 errors
pnpm oxlint src/agents/models-config.ts \
            src/agents/models-config.fingerprint-cache.test.ts
  Found 0 warnings and 0 errors.
git diff --check          # clean

Aisle low #2 (TOCTOU on platforms without O_NOFOLLOW) is unchanged here — Linux gateway hosts have O_NOFOLLOW, the lstat+O_NOFOLLOW defence-in-depth pair is the strongest bound we can offer in JS, and the recommended directory-permission posture for agentDir is enforced elsewhere by the agent-workspace setup. Happy to thread an explicit agentDir ownership check through if reviewers want belt-and-braces here.

@clawsweeper please re-review.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 057024fa46

ℹ️ 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 src/agents/models-config.ts Resolved
Comment thread src/agents/models-config.ts Resolved
zeroaltitude added a commit to zeroaltitude/openclaw that referenced this pull request May 5, 2026
…ransport check + bounded compare (review feedback)

Codex P1+P2 (and matching Aisle High #2 / medium #3) on PR openclaw#73261.
ClawSweeper rejected the previous round's "wrong solution" \u2014 the global
readyCache write after a provider-scoped check, an unbounded recursive
stableEqual on disk-controlled state, no per-model transport drift
check, and a fail-open malformed-apiKey branch.  Redesign:

# Provider-scoped readyCache (Codex P1)

The previous version called
  MODELS_JSON_STATE.readyCache.set(cacheKey, ...)
after the targetProvider short-circuit, where cacheKey was the GLOBAL
fingerprint key.  A later non-targeted ensureOpenClawModelsJson call
would hit that entry and skip the full plan even though only one
provider was validated.  After the redesign, successful short-circuits
populate a SCOPED key:
  `${targetPath}\\0${fingerprint}\\0sc:${targetProvider}`
which non-targeted callers never compute.  Targeted callers consult the
scoped key first, hit it warm if present (with the same modelsJsonHash
two-factor verification as the global cache), and fall through to the
disk-based check otherwise.  Non-targeted callers always run a full
plan to validate every provider.

# Per-model transport drift (Codex P1 / Aisle High #2)

The runtime consumes per-model `baseUrl` / `api` / `headers` from
models.json (`pi-embedded-runner/model.ts` falls back to
`discoveredModel.baseUrl` / `.api` / `.headers` when no provider-level
override is set).  The previous comparison only covered provider-level
fields, so an attacker who could write models.json could keep
provider-level apiKey/baseUrl/headers/auth intact while injecting a
per-model `baseUrl: \"https://attacker.example/v1\"` and the short-
circuit would accept it.  After the redesign, any disk-side per-model
transport field forces a full re-plan that re-applies provider/plugin
defaults and rewrites the file.  This is intentionally strict: the
common case (no per-model transport overrides) still gets the short-
circuit; configurations that legitimately use per-model transport just
skip the fast path.

# Bounded structural equality (Codex P2 / Aisle medium #3)

`stableEqual = stableStringify(a) === stableStringify(b)` recurses
without depth bounds.  A small but pathologically nested
`models.json` (e.g. `{a: {a: {a: ...}}}`) could stack-overflow the
gateway during the short-circuit comparison.  Added
`stableStringifyBounded` (throws on overrun) +
`stableEqualBounded` (catches the overrun and returns false \u2014 fail
closed to the full plan).  Used for baseUrl/headers/auth comparisons
against disk-controlled state with `SHORT_CIRCUIT_COMPARE_MAX_DEPTH =
64`.  The original unbounded `stableEqual` is removed; the trusted-
input fingerprint pipeline still uses unbounded `stableStringify`.

# Fail closed on malformed disk apiKey (Codex P2)

When config has no apiKey, the previous fail-open branch only
rejected non-empty strings on disk \u2014 numbers, null, objects, etc.
were silently accepted.  Now anything other than `undefined` or empty
string forces a re-plan.

# Reuse openclaw#73260's safeHashRegularFile

The disk read in `readExistingProviderMatchesConfig` now uses
`safeHashRegularFile` (the fingerprint-cache primitive) for
O_NOFOLLOW open + lstat/fstat regular-file check + size cap +
fail-closed on grow-past-cap.  Drops the redundant
`MAX_MODELS_JSON_SHORT_CIRCUIT_BYTES` constant in favour of the
shared `MAX_MODELS_JSON_BYTES` from openclaw#73260.

# Tests

13/13 pass in src/agents/models-config.target-provider-short-circuit.test.ts:

- existing 5 (hit-on-match, miss-on-rotated-key, miss-on-baseUrl,
  miss-on-headers, miss-on-cold-cache, hit-after-warm-fingerprint)
  still pass with the new code path.
- `short-circuit-populates-scoped-cache` rewritten: third call hits
  the SCOPED cache entry with no fs.readFile (modelsJsonHash uses
  createReadStream).
- `scoped-cache-isolation` (new): targeted short-circuit followed by
  non-targeted call with same fingerprint runs full plan (does NOT
  hit the scoped entry).
- `miss-on-per-model-baseUrl` / `miss-on-per-model-headers` /
  `miss-on-per-model-api` (new): per-model transport overrides on
  disk reject the short-circuit and fall through to a full plan.
- `miss-on-deep-nested-disk` (new): 200-level-deep adversarial disk
  headers fall through cleanly without throwing/overflowing.
- `miss-on-malformed-disk-apiKey` (new): non-string disk apiKey
  rejects when config has no apiKey.

Also backfills the missing
`resolveProviderEnvAuthEvidence`/`listProviderEnvAuthLookupKeys`/
`resolveProviderEnvAuthLookupKeys` exports in the
`model-auth-env-vars.js` mock so the test suite runs against the
post-merge `model-auth-env.ts` surface (same fix openclaw#73260's follow-up
landed for its fingerprint-cache test).

# Validation (from worktree
~/projects/worktrees/openclaw/perf-models-config-target-provider):

  pnpm vitest run src/agents/models-config.target-provider-short-circuit.test.ts
    Test Files  1 passed (1)
         Tests  13 passed (13)
  pnpm vitest run src/agents/models-config.fingerprint-cache.test.ts \\
                  src/agents/models-config.target-provider-short-circuit.test.ts
    Test Files  2 passed (2)
         Tests  19 passed (19)
  pnpm tsgo:core            # 0 errors
  pnpm tsgo:core:test       # 0 errors
  pnpm oxlint src/agents/models-config.ts \\
              src/agents/models-config.target-provider-short-circuit.test.ts
    Found 0 warnings and 0 errors.
  git diff --check          # clean

Beads: openclaw-l5q
…ache on uncacheable auth-profiles (review feedback)

Round-4 follow-up to Codex P1 + P2 on PR openclaw#73260.  Both findings were
real holes in the round-3 "return null on oversize" change:

  1. Codex P1 — "Treat unhashable models.json as cache drift"
     (src/agents/models-config.ts:474):
     The cache-hit predicate accepted
     `currentModelsJsonHash === settled.modelsJsonHash`, but
     `readModelsJsonContentHash` returned `null` for several distinct
     failure modes (oversize >1 MiB, symlinked, non-regular,
     I/O error) IN ADDITION to the legitimate "file absent" case.
     Anyone who could put models.json into one of those states could
     then mutate its contents repeatedly while every read returned
     null, and the cache kept hitting via `null === null`.

  2. Codex P2 — "Distinguish oversize auth-profiles from stable
     fingerprints" (src/agents/models-config.ts:123):
     `readAuthProfilesStableHash` returned `null` for any oversize
     auth-profiles.json, so all >8 MiB variants collapsed to a single
     fingerprint contribution.  Once the file was already oversize,
     credential edits that kept it oversize no longer changed the
     fingerprint and therefore no longer invalidated the ready cache.

Fix: replace the `string | null` return with a discriminated outcome
(`ContentHashOutcome` in `models-config-state.ts`):

    | { kind: "absent" }     // legitimate file-does-not-exist steady state
    | { kind: "hashed"; hash } // successful bounded-stream read
    | { kind: "uncacheable" } // oversize, symlink, non-regular, or I/O error

Predicate (`modelsContentOutcomesMatch`):

  - `absent === absent`         → cache hit (skip-noop on a missing file).
  - `hashed === hashed`         → cache hit iff hashes are identical.
  - `uncacheable` on EITHER side → ALWAYS a miss.  Two `uncacheable`
                                  outcomes do not match each other,
                                  because they could correspond to
                                  different attacker-controlled bodies
                                  that just happen to trip the same
                                  cap.

Auth-profiles cache-bypass: when `readAuthProfilesStableOutcome`
returns `uncacheable`, `ensureOpenClawModelsJson` bypasses the
ready cache entirely — neither reading from it nor writing to it —
and re-plans on every call.  This stops an attacker who keeps the
file oversize from accumulating dead entries in the in-memory cache,
and stops same-size content swaps from riding a stale entry.  When
the file returns to a hashable state the next call lands a fresh
cache entry keyed by the new content fingerprint.

Defensive guard: `buildModelsJsonFingerprint` now refuses to be
called with an `uncacheable` auth-profiles outcome.  Callers
must bypass the cache instead.

Also:

  - Refactor `safeHashRegularFile` → `safeReadFileOutcome` returning
    the discriminated outcome.  ENOENT is the only lstat error
    treated as `absent`; every other error (EACCES, etc.) is
    `uncacheable` so silent permission failures do not masquerade as
    a stable absence.  All other behaviour is preserved
    (O_NOFOLLOW-hardened open, fstat re-check, bounded streaming
    hash, abort-on-grow-past-cap).
  - Update `ContentHashOutcome` JSDoc + the `MODELS_JSON_STATE`
    cache shape from `modelsJsonHash: string | null` to
    `modelsJsonOutcome: ContentHashOutcome`.
  - Rewrite the cache-flow JSDoc (Greptile P2 noted the previous
    JSDoc was the opposite of the actual behaviour).
  - Add two regression tests:
      * "forces a re-plan on every call while auth-profiles.json
        stays oversize (Codex P2 round-4 on openclaw#73260)" — warms the
        cache with a small profile, verifies repeat-call hit, then
        oversizes the file and asserts that EVERY subsequent call
        re-plans (including byte-identical and same-byte-length
        swapped contents).  Restoring the file to a small state
        re-enables caching on the next call.
      * "invalidates the cache when models.json becomes unhashable
        (Codex P1 round-4 on openclaw#73260)" — warms cache with a real
        write, verifies repeat-call hit, then externally grows
        models.json past `MAX_MODELS_JSON_BYTES` and asserts the
        next call re-plans.
  - Update CHANGELOG to describe the round-4 fail-closed contract.

Validation (from
~/projects/worktrees/openclaw/perf-models-config-cache-fingerprint):

  pnpm vitest run src/agents/models-config.fingerprint-cache.test.ts
    Test Files  2 passed (2)
         Tests  16 passed (16)
  pnpm tsgo:core            # 0 errors
  pnpm tsgo:core:test       # 0 errors
  pnpm oxlint src/agents/models-config.ts \
              src/agents/models-config-state.ts \
              src/agents/models-config.fingerprint-cache.test.ts
    Found 0 warnings and 0 errors.
  git diff --check          # clean

Beads: openclaw-t9l
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 27, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 28, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels May 28, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 28, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 28, 2026
…che-fingerprint

Integration rotation: merge origin/main into topic branch.

Conflict resolution in src/agents/models-config.ts:
- Keep branch's content-based fingerprinting approach (readAuthProfilesStableOutcome,
  stripAuthProfilesVolatileFields, readModelsJsonContentOutcome, modelsContentOutcomesMatch,
  sync buildModelsJsonFingerprint with authProfilesHash) — this is the point of the PR.
- Drop main's mtime-based approach (authProfilesMtimeMs, authProfilesWalMtimeMs,
  resolveAuthProfileDatabasePath) and readPluginCatalogMtimes (dead code in our approach).
- Keep HEAD's planAndWrite(fingerprint) call over main's inlined withModelsJsonWriteLock.
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Jun 3, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Jun 3, 2026
…che-fingerprint

# Conflicts:
#	src/agents/models-config.ts
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. label Jun 4, 2026
…the model-auth-env-vars mock

The fingerprint-cache test's vi.mock("./model-auth-env-vars.js") factory omitted
resolveProviderEnvAuthLookupMaps, which the real models-config.providers.secrets.ts
(loaded via importActual of models-config.providers.js) calls. In isolated runs this
threw "No resolveProviderEnvAuthLookupMaps export is defined on the mock" and failed the
whole file; in full-suite runs it surfaced as the token-profile-expiry cache failures.
Add the stub with the canonical { aliasMap, envCandidateMap, authEvidenceMap } shape
(matching sibling provider tests) and this mock's own openai candidate. Test-only; 9/9 pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. and removed P2 Normal backlog priority with limited blast radius. labels Jun 5, 2026
zeroaltitude added a commit to zeroaltitude/openclaw that referenced this pull request Jun 5, 2026
… integration merge

The fingerprint topic's Round-5 openclaw#73260 fix makes the auth-profile volatile-field set
per-type: OAuth profiles strip expires*/access/refresh (rotation must not invalidate the
implicit-provider cache), but `type: "token"` profiles KEEP expires* (eligibility policy —
an expired token resolves to null in resolveApiKeyForProfile), so valid->expired must
invalidate the cache. Merging the two models-config.ts perf rewrites (cache-fingerprint +
target-provider-short-circuit) into integration dropped AUTH_PROFILE_VOLATILE_FIELDS_TOKEN
and getVolatileFieldsForProfileObject, leaving the strip site on the flat set — so token
expiry changes stopped invalidating the cache (fingerprint-cache.test.ts "...token
profile's expiry changes": expected 2, got 1). Restore the per-type set + picker and use
it at the strip site. fingerprint-cache.test.ts now 9/9.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…elsJson (restore main parity)

The cache-fingerprint rewrite of ensureOpenClawModelsJson dropped main's plugin-catalog
writing: mergeGeneratedPluginCatalogProvidersIntoExistingParsed (merge generated plugin
provider catalogs into existingParsed before planning) and writePluginCatalogsForModelsJson
(write the catalogs in the skip/noop/write paths). Both functions were defined but never
called, so generated plugin provider catalogs were no longer written alongside models.json.
Restore the calls, mirroring main's skip/noop/write structure. main's mtime-based cache
helpers (readFileMtimeMs/readPluginCatalogMtimes) stay intentionally removed — superseded
by this branch's content fingerprint. models-config + plugin-catalog suite: 40/40.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@zeroaltitude

Copy link
Copy Markdown
Contributor Author

Superseded by #90741 — a single reconciled implementation that unifies the content-hash fingerprint cache (#73260) and the targetProvider short-circuit (#73261). The two optimizations are complementary, not competing: a warm-process whole-input memoizer, a provider-scoped cold-start/cross-provider short-circuit, and the full plan, layered in that order in ensureOpenClawModelsJson.

#90741 also fixes a correctness gap shared by both PRs: the fingerprint hashed the legacy auth-profiles.json file, which reads absent for any agent already migrated to the canonical SQLite auth store — so real credential changes never invalidated the implicit-provider-discovery cache. #90741 fingerprints the canonical openclaw-agent.sqlite store instead (volatile OAuth session fields still stripped, so token rotation stays cache-stable).

Verified on the unified branch: 190/190 models-config tests and tsgo:core:all clean. Closing in favor of #90741 — reopen if a scenario there isn't covered.

@zeroaltitude
zeroaltitude deleted the perf/models-config-cache-fingerprint branch June 5, 2026 19:14
zeroaltitude added a commit to zeroaltitude/openclaw that referenced this pull request Jul 10, 2026
…che-unified

2421 commits behind. This branch and main both independently evolved the
same models.json caching subsystem, requiring combining both sides rather
than picking one:

- src/agents/models-config-state.ts: kept our richer ModelsJsonReadyCacheEntry
  (validates cached entries against both the models.json AND plugin-catalog
  sidecars' actual on-disk content hashes before treating a warm hit as
  valid - Codex P1 fixes from PR openclaw#72869/openclaw#73260/openclaw#90741), but adopted main's
  writeQueue: KeyedAsyncQueue in place of our writeLocks: Map<string, Promise<void>>
  - confirmed via the models-config.ts call site (already calling
  writeQueue.enqueue at an unconflicted line) that main's concurrency
  primitive is what the rest of the file already expects.
- src/agents/models-config.ts: dropped main's non-exported
  PreparedOpenClawModelsJsonSource type declaration - this branch already
  has its own, more complete, exported version (a discriminated union with
  a cacheable flag) further down in the file; keeping both would have been
  a duplicate-identifier error.
- src/agents/embedded-agent-runner/compact.hooks.harness.ts: kept our
  ensureOpenClawModelsJsonMock (confirmed still used by real test files),
  adopted main's 2-param maybeCompactAgentHarnessSessionMock signature
  (confirmed the real maybeCompactAgentHarnessSession function already
  takes 2 params) and its new runCompactWithSafetyTimeoutMock/
  compactWithSafetyTimeoutMock addition (a new, unrelated compaction
  timeout feature).

Applied the systematic function-by-function diff-against-main check
documented in refs/openclaw.md after the feat/claude-app-server-extension
incident; only the expected architectural differences from this branch's
own restructuring surfaced, no silent drops.

Validation: tsgo:core, tsgo:extensions, tsgo:core:test, tsgo:extensions:test
all clean. vitest models-config: 173/173. vitest compaction/embedded-agent
suites touching the modified mock harness: 135/135. config:schema:check,
plugin-sdk:api:check, oxlint, git diff --check all clean.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P1 High-priority user-facing bug, regression, or broken workflow. proof: supplied External PR includes structured after-fix real behavior proof. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. scripts Repository scripts size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant