CodeSampleX

Sample

json 2.9.1: Navigate Unicode surrogate asymmetry, UTF-8 BOM rejection, Unicode whitespace rejections, and IEEE 754 negative zero float preservation in the Ruby json gem

Verified sample for gem json 2.9.1: Navigate Unicode surrogate asymmetry, UTF-8 BOM rejection, Unicode whitespace rejections, and IEEE 754 negative zero…

sha256:f35dff85940e709eea7e0676276ab4be475c03c3c093131ba97aba4a80221c71

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
2
Signing keys that built it
2
Declared environment ruby linux x64 ruby ruby rubygems

Verification-run environments

Environment Contract Stages Run
ruby 3 · linux debian/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · rubygems@1
2026-08-17
ruby 3 · linux debian/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · rubygems@1
2026-08-18

Case

HOW
Goal
Navigate Unicode surrogate asymmetry, UTF-8 BOM rejection, Unicode whitespace rejections, and IEEE 754 negative zero float preservation in the Ruby json gem
Packages
Symbols
  • JSON.parse
  • JSON.generate
  • JSON::ParserError
  • JSON::GeneratorError
Environment
ruby
Created
2026-08-17T02:44:01Z

Contract

  1. assert JSON.parse accepts lone low surrogates like \uDC00 without raising ParserError, returning an invalid UTF-8 string that fails when passed to JSON.generate, while lone high surrogates like \uD800 raise ParserError immediately
  2. assert JSON.parse rejects a UTF-8 Byte Order Mark at document start with JSON::ParserError because RFC 8259 forbids BOM signatures in JSON text
  3. assert JSON.parse strictly rejects Unicode whitespace characters like non-breaking space U+00A0 and zero-width space U+200B outside string tokens
  4. assert JSON.parse rejects unescaped raw ASCII control characters U+0000 to U+001F in string literals while correctly decoding escaped \u0000 into binary NUL without string truncation
  5. assert JSON.parse preserves IEEE 754 negative zero float sign from "-0.0" producing -0.0 whose reciprocal evaluates to -Infinity

Files

  • Gemfile
  • Gemfile.lock
  • NOTES.md
  • csx.json
  • src/unicode_boundary.rb
  • test/contract.rb

Download the source artifact (tar.gz)

Source

Gemfile
source "https://rubygems.org"

gem "json", "2.9.1"
gem "minitest", "5.27.0"
Gemfile.lock
GEM
  remote: https://rubygems.org/
  specs:
    json (2.9.1)
    minitest (5.27.0)

PLATFORMS
  ruby
  x64-mingw-ucrt

DEPENDENCIES
  json (= 2.9.1)
  minitest (= 5.27.0)

CHECKSUMS
  bundler (4.0.18) sha256=02d9a17429de1847b4e0c9f27a9ee4b20c0a74c0a641b4e77195d6019e3618ac
  json (2.9.1) sha256=d2bdef4644052fad91c1785d48263756fe32fcac08b96a20bb15840e96550d11
  minitest (5.27.0) sha256=2d3b17f8a36fe7801c1adcffdbc38233b938eb0b4966e97a6739055a45fa77d5

BUNDLED WITH
  4.0.18
NOTES.md
# Notes on Ruby JSON Gem Unicode and Domain Boundaries

## 1. What `search_known_solution` answered
`search_known_solution` returned existing sample `sha256:bec86395ce786b02c01ea89597d38d802ad97a4c997dc95aaa3f09e24aeeffe9` ("Read and write JSON in Ruby on an image with no C compiler, where oj cannot be installed, without the built-in json defaults changing the data"), which focuses on fundamental JSON defaults (`symbolize_names`, `to_json` arity/state, float truncation vs `decimal_class: String`, and C-extension resolution).

This sample targets domain boundary edge cases in Unicode handling and number representation: surrogate pair asymmetry, UTF-8 BOM rejection, Unicode whitespace tokens, and IEEE 754 negative zero float preservation.

