feat(ffi): prove dart-to-rust pipeline and arm64 determinism on device

This commit is contained in:
2026-10-24 22:27:48 +02:00
parent 214ab7aac7
commit e371c72a35
11 changed files with 276 additions and 114 deletions
+2
View File
@@ -7,6 +7,8 @@ Alle nennenswerten Änderungen an diesem Projekt. Format nach
## [Unreleased]
### Added
- (ffi) C-ABI-Probe (`iron_arc_selftest`, `iron_arc_abi_marker`) und Dart-FFI-Screen; **Cross-Target-Determinismus auf arm64-Gerät verifiziert**
- (tooling) `tools/device/*` für Steckbrief, Install, Smoke, Perf, Logs
- (m0) Cargo-Workspace mit `sim`, `content`, `ffi`, `server`, `balance`; `tools/ci.sh`
- (m0) Flutter-App mit `targetSdk 36`, `minSdk 24`, NDK 28.2; `tools/build_rust_android.sh` inkl. 16-KB-Check
- (sim) Q16.16-Fixed-Point, eingecheckte Sinus-LUT, PCG32 mit gepinnter Referenzsequenz
+107 -100
View File
@@ -1,121 +1,128 @@
import 'dart:ffi';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
/// Expected hash for seed 42, recorded on x86_64 host.
/// Must match on arm64 (cross-target determinism, ADR 0002).
const hostHash = '11470816335946967992';
class MyApp extends StatelessWidget {
const MyApp({super.key});
typedef _SelftestC = Uint64 Function(Uint64);
typedef _SelftestDart = int Function(int);
typedef _MarkerC = Uint32 Function();
typedef _MarkerDart = int Function();
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// TRY THIS: Try running your application with "flutter run". You'll see
// the application has a purple toolbar. Then, without quitting the app,
// try changing the seedColor in the colorScheme below to Colors.green
// and then invoke "hot reload" (save your changes or press the "hot
// reload" button in a Flutter-supported IDE, or press "r" if you used
// the command line to start the app).
//
// Notice that the counter didn't reset back to zero; the application
// state is not lost during the reload. To reset the state, use hot
// restart instead.
//
// This works for code too, not just values: Most code changes can be
// tested with just a hot reload.
colorScheme: .fromSeed(seedColor: Colors.deepPurple),
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
typedef _VersionC = Uint32 Function();
typedef _VersionDart = int Function();
class Probe {
final String status;
final String marker;
final String version;
final String hash;
const Probe(this.status, this.marker, this.version, this.hash);
static Probe run() {
try {
final lib = DynamicLibrary.open('libffi.so');
final selftest =
lib.lookupFunction<_SelftestC, _SelftestDart>('iron_arc_selftest');
final marker =
lib.lookupFunction<_MarkerC, _MarkerDart>('iron_arc_abi_marker');
final version = lib.lookupFunction<_VersionC, _VersionDart>(
'iron_arc_sim_version_code');
return Probe(
'RUST OK',
marker().toRadixString(16).padLeft(8, '0'),
(version() / 100).toStringAsFixed(2),
BigInt.from(selftest(42)).toUnsigned(64).toString(),
);
} catch (e) {
return Probe('RUST FAIL', '-', '-', '$e');
}
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
void main() => runApp(const IronArcApp());
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
class IronArcApp extends StatelessWidget {
const IronArcApp({super.key});
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// TRY THIS: Try changing the color here to a specific color (to
// Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
// change color while the other colors stay the same.
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
final probe = Probe.run();
final matches = probe.hash == hostHash;
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData.dark(useMaterial3: true),
home: Scaffold(
backgroundColor: const Color(0xFF101418),
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
//
// TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
// action in the IDE, or press "p" in the console), to see the
// wireframe for each widget.
mainAxisAlignment: .center,
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('You have pushed the button this many times:'),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
const Text('IRON ARC',
style: TextStyle(
fontSize: 34,
fontWeight: FontWeight.w800,
letterSpacing: 4)),
const SizedBox(height: 4),
const Text('M0 pipeline probe',
style: TextStyle(color: Colors.white54)),
const SizedBox(height: 32),
_Row('FFI status', probe.status),
_Row('ABI marker', probe.marker),
_Row('sim version', probe.version),
_Row('device hash', probe.hash),
_Row('host hash', hostHash),
const SizedBox(height: 24),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 16, vertical: 10),
decoration: BoxDecoration(
color: matches ? Colors.green.shade900 : Colors.red.shade900,
borderRadius: BorderRadius.circular(8),
),
child: Text(
matches
? 'DETERMINISM PASS (arm64 == x86_64)'
: 'DETERMINISM MISMATCH',
style: const TextStyle(fontWeight: FontWeight.bold),
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
),
);
}
}
class _Row extends StatelessWidget {
const _Row(this.label, this.value);
final String label;
final String value;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 120,
child: Text(label,
style: const TextStyle(color: Colors.white60, fontSize: 13))),
Expanded(
child: Text(value,
style: const TextStyle(fontFamily: 'monospace', fontSize: 13)),
),
],
),
);
}
+52 -6
View File
@@ -1,8 +1,43 @@
//! Flutter <-> Rust bridge (flutter_rust_bridge API lives here from M3 on).
//! Flutter <-> Rust bridge.
//!
//! Until the flutter_rust_bridge integration (M3) this crate exposes plain
//! C ABI functions so the Android pipeline can be verified end to end.
/// Smoke entry point so the Android build proves the CDylib pipeline works.
pub fn sim_version() -> String {
sim::SIM_VERSION.to_string()
/// Magic marker to verify that the CDylib was loaded and symbols resolve.
pub const ABI_MARKER: u32 = 0x1A2B_3C4D;
/// Returns [`ABI_MARKER`].
#[no_mangle]
pub extern "C" fn iron_arc_abi_marker() -> u32 {
ABI_MARKER
}
/// Runs a fixed scripted match and returns its state hash.
///
/// The same seed must produce the same hash on every target (android arm64,
/// x86_64, wasm). This is the cross-target determinism probe from ADR 0002.
#[no_mangle]
pub extern "C" fn iron_arc_selftest(seed: u64) -> u64 {
let mut sim = sim::state::Sim::default_match(seed);
let _ = sim.submit(sim::state::Command::Fire {
angle_mdeg: 45_000,
power: sim::fixed::from_int(1),
weapon: 1,
});
for _ in 0..300 {
sim.tick();
}
sim.state_hash()
}
/// Returns the simulation version as a packed `major*10000 + minor*100 + patch`.
#[no_mangle]
pub extern "C" fn iron_arc_sim_version_code() -> u32 {
let mut parts = sim::SIM_VERSION.split('.').filter_map(|p| p.parse::<u32>().ok());
let major = parts.next().unwrap_or(0);
let minor = parts.next().unwrap_or(0);
let patch = parts.next().unwrap_or(0);
major * 10_000 + minor * 100 + patch
}
#[cfg(test)]
@@ -10,7 +45,18 @@ mod tests {
use super::*;
#[test]
fn exposes_sim_version() {
assert_eq!(sim_version(), "0.1.0");
fn marker_is_stable() {
assert_eq!(iron_arc_abi_marker(), ABI_MARKER);
}
#[test]
fn selftest_is_deterministic() {
assert_eq!(iron_arc_selftest(42), iron_arc_selftest(42));
assert_ne!(iron_arc_selftest(42), iron_arc_selftest(43));
}
#[test]
fn version_code_is_packed() {
assert_eq!(iron_arc_sim_version_code(), 100);
}
}
+27
View File
@@ -0,0 +1,27 @@
//! Prints the reference state hash for the cross-target determinism probe.
//! Usage: `cargo run -p sim --example selftest -- [seed]`
use std::env;
use sim::fixed::from_int;
use sim::state::{Command, Sim};
fn main() {
let seed: u64 = env::args()
.nth(1)
.and_then(|a| a.parse().ok())
.unwrap_or(42);
let mut sim = Sim::default_match(seed);
sim.submit(Command::Fire {
angle_mdeg: 45_000,
power: from_int(1),
weapon: 1,
})
.expect("scripted command must be valid");
for _ in 0..300 {
sim.tick();
}
println!("seed={seed} sim_version={} hash={}", sim::SIM_VERSION, sim.state_hash());
}
+1 -1
View File
@@ -74,7 +74,7 @@ Little-Endian, keine Padding-Bytes, keine Zeiger, keine Sortierung nach Hash-Wer
| Fließkomma-Verbot | `#![deny(clippy::float_arithmetic)]` + CI-Grep auf `f32`/`f64` in `crates/sim/src` |
| Determinismus-Beweis | Test: gleicher Seed + gleiche Commands ⇒ identischer `final_hash` (über 1000 Seeds) |
| Replay-Roundtrip | `replay → sim → replay'` muss byte-identisch sein (`serde_json::to_string` kanonisch) |
| Cross-Target | Gerät (arm64) loggt `state_hash` eines geskripteten Matches; Host-Binary muss denselben Hash liefern |
| Cross-Target | Gerät (arm64) loggt `state_hash` eines geskripteten Matches; Host-Binary muss denselben Hash liefern — **verifiziert am 2026-10-24**: `11470816335946967992` auf Redmi Note 10 (arm64) und x86_64-Host identisch |
| Optional | `wasm32-wasip1` + `wasmtime` als dritter Beweis in CI |
| Property-Tests | `proptest`: HP ∈ [0, 100], Terrain-Samples ∈ [0, Höhe], kein Panzer unter Terrain, Munition ≥ 0, Tick-Monotonie |
+18
View File
@@ -55,6 +55,24 @@
- Schaden fällt linear statt quadratisch ab (Balancing-Entscheidung offen).
- Spawn-Positionen fest (220 / WORLD_W-220); Karten-Presets folgen in M2.
## Gerät verifiziert (2026-10-24)
| Punkt | Wert |
|---|---|
| Gerät | Xiaomi M2101K7AG (Redmi Note 10), Android 12 / API 31, `arm64-v8a` |
| Display | 1080x2400 @ 440 dpi, 60 Hz, Notch 93 px, Ecken 106 px |
| GPU / RAM | Adreno 612 / 3,5 GB |
| APK | Debug, arm64-only, 144 MB (inkl. Debug-Symbole) |
| FFI | `DynamicLibrary.open("libffi.so")` → `iron_arc_abi_marker` = `1a2b3c4d` |
| **Determinismus** | Geräte-Hash == Host-Hash: `11470816335946967992` (Seed 42, 300 Ticks) |
| Nachweis | Screenshot mit grünem Banner „DETERMINISM PASS (arm64 == x86_64)" |
| Tooling | `tools/device/{steckbrief,install,smoke,perf,logs}.sh` |
**Lesson learned:** Dart-`int` ist vorzeichenbehaftet. Ein `uint64`-Rückgabewert muss als
`BigInt.toUnsigned(64)` formatiert werden, sonst zeigt die UI einen falschen „Mismatch"
(`-6975927737762583624` ist bitgleich mit `11470816335946967992`).
## Nächste Schritte (M2 zuerst)
1. `crates/content`: serde-Modelle + `content_hash` (blake3), JSON für 2 Panzer und 6 Waffen.
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env bash
# Builds (optional), installs and launches the debug APK.
set -euo pipefail
cd "$(dirname "$0")/../.."
ADB=${ADB:-adb}
PKG=${PKG:-com.ironarc.iron_arc}
if [ "${SKIP_BUILD:-0}" != "1" ]; then
(cd app && flutter build apk --debug --target-platform android-arm64)
fi
apk=app/build/app/outputs/flutter-apk/app-debug.apk
[ -f "$apk" ] || { echo "missing $apk" >&2; exit 1; }
$ADB install -r "$apk"
$ADB shell am force-stop "$PKG"
$ADB shell am start -n "$PKG/.MainActivity"
echo 'launched'
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env bash
# Filters logcat for crashes and our native library.
set -euo pipefail
ADB=${ADB:-adb}
$ADB logcat -d -t "${1:-500}" 2>/dev/null | grep -iE 'iron_arc|libffi|FATAL EXCEPTION|AndroidRuntime|signal [0-9]+|backtrace' || true
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# Measures frame statistics for a running app (Android 11+ prints percentiles).
set -euo pipefail
ADB=${ADB:-adb}
PKG=${PKG:-com.ironarc.iron_arc}
SECS=${1:-30}
$ADB shell dumpsys gfxinfo "$PKG" reset > /dev/null
sleep "$SECS"
$ADB shell dumpsys gfxinfo "$PKG" | sed -n '/Total frames rendered/,/HISTOGRAM/p' | head -40
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env bash
# Launches the app and captures a screenshot sequence for visual review.
set -euo pipefail
ADB=${ADB:-adb}
PKG=${PKG:-com.ironarc.iron_arc}
OUT=${OUT:-/tmp/shots}
COUNT=${1:-3}
DELAY=${2:-3}
mkdir -p "$OUT"
$ADB shell am force-stop "$PKG"
$ADB shell am start -n "$PKG/.MainActivity" >/dev/null
for i in $(seq 1 "$COUNT"); do
sleep "$DELAY"
$ADB exec-out screencap -p > "$OUT/shot-$i.png"
done
echo "screenshots in $OUT"
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env bash
# Prints the attached device profile (model, API, display, GPU, RAM).
set -euo pipefail
ADB=${ADB:-adb}
serial=$($ADB devices | awk 'NR>1 && $2=="device" {print $1; exit}')
[ -n "${serial:-}" ] || { echo 'no device attached' >&2; exit 1; }
run() { $ADB -s "$serial" shell "$@" | tr -d '\r'; }
echo "serial : $serial"
echo "model : $(run getprop ro.product.manufacturer) $(run getprop ro.product.model)"
echo "android : $(run getprop ro.build.version.release) (API $(run getprop ro.build.version.sdk))"
echo "abi : $(run getprop ro.product.cpu.abi)"
echo "display : $(run wm size | sed 's/Physical size: //') @ $(run wm density | sed 's/Physical density: //') dpi"
refresh=$(run dumpsys display | grep -m1 -o 'fps=[0-9.]*' || true)
echo "refresh : ${refresh:-unknown}"
gpu=$(run dumpsys SurfaceFlinger | grep -m1 -oE 'Adreno[^,]*|Mali[^,]*|PowerVR[^,]*' || true)
echo "gpu : ${gpu:-unknown}"
echo "ram : $(run cat /proc/meminfo | awk '/MemTotal/ {printf "%.1f GB", $2/1048576}')"