Skip to content

fix(clawrouter): show stable error for malformed usage responses - #119580

Merged
vincentkoc merged 2 commits into
openclaw:mainfrom
sunlit-deng:sunlit/fix/clawrouter-malformed-usage-response
Aug 5, 2026
Merged

vincentkoc merged 2 commits into
openclaw:mainfrom
sunlit-deng:sunlit/fix/clawrouter-malformed-usage-response

Conversation

@sunlit-deng

@sunlit-deng sunlit-deng commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes an issue where users viewing ClawRouter quota information would get a thrown parsing error when the usage endpoint returned malformed JSON or invalid UTF-8.

Why This Change Was Made

ClawRouter now follows the established Venice and OpenRouter usage pattern by reporting malformed payloads as a stable provider error snapshot. Response-size, stream, HTTP, and transport failures remain distinct errors.

User Impact

Users see “Malformed usage response” instead of a failed quota refresh when ClawRouter returns an invalid payload.

Evidence

  • node scripts/run-vitest.mjs extensions/clawrouter/usage.test.ts: focused tests pass, including malformed JSON, invalid UTF-8, non-object JSON, stream failure, size cap, HTTP error, and production transport cases.
  • node --import tsx proof-live.ts: the same real production provider path ran against a loopback HTTP boundary on the validation base and exact head.
  • Result: malformed payloads changed from thrown parser errors to a stable snapshot; valid and HTTP-error controls stayed unchanged.
baseline c02e39345bf6946acd0635ac18732f4003dd45b5
malformed-json threw=SyntaxError
invalid-utf8 threw=TypeError
valid-control snapshot={"provider":"clawrouter","displayName":"ClawRouter","windows":[],"plan":"Unmetered proxy key"}
http-error-control threw=Error:ClawRouter usage request failed (HTTP 503)

fixed head 35a2bf736ee56bf2ff001ec7db0c96939b1e7c72
malformed-json snapshot={"provider":"clawrouter","displayName":"ClawRouter","windows":[],"error":"Malformed usage response"}
invalid-utf8 snapshot={"provider":"clawrouter","displayName":"ClawRouter","windows":[],"error":"Malformed usage response"}
valid-control snapshot={"provider":"clawrouter","displayName":"ClawRouter","windows":[],"plan":"Unmetered proxy key"}
http-error-control threw=Error:ClawRouter usage request failed (HTTP 503)
proof-live.ts
import { execFileSync } from "node:child_process";
import { createServer } from "node:http";
import { resolve } from "node:path";
import { pathToFileURL } from "node:url";

async function main(): Promise<void> {
  const usageModuleUrl = pathToFileURL(resolve("extensions/clawrouter/usage.ts")).href;
  const { fetchClawRouterUsage } = await import(usageModuleUrl);

  async function run(body: string | Uint8Array, status = 200): Promise<string> {
    const server = createServer((_req, res) => {
      res.writeHead(status, { "content-type": "application/json" });
      res.end(body);
    });
    await new Promise<void>((resolveListen) => server.listen(0, "127.0.0.1", resolveListen));
    const address = server.address();
    if (!address || typeof address === "string") {
      throw new Error("loopback server did not expose a TCP address");
    }
    try {
      const snapshot = await fetchClawRouterUsage({
        token: "redacted-test-token",
        baseUrl: `http://127.0.0.1:${address.port}`,
        timeoutMs: 5_000,
      });
      return `snapshot=${JSON.stringify(snapshot)}`;
    } catch (error) {
      return `threw=${error instanceof Error ? `${error.name}:${error.message}` : String(error)}`;
    } finally {
      await new Promise<void>((resolveClose, reject) =>
        server.close((error) => (error ? reject(error) : resolveClose())),
      );
    }
  }

  const invalidUtf8 = new Uint8Array([
    ...new TextEncoder().encode('{"budget":{"configured":'),
    0xff,
    ...new TextEncoder().encode("}}"),
  ]);

  console.log(`sha=${execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim()}`);
  console.log(`malformed-json ${await run('{"budget":{"configured":true}')}`);
  console.log(`invalid-utf8 ${await run(invalidUtf8)}`);
  console.log(`valid-control ${await run('{"budget":{"configured":false}}')}`);
  console.log(`http-error-control ${await run("unavailable", 503)}`);
}

