Skip to content

Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.

21.8 KB
Raw Blame

Generated bridge code part 2 and per-language record/diff drivers (audit id A7b)

Scope and coverage ledger

All assigned files were read in full (every line), in chunks of at most about 800 lines.

File Lines Read
src/codegen_java.rs 2304 1-2304 (Java JSON codec, wrapper, driver, JNI typed/wire generation, error class, tests)
src/codegen_c.rs 974 1-974
src/codegen_csharp.rs 951 1-951 (wrapper, STJ codec, driver)
src/codegen_php.rs 397 1-397
src/codegen_powershell.rs 622 1-622
src/codegen_ruby.rs 696 1-696
src/codegen_swift.rs 634 1-634
src/codegen_kotlin.rs 11 1-11 (re-exports the Java generator)
src/harness_c.rs 950 1-950 (includes the Python/ctypes driver)
src/harness_csharp.rs 406 1-406
src/harness_go.rs 280 1-280
src/harness_java.rs 296 1-296
src/harness_kotlin.rs 354 1-354
src/harness_php.rs 336 1-336
src/harness_powershell.rs 312 1-312
src/harness_py.rs 714 1-714 (includes the Python driver)
src/harness_ruby.rs 318 1-318
src/harness_swift.rs 498 1-498

For context I also read parts of src/harness.rs (380-1000: record/diff dispatch, ensure_built, stale_build; 1190-1610: diff_exact, settle; 2100-2500: record_cases) and the "Known limits" and decision tables in DECISIONS.md (L7, M5, M7, M14).

