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.
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 (
substrorbyteslicein the middle of a multibyte character produces invalid UTF-8).recordreports "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 anyTypeErrorfor any recorded error; Python'sencrecords numpy,datetime,Decimal,FractionandUUIDresults as the type name only; C crash cases are counted as passed without the port running; plaindiffhas 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_locationcheck, 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-690and:713-716(converted == null/ writer exception,continue),src/codegen_java.rs:786-788(invalid/missingskipped),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.
recordonly 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")wherecutisbyteslice/substr. Outputcases.jsonlholds 2 of 4 lines (cut("abc",2)andecho("z")); both functions have at least one case, sorecordexits 0 with "Recorded 2 cases". A port that useschars().take(n)(the textbook mistake that analyze warns about as "string offsets, high") passesdiffandgate. This is exactly the pitfall "A broken port passed because its case was never recorded" (PHPhtml_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; PHPtry { 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": [...]}): Rubyv.encoding == BINARY or !v.valid_encoding?->{"$bytes": v.bytes}, PHP!mb_check_encoding-> same marker; both sides of the diff use the sameenc, so the comparison stays exact. (2) Independently, make every driver emit the number of inputs it could not record and haverecordprint it and fail unless--allow-unrecordable Nis given; comparecases.jsonlline count against inputs minus timed-out inputs inharness::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 failsdiff.
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 raisedValueError, a port that raisesTypeError(for whatever reason, including a bindings rejection of a valid argument, or a PyO3 result-conversion failure, which also surfaces asTypeError) is a match. Messages are never compared (decision L7/M7 accepts type-only; the extraTypeErrorwildcard 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 raiseTypeError: 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
TypeErroronly when the original's own error isTypeError. Verification: a test with a port that always raisesTypeErrormust fail every non-TypeErrorerror 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')andDecimal('9')->{"$repr":"Decimal"};datetime(2020,1,1)anddatetime(1999,5,5)->{"$repr":"datetime"};np.int64(5)andnp.int64(6)->{"$repr":"int64"};np.array([1,2,3])andnp.array([9,9])->{"$repr":"ndarray"};np.bool_,Fraction,UUID,complex,rangelikewise. - 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);diffis green. Even if no generated glue can produce such a value (then the port can only fail), the recording carries no information, and neitherrecordnorgatesays so. - Fix: encode these with a faithful marker (
{"$decimal": str(v)},{"$datetime": v.isoformat()}, numpy via.tolist()plus dtype, fall back torepr(v)rather than the class name), and make the fallback$reprprint a warning at record time ("result of type X is not compared by value"). Test: two differentDecimalresults must produce differentencoutput.
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.rsdriver,diff()(lines ~868-893):if error.startswith("crash:") or error in (...): summary["passed"] += 1; continue;isolated()(824-847) turns any signal, empty output orexit()intocrash:.DiffOutcomehas no counter for these (src/harness.rsstruct), sodiff,gateand 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 intostrlen-style code,assert()failures (SIGABRT), functions that callexit()(recorded ascrash: no result), and any function returning a pointer into static storage (returns a pointer outside its argumentsis 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)forlen == 0; port returns0there;diffsays "passed" for that case, andgateprints "880/900 cases" including those. - Fix: count them in a new
DiffOutcome.skipped_undefinedand print "N of M cases not compared (original crashed)"; makegateshow it and warn (not fail) above a threshold. Forabort/assertconsider requiring the port to also stop (return a sentinel the wrapper maps to abort) when the crash isSIGABRT.
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_buildonly 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), Rubyruby/<lib>_native.so. - What happens: after editing
port.rsand runningdiffwithoutbuild, these languages test the previous library; a previously passing port keeps "passing" while the source now differs (or vice versa).gaterebuilds first (gate.rs:910), so only plaindiff,fuzz,benchand anything that quotes a diff result are exposed. - Failing scenario: agent changes
port.rsto a version that breaks 40 cases, runsrust-anything diff(forgetsbuild), reads "all passed". - Fix: extend
stale_buildto the Ruby/C/Go/Java/Kotlin library paths (same mtime rule; include path dependencies andCargo.lock); better,diffrunscargo builditself (cheap when up to date). Test: touchport.rs, rundifffor 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_casereturns onlyok/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 compareoutput. 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 isok: null; an empty port function passes every case. Nothing inbridgeoranalyzeblocks such a function (lang/python.rshas no print/mutation risk), andgatehas no "unused parameters" check on the port. - Failing scenario:
def normalize_inplace(items): items.sort()ported aspub fn normalize_inplace(items: Vec<String>) {}. - Fix: capture stdout around the call in the other drivers too (Python
contextlib.redirect_stdout, Ruby$stdout = StringIO, JavaSystem.setOut) and record it asoutput, as PHP/C#/PS do; for Python/Ruby also record the argument state after the call (end_args) when the function returnsNone. At minimum makeanalyze/bridgewarn 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 usecmd.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'srun_casesapplies it to diff as well. - What happens: a port with an infinite loop or an allocation storm hangs
diff/gateindefinitely 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-497assertssame(trap, panic);:439mapsRan::Skippedtotrap_fields(...). - What happens: by decision M14 a wrapper turns a Rust panic into
fatalError; so anunwrap()/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. TheSkippedroute 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; makeSkippedin 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.rsdriverbind()skips a name withAttributeError(continue), thencall()doesfunctions[c["fn"]]; the forked child catches theKeyError(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 definesmain,#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
bindinrecord, 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 thetrythat recordscatch (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()equalsnull. These are reachable only when the bridge accepts such a type;lang/java.rsblockschar, 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 notTZ,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: setTZ=UTC,LC_ALL=C.UTF-8(user.language=en,DOTNET_SYSTEM_GLOBALIZATION_INVARIANTas needed) for record, and write the values intorecorded-from.jsonsogatecan flag a change. Unverified: whether PowerShell-ceqon JSON text (codegen_powershell.rs:403-407) is ordinal (no pwsh here to test).
Verification improvements for this area (ranked)
- Make "dropped inputs" impossible to miss: every driver reports the count of inputs it could not record and why,
recordprints it,cases.jsonlcount is checked against the asked count (A7b-01). Cheapest high-value change. - Encode non-UTF-8 strings as
$bytesin 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. - Add a "not compared" counter to
DiffOutcome(C crashes, pointer-outside) and show it next to the pass count indiff,gate, the card and the report (A7b-04). - Extend
stale_buildto all kinds, or runcargo buildinsidediff(A7b-05). - Capture stdout (and for void functions, argument state) in the Python, Ruby, Java/Kotlin and Go drivers (A7b-06).
- Tighten error comparison: dedicated "bindings rejected arguments" exception for Python, no blanket
TypeErrorwildcard (A7b-02). - Replace the Python
$reprand Java/PHP/PS$objectfallbacks with faithful encodings or a record-time error (A7b-03, A7b-11). - Give
diffthe record watchdog (A7b-07) and make SwiftSkipped/panic stricter (A7b-08). - 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
difffails 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_locationequals 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 (
PanicExceptionis aBaseException, 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.frommapsErr("Type: msg")to the namedRuntimeExceptionsubclass and falls back visibly (a checked exception becomesRuntimeException, 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.