void main();

AI-assisted: built with Codex

Maintainer exact-head validation (a02622f369867d32180fe267b19c19e731eeb91b):

  • canonical asOptionalRecord repair applied without widening the response-read catch
  • focused ClawRouter usage tests: 13 passed
  • loopback malformed JSON, invalid UTF-8, valid JSON, HTTP 503, and broken-stream controls passed
  • P1 autoreview: clean, no actionable findings

Punchcard-Session: clear-orchard-lantern-bc

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. P2 Normal backlog priority with limited blast radius. labels Aug 5, 2026
@clawsweeper

clawsweeper Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 5, 2026, 9:17 AM ET / 13:17 UTC.

ClawSweeper review

What this changes

The PR makes malformed ClawRouter quota JSON, invalid UTF-8, and non-object roots produce a stable usage-error snapshot instead of a parser exception.

Merge readiness

⚠️ Ready for maintainer review - 1 item remains

No blocking findings. The exact head fixes the current malformed-payload throw at the provider-owned parsing boundary, resolves the prior canonical-helper finding, and preserves distinct HTTP and body-read failures.

Priority: P2
Reviewed head: a02622f369867d32180fe267b19c19e731eeb91b

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, well-proven provider parsing repair with no actionable source finding.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The PR body contains before/after terminal output from the production usage function through a loopback HTTP boundary, including malformed, valid, and HTTP-error controls; the exact-head follow-up records the expanded focused controls.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The PR body contains before/after terminal output from the production usage function through a loopback HTTP boundary, including malformed, valid, and HTTP-error controls; the exact-head follow-up records the expanded focused controls.
Evidence reviewed 7 items Current failure boundary: Current main fatal-decodes and parses the bounded response outside a catch, so malformed JSON and invalid UTF-8 reject from this provider path.
Owner entry point: The plugin’s provider hook passes this function’s result directly into the generic usage-snapshot flow.
Exact-head repair: The proposed catch begins only after bounded body consumption, converts decode/parse/non-record failures through the canonical record guard, and emits the stable snapshot.
Findings None None.
Security None None.

How this fits together

ClawRouter is a bundled provider plugin that fetches quota data and returns a provider usage snapshot for OpenClaw’s usage display. The changed boundary converts a bounded HTTP response body into either quota data or a user-visible error snapshot.

flowchart LR
  A[Usage refresh] --> B[ClawRouter plugin]
  B --> C[Usage endpoint response]
  C --> D[Bounded body reader]
  D --> E[JSON and record validation]
  E --> F[Usage snapshot]
  E --> G[Stable malformed-response snapshot]
  F --> H[Provider usage display]
  G --> H
Loading

Before merge

  • Complete next step (P2) - No repair lane is needed because the exact-head patch has no actionable finding; normal merge gating remains.
Agent review details

Security

None.

PR surface

Source +11, Tests +41. Total +52 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 16 5 +11
Tests 1 44 3 +41
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 60 8 +52

Review metrics

Metric Value Why it matters
Production vs test delta production +11, tests +41 The small production increase creates one explicit malformed-payload outcome, with focused regression coverage for parsing and stream-error separation.

Stored data model

Persistent data-model change detected: serialized state: extensions/clawrouter/usage.ts. Confirm migration or upgrade compatibility proof before merge.

Technical review

Best possible solution:

Merge the provider-local parsing repair once normal exact-head CI and GitHub merge gates complete; retain the bounded body-read failures as distinct errors.

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

Yes: current main’s fatal decode and JSON parse are outside a catch at the implicated boundary, and the submitted before/after loopback proof exercises that same production function.

Is this the best way to solve the issue?

Yes: handling only decode, JSON, and root-shape failures after the bounded read is the narrowest maintainable fix; copying a broader sibling catch would wrongly normalize stream and size failures.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against d85920c03e25.

Labels