Not covered: the Go driver text itself (codegen_go.rs, outside this assignment; only the Rust glue in harness_go.rs was audited), codegen_py.rs and the Python wrapper (A7a's area). No toolchain for C# (dotnet), PowerShell (pwsh), Kotlin or Swift is installed here, so those drivers were audited by reading only. Reproduced by running the real driver text: Python, Ruby, PHP (extracted from the Rust source into the scratchpad dir .../scratchpad/a7b/). Nothing was built inside the repository and no repo file was modified except this report.

Summary

  • 0 CRITICAL, 1 HIGH, 5 MEDIUM, 6 LOW findings.
  • HIGH: the Ruby, PHP, C#, Java and Swift record drivers silently drop every case whose result cannot be written as JSON. For string code this is the byte-offset trap itself (substr or byteslice in the middle of a multibyte character produces invalid UTF-8). record reports "Recorded N cases" with no mention of the dropped inputs, and the only guard ("no case at all for a function") passes when one case survives. Reproduced for Ruby and PHP.
  • MEDIUM: Python same() accepts any TypeError for any recorded error; Python's enc records numpy, datetime, Decimal, Fraction and UUID results as the type name only; C crash cases are counted as passed without the port running; plain diff has no staleness check for Ruby, C, Go, Java and Kotlin; Python, Ruby, Java, Kotlin, Go and C compare only the return value, so a void/printing/mutating function can be "ported" by an empty body.
  • Good news: the diff drivers really go through the generated wrapper (and Ruby proves it with a source_location check, PHP/PowerShell/Swift/Kotlin load only the wrapper), a Rust panic is never counted as a match except in Swift (by decision M14), and PHP, C# and PowerShell compare captured stdout.
  • The codec is the same code on the record and diff side in every language (good: no one-sided lossy codec), but several codecs are lossy on both sides at once (see A7b-02, A7b-11).

Findings

A7b-01 [H1][H6] [HIGH] [CONFIRMED] Record drivers silently drop cases whose result is not JSON-encodable (byte-slicing traps)

  • Where: src/codegen_ruby.rs:271-277 (rescue JSON::GeneratorError, Encoding::UndefinedConversionError; next), src/codegen_php.rs:291-296 (catch (\JsonException $e) { continue; }), src/codegen_csharp.rs:686-690 and :713-716 (converted == null / writer exception, continue), src/codegen_java.rs:786-788 (invalid / missing skipped), src/harness_swift.rs:346 (Ran::Skipped => continue). The only guard is per function: src/harness_ruby.rs:122-135, src/harness_php.rs:140-153, src/harness_csharp.rs:204-217, src/harness_swift.rs:369-377. Java, Kotlin, Go and C have none.
  • What happens: an input is run through the original; the result string is invalid UTF-8; the case line is never written and nothing is counted or printed. record only fails when a function has zero lines.
  • Failing scenario (reproduced with the real driver text, Ruby 3 and PHP 8): inputs cut("héllo", 2), cut("abc", 2), cut("😀x", 1), echo("z") where cut is byteslice / substr. Output cases.jsonl holds 2 of 4 lines (cut("abc",2) and echo("z")); both functions have at least one case, so record exits 0 with "Recorded 2 cases". A port that uses chars().take(n) (the textbook mistake that analyze warns about as "string offsets, high") passes diff and gate. This is exactly the pitfall "A broken port passed because its case was never recorded" (PHP html_entity_decode), still open mechanically: the rule there is "check by hand".
  • Evidence: Ruby begin out.puts(JSON.generate(line)) ... rescue JSON::GeneratorError ... next end; PHP try { fwrite(... json_encode($line, Codec::FLAGS)) } catch (\JsonException $e) { continue; }.
  • Fix / verification improvement: (1) encode invalid UTF-8 instead of dropping it, as Python already does ({"$bytes": [...]}): Ruby v.encoding == BINARY or !v.valid_encoding? -> {"$bytes": v.bytes}, PHP !mb_check_encoding -> same marker; both sides of the diff use the same enc, so the comparison stays exact. (2) Independently, make every driver emit the number of inputs it could not record and have record print it and fail unless --allow-unrecordable N is given; compare cases.jsonl line count against inputs minus timed-out inputs in harness::summarize. (3) Mutation self-test: for each language add a fixture function that byte-slices a multibyte string and assert that a port using char slicing fails diff.

A7b-02 [H1] [MEDIUM] [CONFIRMED] Python same() accepts any recorded error against any TypeError, and never compares messages

  • Where: src/harness_py.rs:560-567.
  • What happens: error_type(actual) in (error_type(expected), "TypeError"). If the original raised ValueError, a port that raises TypeError (for whatever reason, including a bindings rejection of a valid argument, or a PyO3 result-conversion failure, which also surfaces as TypeError) is a match. Messages are never compared (decision L7/M7 accepts type-only; the extra TypeError wildcard is not recorded anywhere in DECISIONS).
  • Failing scenario: original def parse(s): raise ValueError(...) on empty input; port declared with a parameter type the bindings cannot extract for some inputs, so those calls raise TypeError: argument 's': .... Every error case passes, and so does the gate rule "a recorded failing case for every error path".
  • Evidence: return error_type(actual["error"]) in (error_type(expected["error"]), "TypeError"). Run: same({"error":"ValueError: x"},{"error":"TypeError: whatever"},False) -> True.
  • Fix: the wildcard is only needed when the arguments are rejected. Let the wrapper raise a dedicated exception subclass for extraction failures (or mark them in the message) and accept only that when the original also failed on that argument shape, not any expected error; or require TypeError only when the original's own error is TypeError. Verification: a test with a port that always raises TypeError must fail every non-TypeError error case.

A7b-03 [H1] [MEDIUM] [CONFIRMED] Python enc records objects without __dict__ by type name only (numpy, datetime, Decimal, Fraction, UUID, complex, range, ...)

  • Where: src/harness_py.rs:292-294 (hasattr(v, "__dict__") else {"$repr": type(v).__name__}).
  • What happens: both record and diff use the same enc, so values of these types are equal whenever their class name is. Run on the real driver: Decimal('1.10') and Decimal('9') -> {"$repr":"Decimal"}; datetime(2020,1,1) and datetime(1999,5,5) -> {"$repr":"datetime"}; np.int64(5) and np.int64(6) -> {"$repr":"int64"}; np.array([1,2,3]) and np.array([9,9]) -> {"$repr":"ndarray"}; np.bool_, Fraction, UUID, complex, range likewise.
  • Failing scenario: a function returning Decimal/datetime/numpy values is ported so that it returns a value of that class with wrong content (hand-written PyO3 glue or a custom converter); diff is green. Even if no generated glue can produce such a value (then the port can only fail), the recording carries no information, and neither record nor gate says so.
  • Fix: encode these with a faithful marker ({"$decimal": str(v)}, {"$datetime": v.isoformat()}, numpy via .tolist() plus dtype, fall back to repr(v) rather than the class name), and make the fallback $repr print a warning at record time ("result of type X is not compared by value"). Test: two different Decimal results must produce different enc output.

A7b-04 [H1][H2] [MEDIUM] [CONFIRMED] C: recorded crashes and "pointer outside" cases are counted as passed without running the port

  • Where: src/harness_c.rs driver, diff() (lines ~868-893): if error.startswith("crash:") or error in (...): summary["passed"] += 1; continue; isolated() (824-847) turns any signal, empty output or exit() into crash:. DiffOutcome has no counter for these (src/harness.rs struct), so diff, gate and the report show them inside "N/N cases".
  • What happens: decision M5 documents "any port behavior passes", but the reported number overstates the evidence. Realistic inputs reach it: NULL / out-of-contract arguments into strlen-style code, assert() failures (SIGABRT), functions that call exit() (recorded as crash: no result), and any function returning a pointer into static storage (returns a pointer outside its arguments is also accepted wholesale). A generated suite of edge cases can have a large share of such cases.
  • Failing scenario: original aborts via assert(len > 0) for len == 0; port returns 0 there; diff says "passed" for that case, and gate prints "880/900 cases" including those.
  • Fix: count them in a new DiffOutcome.skipped_undefined and print "N of M cases not compared (original crashed)"; make gate show it and warn (not fail) above a threshold. For abort/assert consider requiring the port to also stop (return a sentinel the wrapper maps to abort) when the crash is SIGABRT.

A7b-05 [H1][H5] [MEDIUM] [CONFIRMED path, plausible trigger] Plain diff does not detect a stale port build for Ruby, C, Go, Java, Kotlin (and wasm)

  • Where: src/harness.rs:789-808 (stale_build only for napi, PyO3, PHP, C#, PowerShell, Swift; _ => return None); ensure_built (702-785) checks existence only and has _ => {} for Ruby, Java, Kotlin. Loaders: harness_c::built_library (crate/target/release/lib*.so), Ruby ruby/<lib>_native.so.
  • What happens: after editing port.rs and running diff without build, these languages test the previous library; a previously passing port keeps "passing" while the source now differs (or vice versa). gate rebuilds first (gate.rs:910), so only plain diff, fuzz, bench and anything that quotes a diff result are exposed.
  • Failing scenario: agent changes port.rs to a version that breaks 40 cases, runs rust-anything diff (forgets build), reads "all passed".
  • Fix: extend stale_build to the Ruby/C/Go/Java/Kotlin library paths (same mtime rule; include path dependencies and Cargo.lock); better, diff runs cargo build itself (cheap when up to date). Test: touch port.rs, run diff for each language, expect the error.

A7b-06 [H1][H4] [MEDIUM] [CONFIRMED] Python, Ruby, Java, Kotlin, Go, C drivers compare only the return value: printing and in-place mutation are invisible

  • Where: harness_py.rs:500-528 (run_case returns only ok/error), codegen_ruby.rs:228-238, codegen_java.rs:731-745. In contrast PHP (codegen_php.rs:243-253, ob_start), C# (:559-578, Console.SetOut) and PowerShell (:351-377, stream capture) record and compare output. C compares buffers/out-params.
  • What happens: a function that only prints, logs, appends to a passed list or mutates a dict returns None/nil/void; the recording is ok: null; an empty port function passes every case. Nothing in bridge or analyze blocks such a function (lang/python.rs has no print/mutation risk), and gate has no "unused parameters" check on the port.
  • Failing scenario: def normalize_inplace(items): items.sort() ported as pub fn normalize_inplace(items: Vec<String>) {}.
  • Fix: capture stdout around the call in the other drivers too (Python contextlib.redirect_stdout, Ruby $stdout = StringIO, Java System.setOut) and record it as output, as PHP/C#/PS do; for Python/Ruby also record the argument state after the call (end_args) when the function returns None. At minimum make analyze/bridge warn on void functions and say that the recorded result is empty.

A7b-07 [H6] [LOW] [CONFIRMED] No per-case timeout in any diff driver except Swift

  • Where: all run() helpers use cmd.output() (harness_py.rs:27, harness_ruby.rs:17, harness_php.rs:16, harness_java.rs:17, harness_csharp.rs:24, harness_powershell.rs:13, harness_go.rs:18, harness_c.rs:17). Record has the watchdog (harness.rs:2204); Swift's run_cases applies it to diff as well.
  • What happens: a port with an infinite loop or an allocation storm hangs diff/gate indefinitely instead of failing that case ("timeout counted as failure"). It is not a false pass, but a CI hang can also be killed by an agent's tool timeout and read as "inconclusive".
  • Fix: reuse the record watchdog (progress file plus kill) for diff, and report timed-out cases as mismatches.

A7b-08 [H1] [LOW] [CONFIRMED] Swift: a recorded trap is matched by any trap, including a Rust panic from an unrelated bug; Skipped is turned into a trap

  • Where: src/harness_swift.rs:391-400 (Some(TRAP) => actual error_type == TRAP), the test at :482-497 asserts same(trap, panic); :439 maps Ran::Skipped to trap_fields(...).
  • What happens: by decision M14 a wrapper turns a Rust panic into fatalError; so an unwrap()/index out of bounds in the port matches an original that trapped on overflow. Ran::Skipped (arguments do not convert, or a result line missing) in diff becomes a trap and also matches a recorded trap. The Skipped route is unreachable in practice (same arms in both drivers), but it is a silent-pass shape.
  • Fix: keep panics distinct (error_type: "panic") and require the Fatal-error text class (overflow / nil / range) to match the recorded one; make Skipped in diff a plain mismatch.
  • Status: not changed. A first fix made a Rust panic fail against a recorded trap, and the Swift CI test (tests/swift.rs, a correct port whose + panics where Swift traps on overflow) failed: M14 says the port reproduces a trap by panicking, so the match is the intended behaviour. A real fix has to compare the kind of trap (overflow, nil, range), not reject panics.

A7b-09 [H1] [LOW] [CONFIRMED] C record: a missing symbol is recorded as the original's behavior (KeyError)

  • Where: src/harness_c.rs driver bind() skips a name with AttributeError (continue), then call() does functions[c["fn"]]; the forked child catches the KeyError (except Exception) and writes {"error": "KeyError: 'name'"} as the recorded result.
  • What happens: a function whose symbol is not in original.so (static function, function in a file that defines main, #ifdef-ed out, header-only inline) gets all its cases recorded as errors. In diff the Rust library has the symbol and returns real values, so these show as mismatches (false fail), or if the port is built to return nothing sensible they count as "error paths" for the gate rule on recorded failing cases.
  • Fix: after bind in record, fail with "symbol X is not defined in the compiled original" before running a case.

A7b-10 [H1] [LOW] [CONFIRMED] C#: serialization faults of the original's result are recorded as the original's exception

  • Where: src/codegen_csharp.rs:561-572: SerializeToElement(r, m.ReturnType, ...) runs inside the try that records catch (Exception e) { Error = e.Message; ErrorType = e.GetType().FullName; }.
  • What happens: a result STJ cannot serialize (cycle, unsupported type, depth limit) is stored as error_type: System.Text.Json.JsonException, not as a driver failure. The same fault would not occur for the port, so the case shows a mismatch (false fail) and the "error path" counter rises.
  • Fix: serialize outside the try, and treat a failure there as "unrecordable" (A7b-01).

A7b-11 [H1] [LOW] [CONFIRMED] Lossy codecs on both sides: Java/Kotlin, PHP, PowerShell write unknown objects by class name only; Java collapses Optional/Set/List/Character/int/long

  • Where: codegen_java.rs:224-228 ({"$object": className}), :190-193 (Optional -> value/null), :175-176 (Character = String); codegen_php.rs:35-37 (['$object' => get_class]); codegen_powershell.rs:111-113.
  • What happens: results the bridge can carry (typed signatures) are fully compared; but any result that falls into the fallback branch (a class without a codec) compares equal for equal class names, and a Java Optional.empty() equals null. These are reachable only when the bridge accepts such a type; lang/java.rs blocks char, but I did not find a general refusal for results that end in $object.
  • Fix: make the fallback branch an error at record time ("unsupported result type X") rather than a class-name marker.

A7b-12 [H5] [LOW] [WEAK] Recording is bound to the recording machine's locale, time zone and PHP/pwsh ini

  • Drivers pin the C locale (harness_c.rs), Ruby encodings (harness_ruby.rs:83) and Java file.encoding (harness_java.rs:183), but not TZ, LANG, Java default locale or .NET culture. The recording is committed; a port derived from a Turkish-locale recording (toUpperCase, ToString()) matches that recording, not the original's behavior elsewhere. Mitigation: set TZ=UTC, LC_ALL=C.UTF-8 (user.language=en, DOTNET_SYSTEM_GLOBALIZATION_INVARIANT as needed) for record, and write the values into recorded-from.json so gate can flag a change. Unverified: whether PowerShell -ceq on JSON text (codegen_powershell.rs:403-407) is ordinal (no pwsh here to test).

Verification improvements for this area (ranked)

  1. Make "dropped inputs" impossible to miss: every driver reports the count of inputs it could not record and why, record prints it, cases.jsonl count is checked against the asked count (A7b-01). Cheapest high-value change.
  2. Encode non-UTF-8 strings as $bytes in Ruby, PHP, C#, Java (as Python already does) so the byte-offset cases are recorded and compared; add a byte-slicing fixture per language and a "port that slices by chars must fail" mutation test.
  3. Add a "not compared" counter to DiffOutcome (C crashes, pointer-outside) and show it next to the pass count in diff, gate, the card and the report (A7b-04).
  4. Extend stale_build to all kinds, or run cargo build inside diff (A7b-05).
  5. Capture stdout (and for void functions, argument state) in the Python, Ruby, Java/Kotlin and Go drivers (A7b-06).
  6. Tighten error comparison: dedicated "bindings rejected arguments" exception for Python, no blanket TypeError wildcard (A7b-02).
  7. Replace the Python $repr and Java/PHP/PS $object fallbacks with faithful encodings or a record-time error (A7b-03, A7b-11).
  8. Give diff the record watchdog (A7b-07) and make Swift Skipped/panic stricter (A7b-08).
  9. Generic mutation self-test harness (one fixture per language, with ~6 "break the port in way W" variants: wrong error type, empty body, char vs byte slicing, off-by-one, returns TypeError) run in CI, asserting diff fails each.

Things checked and found sound (so nobody re-checks them)

  • Diff goes through the wrapper, not the original: Ruby verifies each target's source_location equals the wrapper file (codegen_ruby.rs:251-261) before comparing; PHP, PowerShell, Swift and Kotlin load only the wrapper in diff; C# calls <ns>.Rust.* explicitly; Java puts wrapper classes first on the classpath and the driver resolves methods from that class; Python imports the generated package. No path found where the original answers in diff mode.
  • Record and diff use the same codec code in every language (enc/write/Write/Codec); no one-sided lossy codec found. Python distinguishes int, float ($float), bool, -0, NaN, big ints, bytes, tuple, set, dict order; Ruby distinguishes symbol/string and encodes -0/NaN; Java escapes lone surrogates; C# round-trips $utf16.
  • A Rust panic is never accepted as an expected result: Python (PanicException is a BaseException, type mismatch), Ruby (Rust panic: prefix check), Java, PHP, C#, PowerShell (message / type checks). Swift is the documented exception (A7b-08).
  • Error mapping: Java RustAnythingError.from maps Err("Type: msg") to the named RuntimeException subclass and falls back visibly (a checked exception becomes RuntimeException, which mismatches the recorded type, so the difference is surfaced, not hidden); C#, PHP, PowerShell and Ruby do the same with a visible fallback type. Swift compares type and message.
  • Stdin is closed in record (Stdio::null()) and diff (Command::output). JVM start-up warnings cannot reach results (results travel through files). Timeouts in record are reported ("Left out N inputs").
  • C driver pins the C locale, runs each case in a fork (state-free), and the signatures come from the same manifest for both libraries. Rust ABI helpers in codegen_c.rs (c_str, bytes, len) guard NULL and negative lengths.
  • PHP/C#/PowerShell compare captured stdout in addition to the value; PowerShell records warnings, errors and information streams as output.