Skip to content

fix: Python SDK canonical encoding (ensure_ascii=True) to match TypeScript#91

Open
catchmeifyoucaan wants to merge 1 commit into
mainfrom
fix/python-sdk-ensure-ascii
Open

fix: Python SDK canonical encoding (ensure_ascii=True) to match TypeScript#91
catchmeifyoucaan wants to merge 1 commit into
mainfrom
fix/python-sdk-ensure-ascii

Conversation

@catchmeifyoucaan

@catchmeifyoucaan catchmeifyoucaan commented Jul 16, 2026

Copy link
Copy Markdown

Summary

The Python SDK used \ensure_ascii=False\ in \json.dumps\ during \canonicalize_protocol_value(), while the TypeScript SDK uses \JSON.stringify\ which defaults to escaping non-ASCII characters. This caused cross-SDK hash disagreement for any protocol message containing non-ASCII Unicode (accents, CJK, emoji, etc.), breaking event hash chain integrity.

Change

\\diff

  • return json.dumps(..., ensure_ascii=False)
  • return json.dumps(..., ensure_ascii=True)
    \\

Why

  • \JSON.stringify\ in JavaScript always escapes non-ASCII characters — it is the ECMAScript default
  • Python's \json.dumps\ with \ensure_ascii=True\ produces identical output to \JSON.stringify\
  • Without this fix, any host mixing TypeScript and Python SDKs would compute different event hashes for the same logical message, breaking protocol integrity

Verification

  • All 57 Python SDK tests pass
  • Cross-SDK canonicalization now produces identical strings for the same input, regardless of Unicode content

Finds: JA-TM-01

Summary by CodeRabbit

  • Bug Fixes
    • Updated protocol value serialization to consistently escape non-ASCII characters.
    • Improved consistency of downstream protocol record hashing and canonicalization.

…rue)

The Python SDK used ensure_ascii=False in json.dumps during canonicalization,
while the TypeScript SDK uses JSON.stringify which defaults to escaping non-ASCII
characters. This caused cross-SDK hash disagreement for any protocol message
containing non-ASCII Unicode (accents, CJK, emoji, etc.), breaking event hash
chain integrity.

JA-TM-01 in the Jarvis threat model.
@coderabbitai

coderabbitai Bot commented Jul 16, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

canonicalize_protocol_value now serializes canonical JSON with ensure_ascii=True, changing Unicode escaping in the byte representation consumed by hash_protocol_value.

Changes

Protocol canonicalization

Layer / File(s) Summary
ASCII-safe canonical serialization
packages/python/src/jarvis_protocol/__init__.py
canonicalize_protocol_value now enables ASCII escaping when serializing values used for protocol hashing.

Estimated code review effort: 1 (Trivial) | ~2 minutes

Suggested reviewers: abiorh001

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive The description covers the summary, rationale, and verification, but it omits several template sections like Protocol Surface and Boundary Check. Add the missing template sections, especially Protocol Surface, Boundary Check, Compatibility Impact, Conformance Impact, and the validation checklist.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: updating Python canonical encoding to match TypeScript behavior.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/python-sdk-ensure-ascii

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

❤️ Share

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

@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: 063797eb75

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


def canonicalize_protocol_value(value: Any) -> str:
return json.dumps(_sort_protocol_value(value), separators=(",", ":"), ensure_ascii=False)
return json.dumps(_sort_protocol_value(value), separators=(",", ":"), ensure_ascii=True)

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 JSON.stringify-compatible Unicode encoding

For protocol records containing non-ASCII text (for example a worker display name, review note, or evidence description), this changes Python canonicalization away from the TypeScript helper: packages/typescript/src/index.js uses JSON.stringify(sortProtocolValue(value)), which emits {"text":"Café ☕"}, while ensure_ascii=True emits {"text":"Caf\u00e9 \u2615"}. Because hash_protocol_value hashes these bytes, Python and TypeScript now produce different event hashes for valid Unicode protocol records, breaking cross-SDK hash-chain verification.

Useful? React with 👍 / 👎.

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/python/src/jarvis_protocol/__init__.py`:
- Line 1733: Update the protocol JSON serialization call in the canonicalization
function to use ensure_ascii=False so Unicode characters remain literal and
match JSON.stringify hashing behavior. Add regression coverage for BMP
characters, astral characters, and U+2028/U+2029, while preserving the existing
sorting and compact separator behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: e0d19e8d-34ae-4d97-8c86-ad323761fbce

📥 Commits

Reviewing files that changed from the base of the PR and between e0c4842 and 063797e.

📒 Files selected for processing (1)
  • packages/python/src/jarvis_protocol/__init__.py


def canonicalize_protocol_value(value: Any) -> str:
return json.dumps(_sort_protocol_value(value), separators=(",", ":"), ensure_ascii=False)
return json.dumps(_sort_protocol_value(value), separators=(",", ":"), ensure_ascii=True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== locate protocol serialization functions =="
rg -n "canonicalize_protocol_value|hash_protocol_value|JSON.stringify|ensure_ascii" packages -S

echo
echo "== map python file shape =="
ast-grep outline packages/python/src/jarvis_protocol/__init__.py --view expanded | sed -n '1,220p'

echo
echo "== map possible TypeScript protocol files =="
fd -a -t f ".*" packages | rg "typescript|ts|jarvis_protocol|protocol"

Repository: Flow-Research/jarvis

Length of output: 12495


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
import json

samples = [
    {"text": "café"},
    {"text": "𝄞"},
    {"text": "é😀"},
    {"text": "\u2028"},
]
for v in samples:
    py = json.dumps(v, separators=(",", ":"), ensure_ascii=True)
    py_no = json.dumps(v, separators=(",", ":"), ensure_ascii=False)
    print(v, "ensure_ascii=True ", py)
    print(v, "ensure_ascii=False", py_no)
PY

node - <<'JS'
const samples = [
  {text: "café"},
  {text: "𝄞"},
  {text: "é😀"},
  {text: "\u2028"},
];
for (const v of samples) {
  console.log(v, JSON.stringify(v));
}
JS

Repository: Flow-Research/jarvis

Length of output: 715


Do not canonicalize protocol JSON with ensure_ascii=True.

Python escapes non-ASCII characters (cafécaf\u00e9, astral chars → surrogate escapes), while JSON.stringify keeps them literal. Since this string is hashed, Python and TypeScript will diverge for Unicode payloads. Use ensure_ascii=False (or make both SDKs use the same escaping) and add regression tests for BMP, astral, and U+2028/U+2029 cases.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/python/src/jarvis_protocol/__init__.py` at line 1733, Update the
protocol JSON serialization call in the canonicalization function to use
ensure_ascii=False so Unicode characters remain literal and match JSON.stringify
hashing behavior. Add regression coverage for BMP characters, astral characters,
and U+2028/U+2029, while preserving the existing sorting and compact separator
behavior.

Source: MCP tools

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