## 2. What a model would have written instead
A model would assume `JSON.parse` treats all unpaired Unicode surrogates symmetrically by raising `JSON::ParserError`, assume UTF-8 JSON starting with a Byte Order Mark (`\xEF\xBB\xBF`) is parsed transparently without manual stripping, and expect `-0.0` to collapse into positive `0.0`.

## 3. How the wrong version fails
- **Silent failure with green build**: `JSON.parse('["\uDC00"]')` silently succeeds and constructs a `String` containing invalid UTF-8 bytes (`\xED\xB0\x80`, `valid_encoding? == false`), which passes initial parse checks but crashes downstream callers and fails during re-serialization with `JSON::GeneratorError: source sequence is illegal/malformed utf-8`.
- **Loud failures**: Documents starting with UTF-8 BOM fail loudly with `JSON::ParserError: unexpected token`; non-ASCII whitespace outside string tokens (such as `\u00A0` or `\u200B`) fails with `JSON::ParserError`; unescaped raw ASCII control characters (0x00-0x1F) inside string literals fail with `JSON::ParserError`.
csx.json
{"case":{"believed":"JSON.parse validates all escaped Unicode surrogate sequences identically by rejecting any unpaired surrogate with a ParserError.","caseId":"case:sha256:a93a7af59ba1f6a7ced2c6690510b14a3d120530e142a7d90bd18c5cd3df2b29","contract":["assert JSON.parse accepts lone low surrogates like \\uDC00 without raising ParserError, returning an invalid UTF-8 string that fails when passed to JSON.generate, while lone high surrogates like \\uD800 raise ParserError immediately","assert JSON.parse rejects a UTF-8 Byte Order Mark at document start with JSON::ParserError because RFC 8259 forbids BOM signatures in JSON text","assert JSON.parse strictly rejects Unicode whitespace characters like non-breaking space U+00A0 and zero-width space U+200B outside string tokens","assert JSON.parse rejects unescaped raw ASCII control characters U+0000 to U+001F in string literals while correctly decoding escaped \\u0000 into binary NUL without string truncation","assert JSON.parse preserves IEEE 754 negative zero float sign from \"-0.0\" producing -0.0 whose reciprocal evaluates to -Infinity"],"goal":"Navigate Unicode surrogate asymmetry, UTF-8 BOM rejection, Unicode whitespace rejections, and IEEE 754 negative zero float preservation in the Ruby json gem","kind":"HOW","packages":["pkg:gem/json@2.9.1"],"schemaVersion":1,"symbols":["JSON.parse","JSON.generate","JSON::ParserError","JSON::GeneratorError"]},"contractCommand":["ruby","test/contract.rb"],"environment":{"arch":"x64","ecosystem":"gem","executionContext":"ruby","language":"ruby","os":"linux","packageManager":"rubygems","runtime":"ruby","schemaVersion":1},"license":"MIT-0","packages":["pkg:gem/json@2.9.1"],"schemaVersion":1,"symbols":["JSON.parse","JSON.generate","JSON::ParserError","JSON::GeneratorError"],"verifierAdapter":"rubygems@1"}
src/unicode_boundary.rb
# frozen_string_literal: true

require "json"

module UnicodeBoundary
  # UTF-8 Byte Order Mark (BOM) constant
  BOM_UTF8 = "\xEF\xBB\xBF".b.freeze

  # Strips leading UTF-8 BOM if present before passing to JSON.parse,
  # preventing JSON::ParserError on valid UTF-8 documents with BOM.
  def self.parse_with_bom_strip(json_text)
    sanitized = json_text.b.start_with?(BOM_UTF8) ? json_text.byteslice(3..-1) : json_text
    JSON.parse(sanitized)
  end

  # Validates that all strings within parsed JSON data have valid UTF-8 encoding.
  # This catches lone low surrogates (e.g. \uDC00) which JSON.parse silently accepts
  # into malformed UTF-8 String instances with valid_encoding? == false.
  def self.deep_validate_utf8(obj)
    case obj
    when Hash
      obj.all? do |k, v|
        (k.is_a?(String) ? k.valid_encoding? : true) && deep_validate_utf8(v)
      end
    when Array
      obj.all? { |item| deep_validate_utf8(item) }
    when String
      obj.valid_encoding?
    else
      true
    end
  end

  # Safely parses JSON and ensures the parsed object graph contains only valid UTF-8.
  # If a lone low surrogate was accepted by JSON.parse, this raises an EncodingError
  # before downstream operations or JSON.generate fail with GeneratorError.
  def self.safe_parse_unicode(json_text)
    data = JSON.parse(json_text)
    raise Encoding::CompatibilityError, "JSON input contains invalid UTF-8 sequences from unvalidated surrogates" unless deep_validate_utf8(data)

    data
  end

  # Distinguishes negative zero (-0.0) from positive zero (+0.0) in parsed float values.
  def self.negative_zero?(value)
    value.is_a?(Float) && value.zero? && (1.0 / value).negative?
  end
end
test/contract.rb
# frozen_string_literal: true

require "minitest/autorun"
require "json"
require_relative "../src/unicode_boundary"

class JsonUnicodeBoundaryTest < Minitest::Test
  # Contract 1: JSON.parse accepts lone low surrogates like \uDC00 without raising ParserError,
  # returning an invalid UTF-8 string that fails when passed to JSON.generate, while lone
  # high surrogates like \uD800 raise ParserError immediately.
  def test_unicode_surrogate_asymmetry_and_malformed_utf8_generation_failure
    # High surrogate alone raises JSON::ParserError
    err_high = assert_raises(JSON::ParserError) do
      JSON.parse('["\uD800"]')
    end
    assert_match(/incomplete surrogate pair/, err_high.message)

    # Lone low surrogate does NOT raise ParserError; JSON.parse silently emits invalid UTF-8 bytes
    parsed_low = JSON.parse('["\uDC00"]')[0]
    refute parsed_low.valid_encoding?, "Lone low surrogate must result in an invalid UTF-8 string"
    assert_equal Encoding::UTF_8, parsed_low.encoding
    assert_equal [0xED, 0xB0, 0x80], parsed_low.bytes

    # Attempting to re-serialize the malformed string fails with JSON::GeneratorError
    assert_raises(JSON::GeneratorError) do
      JSON.generate([parsed_low])
    end

    # Valid paired surrogates combine into a valid 4-byte UTF-8 emoji character
    parsed_pair = JSON.parse('["\uD83D\uDE00"]')[0]
    assert parsed_pair.valid_encoding?
    assert_equal "😀", parsed_pair
    assert_equal [0xF0, 0x9F, 0x98, 0x80], parsed_pair.bytes
    assert_equal '["😀"]', JSON.generate([parsed_pair])

    # Inverted surrogate pair (low then high) silently accepts low surrogate then fails on high
    err_inverted = assert_raises(JSON::ParserError) do
      JSON.parse('["\uDC00\uD800"]')
    end
    assert_match(/incomplete surrogate pair/, err_inverted.message)

    # Helper detects and prevents unvalidated surrogates from entering the application
    assert_raises(Encoding::CompatibilityError) do
      UnicodeBoundary.safe_parse_unicode('["\uDC00"]')
    end
    safe_data = UnicodeBoundary.safe_parse_unicode('["\uD83D\uDE00"]')
    assert_equal ["😀"], safe_data
  end

  # Contract 2: JSON.parse rejects UTF-8 Byte Order Marks (\xEF\xBB\xBF) at document start
  # with JSON::ParserError because RFC 8259 forbids BOM signatures in JSON text.
  def test_utf8_bom_rejection_and_safe_stripping
    bom_payload = "\xEF\xBB\xBF{\"service\":\"payments\",\"status\":\"active\"}"

    # Direct JSON.parse fails on BOM
    err_bom = assert_raises(JSON::ParserError) do
      JSON.parse(bom_payload)
    end
    assert_match(/unexpected token/, err_bom.message)

    # Stripping leading BOM allows valid JSON parsing
    parsed = UnicodeBoundary.parse_with_bom_strip(bom_payload)
    assert_equal({ "service" => "payments", "status" => "active" }, parsed)
  end

  # Contract 3: JSON.parse strictly rejects Unicode whitespace characters like non-breaking
  # space U+00A0 and zero-width space U+200B outside string tokens.
  def test_unicode_whitespace_strict_rejection
    # RFC 8259 allows ONLY 0x20 (space), 0x09 (tab), 0x0A (LF), 0x0D (CR)
    invalid_whitespace_docs = [
      "\u00A0{\"status\":\"ok\"}", # Non-breaking space U+00A0
      "{\"status\":\"ok\"}\u00A0",
      "\u200B{\"status\":\"ok\"}", # Zero-width space U+200B
      "\u3000{\"status\":\"ok\"}", # Ideographic space U+3000
      "\u2028{\"status\":\"ok\"}", # Line separator U+2028
      "\u2029{\"status\":\"ok\"}"  # Paragraph separator U+2029
    ]

    invalid_whitespace_docs.each do |doc|
      assert_raises(JSON::ParserError, "Expected ParserError for Unicode whitespace in #{doc.inspect}") do
        JSON.parse(doc)
      end
    end

    # Standard ASCII whitespace outside strings is accepted
    valid_doc = "\t \r\n{\"status\":\"ok\"}\r\n "
    assert_equal({ "status" => "ok" }, JSON.parse(valid_doc))
  end

  # Contract 4: JSON.parse rejects unescaped raw ASCII control characters U+0000 to U+001F in
  # string literals while correctly decoding escaped \u0000 into binary NUL without string truncation.
  def test_control_character_escaping_and_null_byte_integrity
    # Raw unescaped newline or tab inside string literal raises ParserError
    assert_raises(JSON::ParserError) do
      JSON.parse("{\"data\":\"line1\nline2\"}")
    end
    assert_raises(JSON::ParserError) do
      JSON.parse("{\"data\":\"col1\tcol2\"}")
    end

    # Escaped control characters parse correctly
    parsed_escaped = JSON.parse('{"data":"line1\nline2\tcol2"}')
    assert_equal "line1\nline2\tcol2", parsed_escaped["data"]

    # Escaped \u0000 preserves full binary NUL in hash keys and values without C-string truncation
    doc_with_nul = JSON.parse('{"key\u0000id":"val\u0000data"}')
    key = doc_with_nul.keys.first
    val = doc_with_nul.values.first

    assert_equal 6, key.bytesize
    assert_equal [107, 101, 121, 0, 105, 100], key.bytes
    assert_equal 8, val.bytesize
    assert_equal [118, 97, 108, 0, 100, 97, 116, 97], val.bytes
    assert_equal "val\0data", doc_with_nul["key\0id"]
  end

  # Contract 5: JSON.parse preserves IEEE 754 negative zero float sign from "-0.0" producing
  # -0.0 whose reciprocal evaluates to -Infinity.
  def test_ieee754_negative_zero_float_preservation
    neg_float = JSON.parse("-0.0")
    pos_float = JSON.parse("0.0")
    neg_int = JSON.parse("-0")

    assert_instance_of Float, neg_float
    assert_instance_of Float, pos_float
    assert_instance_of Integer, neg_int

    assert_equal 0.0, neg_float
    assert_equal 0.0, pos_float
    assert_equal 0, neg_int

    # IEEE 754 reciprocal distinguishes -0.0 from +0.0
    assert_equal(-Float::INFINITY, 1.0 / neg_float)
    assert_equal Float::INFINITY, 1.0 / pos_float
    assert_equal Float::INFINITY, 1.0 / neg_int

    assert UnicodeBoundary.negative_zero?(neg_float)
    refute UnicodeBoundary.negative_zero?(pos_float)
    refute UnicodeBoundary.negative_zero?(neg_int)
  end
end

Origin Seeder

csx-seed