Label justifications:

  • P2: This is a bounded reliability repair for ClawRouter quota refreshes rather than a core-runtime or security emergency.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR body contains before/after terminal output from the production usage function through a loopback HTTP boundary, including malformed, valid, and HTTP-error controls; the exact-head follow-up records the expanded focused controls.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body contains before/after terminal output from the production usage function through a loopback HTTP boundary, including malformed, valid, and HTTP-error controls; the exact-head follow-up records the expanded focused controls.

Evidence

What I checked:

Likely related people:

  • Jason (Json): Blame attributes the current ClawRouter parser boundary and the canonical record-coercion helper to the initial implementation commit. (role: original implementation author; confidence: high; commits: 4b7a989a8bfe; files: extensions/clawrouter/usage.ts, packages/normalization-core/src/record-coerce.ts, src/plugin-sdk/string-coerce-runtime.ts)
  • vincentkoc: Authored the exact-head follow-up that applied the canonical SDK coercion and requested this re-review. (role: recent area contributor; confidence: medium; commits: a02622f36986; files: extensions/clawrouter/usage.ts)

Rating scale

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

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

Workflow

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

History

Review history (1 earlier review cycle)
  • reviewed 2026-08-05T11:13:17.419Z sha 35a2bf7 :: needs changes before merge. :: [P3] Use the canonical record coercion

@vincentkoc vincentkoc self-assigned this Aug 5, 2026
Punchcard-Session: clear-orchard-lantern-bc
@vincentkoc

Copy link
Copy Markdown
Member

@clawsweeper re-review

Applied the durable rank-up move on exact head a02622f369867d32180fe267b19c19e731eeb91b: ClawRouter now uses the canonical asOptionalRecord helper without widening the bounded response-read catch. Focused tests, loopback controls, and P1 autoreview are clean.

@clawsweeper

clawsweeper Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@vincentkoc
vincentkoc merged commit 0d7baff into openclaw:main Aug 5, 2026
91 checks passed
@vincentkoc

Copy link
Copy Markdown
Member

Merged via squash.

vincentkoc added a commit to VACInc/openclaw that referenced this pull request Aug 5, 2026
* origin/main: (130 commits)
  refactor(qa): consolidate scenario runtime helpers (openclaw#119623)
  fix(telegram): bind Mini App auth to dashboard launches
  refactor(agent-core): unify session projection and compaction summaries (openclaw#119639)
  fix(codex): allow natural reactions in the current conversation (openclaw#119649)
  refactor(providers): deduplicate bundled model catalogs (openclaw#119627)
  fix(ui): observe the active service worker after asset refresh (openclaw#119622)
  fix(agents): strip echoed base64 image payloads so photo-heavy turns no longer hit the per-turn output cap (openclaw#119488)
  improve: make state-heavy test suites faster (openclaw#119617)
  perf(agents): add concurrency benchmark (openclaw#119569)
  fix(browser): visibly report failed pairing and tab-sharing actions (openclaw#119526)
  refactor(lobster): consolidate embedded workflow execution (openclaw#119630)
  fix(plugin-sdk): stabilize tuple-derived API baseline ordering (openclaw#119635)
  docs(skills): make full-authority maintainer runs unattended (openclaw#119629)
  fix(managed-child): honor process groups that vanish before cleanup (openclaw#119614)
  fix(ci): stop label-driven automation churn (openclaw#119610)
  fix(media): keep the ttl sweep out of the managed outgoing tree (openclaw#119127)
  fix(claws): remove owner-qualified skills (openclaw#119606)
  fix(clawrouter): show stable error for malformed usage responses (openclaw#119580)
  fix(gateway): claim malformed plugin icon routes (openclaw#119559)
  fix(telegram): preserve truthful empty-content delivery (openclaw#88810)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 6, 2026
…nclaw#119580)

* fix(clawrouter): handle malformed usage responses

* fix(clawrouter): use canonical usage record coercion

Punchcard-Session: clear-orchard-lantern-bc

---------

Co-authored-by: Vincent Koc <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

extensions: clawrouter Extension: clawrouter P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants