commit c6062357312c546d0db3ea6cdbbf8d05bab03299 Author: Marc Mintel Date: Thu Dec 3 16:07:37 2026 +0100 SHARINGAN pokerfreak-splash d5b9a6f (git archive vom Spielrechner, 03.12.) diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..6d2d90a4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,39 @@ +target/ +data/run-* +data/probe-* +data/buckets-200/ +data/pokerbench/ +logs/ +*.log +*.out +*.stop +.env* +scripts/infra/archive/state/ +__pycache__/ +.DS_Store + +# wrangler files +.wrangler +.dev.vars* +!.dev.vars.example +!.env.example + +# local hosted-stack e2e data +data/local-e2e/ +deploy/local/.env + +# build / package output +node_modules/ +dist/ +*.egg-info/ +.venv/ +.pytest_cache/ + +# weights, archives, secrets, local databases +*.plcp +*.plcp.part-* +*.tar +*.pem +*.key +*.db +tinybp/ diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 00000000..ff228595 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,2656 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "abstraction" +version = "0.1.0" +dependencies = [ + "cards", + "iso", + "rayon", +] + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "axum" +version = "0.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edca88bc138befd0323b20752846e6587272d3b03b0343c8ea28a6f819e6e71f" +dependencies = [ + "async-trait", + "axum-core 0.4.5", + "bytes", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit 0.7.3", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "rustversion", + "serde", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core 0.5.6", + "base64 0.22.1", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit 0.8.4", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sha1", + "sync_wrapper", + "tokio", + "tokio-tungstenite 0.29.0", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09f2bd6146b97ae3359fa0cc6d6b376d9539582c7b4220f041a33ec24c226199" +dependencies = [ + "async-trait", + "bytes", + "futures-util", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "rustversion", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bench" +version = "0.1.0" +dependencies = [ + "abstraction", + "blueprint", + "cards", + "nlhe", + "rayon", + "serde", + "serde_json", + "ureq", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "blueprint" +version = "0.1.0" +dependencies = [ + "cards", + "nlhe", + "rayon", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cards" +version = "0.1.0" +dependencies = [ + "rayon", +] + +[[package]] +name = "cc" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfr-lab" +version = "0.1.0" +dependencies = [ + "cards", +] + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "ctutils" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe3e9d21d39e6f39ff46e03d5b621424f88ee23d8a1672c6bfc9ccc7f2da4f6a" +dependencies = [ + "cmov", +] + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "der_derive", + "flagset", + "zeroize", +] + +[[package]] +name = "der_derive" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8034092389675178f570469e6c3b0465d3d30b4505c294a6550db47f3c17ad18" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "crypto-common 0.1.7", + "subtle", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid 0.10.2", + "crypto-common 0.2.2", + "ctutils", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "exploit" +version = "0.1.0" +dependencies = [ + "abstraction", + "bench", + "blueprint", + "cards", + "nlhe", + "rayon", + "serde_json", +] + +[[package]] +name = "fallible-iterator" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443176a9f2c162692bd3d352d745ef9413eec5782a80d8fd6f8a1ac692a07f7" + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "flagset" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe" + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-macro", + "futures-sink", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi 0.11.1+wasi-snapshot-preview1", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashlink" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af" +dependencies = [ + "hashbrown", +] + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", +] + +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "iso" +version = "0.1.0" +dependencies = [ + "cards", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.190" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "libc", +] + +[[package]] +name = "libsqlite3-sys" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matchit" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "md-5" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" +dependencies = [ + "cfg-if", + "digest 0.11.3", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi 0.11.1+wasi-snapshot-preview1", + "windows-sys 0.61.2", +] + +[[package]] +name = "nlhe" +version = "0.1.0" +dependencies = [ + "cards", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags", +] + +[[package]] +name = "objc2-system-configuration" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7216bd11cbda54ccabcab84d523dc93b858ec75ecfb3a7d89513fa22464da396" +dependencies = [ + "objc2-core-foundation", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "openpoker" +version = "0.1.0" +dependencies = [ + "abstraction", + "bench", + "blueprint", + "cards", + "nlhe", + "rayon", + "search", + "serde", + "serde_json", + "tungstenite 0.24.0", + "ureq", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_shared", + "serde", +] + +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "pluribus" +version = "0.1.0" +dependencies = [ + "abstraction", + "bench", + "blueprint", + "cards", + "exploit", + "nlhe", + "rayon", + "serde_json", +] + +[[package]] +name = "postgres" +version = "0.19.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ad20e0aa0b24f5a394eab4f78c781d248982b22b25cecc7e3aa46a681605bd" +dependencies = [ + "bytes", + "fallible-iterator 0.2.0", + "futures-util", + "log", + "tokio", + "tokio-postgres", +] + +[[package]] +name = "postgres-protocol" +version = "0.6.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08808e3c483c46e999108051c78334f473d5adb59d78bb80a1268c7e6aa6c514" +dependencies = [ + "base64 0.22.1", + "byteorder", + "bytes", + "fallible-iterator 0.2.0", + "hmac 0.13.0", + "md-5", + "memchr", + "rand 0.10.3", + "sha2 0.11.1", + "stringprep", +] + +[[package]] +name = "postgres-types" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "851ca9db4932932d69f3ea811b1abe63087a0f740a47692619dd40d4899b68be" +dependencies = [ + "bytes", + "fallible-iterator 0.2.0", + "postgres-protocol", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "referee" +version = "0.1.0" +dependencies = [ + "abstraction", + "bench", + "blueprint", + "cards", + "nlhe", + "rayon", + "serde", + "serde_json", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rusqlite" +version = "0.32.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e" +dependencies = [ + "bitflags", + "fallible-iterator 0.3.0", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", +] + +[[package]] +name = "rustls" +version = "0.23.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "search" +version = "0.1.0" +dependencies = [ + "abstraction", + "bench", + "blueprint", + "cards", + "nlhe", + "pluribus", + "rayon", + "referee", +] + +[[package]] +name = "search-lab" +version = "0.1.0" +dependencies = [ + "cards", + "cfr-lab", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "sharingan-arena" +version = "0.1.0" +dependencies = [ + "axum 0.8.9", + "bench", + "cards", + "futures-util", + "hex", + "hmac 0.12.1", + "libc", + "nlhe", + "postgres", + "rand_chacha 0.9.0", + "rayon", + "reqwest", + "rusqlite", + "rustls", + "serde", + "serde_json", + "sha2 0.10.9", + "tokio", + "tokio-postgres-rustls", + "tokio-tungstenite 0.26.2", + "tracing", + "tracing-subscriber", + "ureq", + "uuid", + "webpki-roots 0.26.11", +] + +[[package]] +name = "sharingan-serve" +version = "0.1.0" +dependencies = [ + "abstraction", + "axum 0.7.9", + "bench", + "blueprint", + "cards", + "http-body-util", + "nlhe", + "rayon", + "search", + "serde", + "serde_json", + "tokio", + "tower", + "ureq", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "stringprep" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" +dependencies = [ + "unicode-bidi", + "unicode-normalization", + "unicode-properties", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tls_codec" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de2e01245e2bb89d6f05801c564fa27624dbd7b1846859876c7dad82e90bf6b" +dependencies = [ + "tls_codec_derive", + "zeroize", +] + +[[package]] +name = "tls_codec_derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tokio-postgres" +version = "0.7.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a528f7d280f6d5b9cd149635c8705b0dd049754bc67d81d31fa25169a93809d3" +dependencies = [ + "async-trait", + "byteorder", + "bytes", + "fallible-iterator 0.2.0", + "futures-channel", + "futures-util", + "log", + "parking_lot", + "percent-encoding", + "phf", + "pin-project-lite", + "postgres-protocol", + "postgres-types", + "rand 0.10.3", + "socket2", + "tokio", + "tokio-util", + "whoami", +] + +[[package]] +name = "tokio-postgres-rustls" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27d684bad428a0f2481f42241f821db42c54e2dc81d8c00db8536c506b0a0144" +dependencies = [ + "const-oid 0.9.6", + "ring", + "rustls", + "tokio", + "tokio-postgres", + "tokio-rustls", + "x509-cert", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.26.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a9daff607c6d2bf6c16fd681ccb7eecc83e4e2cdc1ca067ffaadfca5de7f084" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite 0.26.2", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite 0.29.0", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "tungstenite" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18e5b8366ee7a95b16d32197d0b2604b43a0be89dc5fac9f8e96ccafbaedda8a" +dependencies = [ + "byteorder", + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.8.8", + "rustls", + "rustls-pki-types", + "sha1", + "thiserror 1.0.69", + "utf-8", + "webpki-roots 0.26.11", +] + +[[package]] +name = "tungstenite" +version = "0.26.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4793cb5e56680ecbb1d843515b23b6de9a75eb04b66643e256a396d43be33c13" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1", + "thiserror 2.0.21", + "utf-8", +] + +[[package]] +name = "tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1", + "thiserror 2.0.21", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "2.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d" +dependencies = [ + "base64 0.22.1", + "flate2", + "log", + "once_cell", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "url", + "webpki-roots 0.26.11", +] + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasi" +version = "0.14.7+wasi-0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "883478de20367e224c0090af9cf5f9fa85bed63a95c1abf3afc5c083ebc06e8c" +dependencies = [ + "wasip2", +] + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasite" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66fe902b4a6b8028a753d5424909b764ccf79b7a209eac9bf97e59cda9f71a42" +dependencies = [ + "wasi 0.14.7+wasi-0.2.4", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.9", +] + +[[package]] +name = "webpki-roots" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "whoami" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626c4bac6755d76ffc12cb01b2eac751db1996b9e0041de9aa02c8c211ddc82c" +dependencies = [ + "libc", + "libredox", + "objc2-system-configuration", + "wasite", + "web-sys", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "x509-cert" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94" +dependencies = [ + "const-oid 0.9.6", + "der", + "spki", + "tls_codec", +] + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.62" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86502bf56ac7c77571a32e2647bb2a15894565e981fb2a48d7bde2d91c965a9d" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.62" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5457206954b06561e2608c7e19cf58b1926586d999c246eebe4502f7e2039d1a" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 00000000..c2b7bb07 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,39 @@ +[workspace] +resolver = "2" +members = [ + "engine/cards", "engine/iso", "engine/nlhe", + "sharingan-1/abstraction", "sharingan-1/blueprint", "sharingan-1/search", "sharingan-1/pluribus", "sharingan-1/serve", + "arena/bench", "arena/exploit", "arena/referee", "arena/openpoker", "arena/server", + "research/cfr-lab", "research/search-lab", +] + +[workspace.package] +edition = "2021" +version = "0.1.0" +license = "Apache-2.0" +repository = "https://github.com/markokraemer/poker-sharingan" + +[workspace.dependencies] +cards = { path = "engine/cards" } +rayon = "1.12" +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" + +[profile.release] +opt-level = 3 +lto = "thin" +codegen-units = 1 +debug = 1 +panic = "abort" + +[profile.test] +opt-level = 2 + +[workspace.metadata] +name = "Poker Sharingan" +description = "The poker bot arena: open engine, harness and luck-corrected scoring, plus SHARINGAN-1, an open Pluribus reproduction." + +# Long-running servers: same as release but a panic unwinds (caught per request) instead of aborting the process. +[profile.serve] +inherits = "release" +panic = "unwind" diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..47ad28af --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 Marko Kraemer + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/MODEL_CARD.md b/MODEL_CARD.md new file mode 100644 index 00000000..a9de7029 --- /dev/null +++ b/MODEL_CARD.md @@ -0,0 +1,173 @@ +--- +license: apache-2.0 +library_name: custom +language: +- en +tags: +- poker +- game-theory +- cfr +- mccfr +- reinforcement-learning +- imperfect-information-games +- no-limit-holdem +- rust +pipeline_tag: reinforcement-learning +model-index: +- name: SHARINGAN-1 + results: [] +--- + +# SHARINGAN-1: the C@2e10 Poker Sharingan blueprint + +> This is C@2e10, the earlier checkpoint of the training run that produced [SHARINGAN-2](https://huggingface.co/markokraemer/sharingan-2) at 1.83e11 iterations. The [SHARINGAN-2 model card](https://huggingface.co/markokraemer/sharingan-2) describes the final weights. Both releases have confirmed profitable deviations; longer training is not a robustness guarantee. + +SHARINGAN-1 is an earlier blueprint from [Poker Sharingan](https://github.com/markokraemer/poker-sharingan): an open reproduction of Pluribus (Brown & Sandholm, *Science* 2019) for 6-player no-limit Texas hold'em. This repository holds the +**trained strategy files** and the **card abstraction tables**. Code, training and evaluation tooling: https://github.com/markokraemer/poker-sharingan +(Rust workspace, "library: custom": there is no `transformers`/`pytorch` loader; the weights are read by the Rust crates `blueprint` and `bench`). + +The released weights are blueprint **C@2e10**, with the `medium` action menu. +Optional turn/river search is implemented in Rust, not stored in the weights. +The final 1.83e11-iteration release is +[SHARINGAN-2](https://huggingface.co/markokraemer/sharingan-2). + +## Release status and risk + +This is an open-source research release for local inference and evaluation. +**Known profitable attacks exist against both releases.** A verified frozen +3M-iteration attacker scores +2,307 ±75 mbb/game against C@2e10 and +2,466 ±75 +against final SHARINGAN-2 (duplicate + AIVAT, 95% CI; no search). +These are finite attack lower bounds, not guarantees about maximum exploitation. +Off-menu action translation and fallback decisions remain weaknesses. +Record the model checksum, buckets, sizing, code revision and tracking options. +Hardening is paused at the documented +[checkpoint](https://github.com/markokraemer/poker-sharingan/blob/main/docs/CHECKPOINT.md); +no hosted service is required or promised. + +## What is in this repository + +| file | size | what it is | +|---|---|---| +| `sharingan-1.plcp.part-*` | 124.7 GB | **SHARINGAN-1**: blueprint C after 2e10 iterations (PLCP1 compact). Search is optional code, separate from these weights | +| `C-medium-4.77e10.plcp.part-*` | 141.7 GB | earlier blueprint C checkpoint after 4.77e10 iterations (+3.8 ± 1.0 mbb/game vs C@2e10; the final SHARINGAN-2 is stronger in the reported head-to-head) | +| `B-local-2e10.plcp.part-*` | 28.3 GB | blueprint B (smaller `local` menu): the light option for normal machines | +| `A-paper-2e10.plcp.part-*` | 186.9 GB | blueprint A (paper-style menu) | +| `buckets-200.tar` | 0.28 GB | the 200-bucket card abstraction for postflop streets. Required by every blueprint | +| `SHA256SUMS.models`, `SHA256SUMS.parts` | | checksums of the reassembled files and of every part | + +Files are split into 25 GB parts for upload. Reassemble and check: + +```bash +pip install -U huggingface_hub +hf download markokraemer/sharingan-1 --local-dir weights --include "sharingan-1.plcp.part-*" "buckets-200.tar" "SHA256SUMS.*" # or everything +cd weights && sha256sum -c --ignore-missing SHA256SUMS.parts +cat sharingan-1.plcp.part-* > sharingan-1.plcp && sha256sum -c --ignore-missing SHA256SUMS.models && rm sharingan-1.plcp.part-* +mkdir -p ../data && tar xf buckets-200.tar -C ../data # -> data/buckets-200/ +``` + +The published full-file SHA256 for `sharingan-1.plcp`, used by the verified offline evaluations, is `2a4484f6fabf61470a67c941552f5a97c6f6474e14ea010ef94a41d7b5861300`. Verify the checksum manifest after reassembly. This model-card update changes no weights. + +## Use it + +From a clone of [the repo](https://github.com/markokraemer/poker-sharingan) (`RUSTFLAGS="-C target-cpu=native" cargo build --release`). The files are +memory-mapped: disk is required, RAM only makes it faster. + +```bash +# inference server: POST /v1/act with a hand, get SHARINGAN-1's action (format: sharingan-1/serve/README.md) +./target/release/sharingan-serve --blueprint weights/sharingan-1.plcp --buckets data/buckets-200 --sizing medium --no-auth + +# your own arena with C@2e10 as the house bot (match code revision and tracking options before comparing scores) +ARENA_BLUEPRINT=$PWD/weights/sharingan-1.plcp ARENA_BUCKETS=tables:$PWD/data/buckets-200 ARENA_SIZING=medium ./target/release/sharingan-arena --port 8080 + +# duplicate head-to-head of two blueprints, 6-max, 4M deals +./target/release/pluribus h2h --a weights/C-medium-4.77e10.plcp --sizing-a medium --b weights/sharingan-1.plcp --sizing-b medium \ + --buckets data/buckets-200 --players 6 --deals 4000000 --threads 32 --warm --out h2h.json + +# gauntlet against the built-in bots; trained best response against a frozen blueprint +./target/release/bench gauntlet --hero compact:weights/sharingan-1.plcp --bucketer tables:data/buckets-200 --sizing medium --deals 20000 +./target/release/pluribus exploit-compact --target weights/sharingan-1.plcp --sizing medium --buckets data/buckets-200 \ + --players 6 --iters 12000000 --threads 32 --mem-gb 120 --seat all --warm --eval-deals 20000 --seed 1 --out exploit.json +``` + +Each blueprint must be loaded with its own menu: `medium` for C and SHARINGAN-1, `local` for B, `paper` for A. + +### Formats + +* **PLCP1 (compact policy)**: the playable average strategy only. 8-bit action probabilities plus an infoset index, **about 12 bytes per infoset**. + Produced by `pluribus compact`. Read by `bench`, `openpoker`, `search` (`--policy compact:...` / `search:...`). +* **PLBP4 (full checkpoint)**: `blueprint.bin` with the full regrets and average strategy, enough to **resume training** (`pluribus train --resume`). + Companion `snapshots.sum` (PLSA1) holds the postflop average-strategy snapshots. Checkpoints are written tmp-then-rename. +* **Bucket tables**: `flop.u16`, `turn.u16`, `river.u16` map a suit-isomorphic hand index to a bucket id; `meta.txt` records `buckets 200 200 200`. + Preflop is lossless (169 classes). + +Historical training-store counts: the earlier C phase reached 12.2B infosets (78% of a 460-GB store); A reached 17.0B (store full). These are training-phase counts, not the size of every released checkpoint. The final SHARINGAN-2 compact contains about 14.5B infosets. + +## Model details + +* **Game:** 6-max (2-6 handled by the engine) no-limit hold'em, 100 bb stacks (blueprint). A separate 200 bb heads-up blueprint exists for Slumbot tests and is not part of this release. +* **Algorithm:** parallel external-sampling **Linear MCCFR** with negative-regret pruning. LCFR discount for the first 3.5% of the run, pruning from 1.7% + (95% of iterations, threshold -300M, not on river or terminal actions), averaging from 6.9%, strategy interval 10k. The paper's minute-based schedule is scaled to iterations. +* **Abstraction:** preflop lossless; 200 buckets per postflop street (EMD k-means on equity histograms for flop/turn, OCHS for river). Action menus: + `local` (B), `paper`-style (A), `medium` (C). **Menu must match at load time** (`--sizing`): evaluating a blueprint with the wrong menu gives garbage (about -2,364 mbb/game). +* **Real-time search (code, not weights):** depth-limited MC-LCFR with 4 continuation strategies at the leaves, Bayesian beliefs, off-tree re-search; final config searches turn and river only (`--set flop=0`), 200k iterations. +* **Action translation in the blueprint/player path:** the fixed source uses `BelowMenu::Smallest`, one-step synchronization checks, explicit handoff when synchronization is impossible, and a strength-based fallback. Known profitable attacks remain. This source behavior is separate from the model file and from any deployed worker revision. +* **Seeds:** 2019 for C and A. + +## Training + +| run | menu | iterations reached | wall | notes | +|---|---|---|---|---| +| B | `local` | 2e10 (finished) | ~9.5 h | | +| C, earlier phase | `medium` | 5.55e10 before resuming | ~58 h | 180k -> 355k it/s; subsequently continued to the full budget | +| A | `paper` | 3.43e10 (stopped) | ~66 h | store full at 17.0B infosets | +| C final (SHARINGAN-2) | `medium` | 1.83e11 (finished 2026-11-02) | | the paper's budget; beats SHARINGAN-1 by +5.1 ± 1.2, C@4.77e10 by +2.0 ± 1.0 (3 vs 3) | + +Hardware: 64-core / 576 GB bare-metal servers, about EUR 1.86/h each. The runs B, C and A above add up to about 134 server-hours, about EUR 250 at that rate (training only). + +## Evaluation + +Unless noted otherwise: 6-max, duplicate deals + AIVAT, mbb/game (1 mbb/game = 0.1 bb/100), 95% CI. Full tables and caveats are in [docs/RESULTS.md](https://github.com/markokraemer/poker-sharingan/blob/main/docs/RESULTS.md). + +| test | result | +|---|---| +| C@2e10 vs B-final (3+3, 4M deals/format) | +1.6 +- 1.3 | +| C@4.77e10 vs C@2e10 (3+3) | +3.8 +- 1.0 | +| A@2e10 vs C@2e10 (3+3) | -4.0 +- 1.3 | +| trained best response (12M iters) vs C@2e10 / C@4.77e10 / A@2e10 | -323 +- 62 / -290 +- 59 / -372 +- 61 (this limited attack loses; later adversarial-menu attacks below find profitable deviations) | +| original sombra strategy (tiny bets misread as checks) vs C@2e10 | fixed **offline** build **−420 ± 162**, 20,004 hands. These do not establish current live behavior; see the current reruns in docs/RESULTS.md | +| frozen adversarial-menu attacker (3M iters / 35 GB) vs fixed C@2e10 / final SHARINGAN-2, no search | **+2,307 +- 75 / +2,466 +- 75**, two deal seeds / 1.2M hands per target; verified model/learner inputs | +| API chip-rounding attacker vs C@2e10, search disabled | **+14,283 ± 910**, 20,004 hands at 500/1,000 blinds; actual guarded Core API, chance/attacker corrections only, API target decisions unexposed. This is not the native 50/100 blueprint protocol | +| strong profile LBR vs fixed C@2e10 (raw duplicate winnings, no AIVAT) | **+841 +- 162**, 20k deals / 120k hands; exactly reproduced on a verified public model copy | +| search (turn+river) vs 5 x C@2e10 | +87 +- 27 | +| search (turn+river) vs rule bots chart6 / loose / tight | +59 / +108 / +66 | +| Open Poker live, final config (with search), 2,329 hands | +77.6 bb/100, 95% CI [26, 129] (all-in adjusted) | +| offline vs SvanBot at its live budget, C@4.77e10 blueprint: 1 SvanBot vs 5 x blueprint / 1 blueprint vs 5 x SvanBot | SvanBot -46.9 +- 21.2 / blueprint +56.7 +- 34.7 | + +## Intended use + +Research on imperfect-information game solving, abstraction and real-time search; benchmarking other poker agents; studying +6-player strategy optimization; playing against the bot locally or on arenas that explicitly allow bots. + +The sync fix is in source commit [05f59cc](https://github.com/markokraemer/poker-sharingan/commit/05f59cc) and later. Rebuild the Rust player/worker when adopting that fix; downloading the same weights does not update a previously compiled executable. This addresses the original translation bug, not all profitable attacks. + +## Limitations and risks + +* **Not evaluated against strong humans** or against other top solvers; external references are one bot arena and one offline bot, both with caveats. +* **Confirmed profitable deviations remain:** the strongest tested frozen trained learner wins +2,307 +- 75 against C@2e10 and +2,466 +- 75 against final SHARINGAN-2 without search. These finite attacks supply lower bounds, not equilibrium-gap estimates or guarantees about other attacks. Search-augmented play was not tested for exploitability. +* Trained for six-max, 100 bb stacks; native heads-up play is out of distribution. Very deep stacks need an external stack-reset guard (`--max-stack-bb`) or the strategy is out of distribution. +* Model weights and source-level fixes do not by themselves identify the version used by a hosted benchmark. +* The API has a separate real/scaled-chip replay and fallback path. A measured chip-rounding attack profits against C@2e10 with search disabled; the terminal-replay panic guard does not repair the poker weakness of check/fold fallback. See iteration 10 in the results. +* Off-menu bet sizes are handled by action translation; sizes far from the menu are the main exploitable surface in this class of agents. +* Self-play performance and the ability to exploit weak opponents are different measurements; do not infer either from the other. +* Files are very large and need correspondingly large disk/RAM; use B (28 GB) or a `--min-visits` pruned compact for constrained machines. +* **Dual use:** a strong poker agent can be used to cheat on real-money sites, which prohibit bots. Do not use it for that. + +## Citation + +```bibtex +@article{brown2019superhuman, + title = {Superhuman AI for multiplayer poker}, + author = {Brown, Noam and Sandholm, Tuomas}, + journal = {Science}, volume = {365}, number = {6456}, pages = {885--890}, year = {2019} +} +``` diff --git a/NOTICE b/NOTICE new file mode 100644 index 00000000..13b573e1 --- /dev/null +++ b/NOTICE @@ -0,0 +1,37 @@ +SHARINGAN +Copyright 2026 Marko Kraemer +Licensed under the Apache License, Version 2.0. + +This product includes or derives from the following third-party work: + +* engine/iso is a Rust port of the hand-isomorphism indexer by Kevin Waugh + (https://github.com/kdub0/hand-isomorphism, `hand_index.c`; K. Waugh, "A Fast and + Optimal Hand Isomorphism Algorithm", 2013), distributed under this notice: + + Copyright (c) 2013 Kevin Waugh (waugh@cs.cmu.edu). + All rights reserved. + + Redistribution and use in source and binary forms are permitted + provided that the above copyright notice and this paragraph are + duplicated in all such forms and that any documentation, + advertising materials, and other materials related to such + distribution and use acknowledge that the software was developed + by the . The name of the + may not be used to endorse or promote products derived + from this software without specific prior written permission. + THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. + + The hand-isomorphism indexer was developed by Kevin Waugh. + +External tools that are used as opponents or data but are NOT redistributed here: +* RLCard (https://github.com/datamllab/rlcard, MIT): arena/adapters/rlcard_*.py are our own + bridge/training scripts that import it at runtime. +* PokerBench (HF `RZ412/PokerBench`, Apache-2.0 per its dataset card): download it separately. +* SvanBot (https://github.com/SvanLabs/SvanBot, Apache-2.0): arena/adapters/svan/extbridge.rs is our own + glue code that links against SvanBot's crates at build time; SvanBot's source is not included. +* Open Poker (openpoker.ai) and Slumbot (slumbot.com): public services used through their APIs. + +The Pluribus paper and supplement (Brown & Sandholm, Science 2019) are copyrighted by +their publisher and are not included. diff --git a/README.md b/README.md new file mode 100644 index 00000000..a7e06856 --- /dev/null +++ b/README.md @@ -0,0 +1,59 @@ +# Poker Sharingan + +An open-source Rust reproduction of the Pluribus method for six-player no-limit +Texas hold'em: training, blueprint inference, optional real-time search, and +reproducible duplicate-deal + AIVAT evaluation. Apache-2.0 licensed. + +[SHARINGAN-2 weights](https://huggingface.co/markokraemer/sharingan-2) · +[SHARINGAN-1 weights](https://huggingface.co/markokraemer/sharingan-1) · +[Method](docs/METHOD.md) · [Evaluation](docs/EVALUATION.md) + +## Models + +SHARINGAN-2 is blueprint C trained for **1.83e11 iterations**. SHARINGAN-1 is the +**2e10-iteration checkpoint of the same run**. Both use the medium action menu, +200 postflop buckets, six players and 100 bb starting stacks. Real-time search +is optional Rust code, not part of the weight files. + +The final blueprint scores **+5.09 ± 1.16 mbb/game** against SHARINGAN-1 in the +3-versus-3 format (4M duplicate deals, 95% CI). This measures relative playing +strength, not resistance to exploitation. + +## Research limits + +Both models have known exploitable weaknesses, particularly around off-menu bets. +They are research baselines, not guaranteed optimal strategies. +[Evaluation results](docs/RESULTS.md#action-translation-leak-and-fix-nov-2026) · +[Research checkpoint](docs/CHECKPOINT.md) + +## Use locally + +Download and verify the model and bucket files using the +[model cards](model-cards/README.md), then build the Rust tools: + +```bash +cargo build --release -p sharingan-serve -p bench -p exploit -p pluribus +./target/release/sharingan-serve \ + --blueprint weights/sharingan-2.plcp --buckets data/buckets-200 \ + --sizing medium --no-auth +``` + +Use `--no-auth` only in an isolated local environment. See the +[inference server documentation](sharingan-1/serve/README.md) for authentication, +request formats and search configuration. The weights are memory-mapped; plan +for sufficient disk space and substantial RAM for practical evaluation speed. + +## Repository + +- `engine/`: poker rules. +- `arena/`: evaluation harness, scoring, reference bots and self-hosted server. +- `sharingan-1/`: training, search and inference code for both model releases. +- `sdk/`: Python and TypeScript clients. +- `research/`: small-game experiments. +- `docs/`: methods, training instructions and measured results. + +[Train from scratch](docs/TRAINING.md) · [Results](docs/RESULTS.md) · +[Self-host](arena/server/README.md#self-host) · [API](docs/TABLE_API.md) + +For research and local experimentation. Do not use bots to cheat on real-money +poker services. diff --git a/arena/adapters/rlcard_bot_server.py b/arena/adapters/rlcard_bot_server.py new file mode 100644 index 00000000..49d69112 --- /dev/null +++ b/arena/adapters/rlcard_bot_server.py @@ -0,0 +1,60 @@ +"""JSON-lines bridge server around an RLCard no-limit hold'em DQN (see arena/bench/src/ext.rs +for the protocol). argv[1] = checkpoint written by rlcard_train.py. Dev box only; run with -I. + +RLCard NLHE observation (rlcard/envs/nolimitholdem.py): 54-vector = one-hot of board+hole cards +(52) + my chips committed + max chips committed (RLCard units; we scale our chips by 1/50 so a +100 bb stack = 200 chips, bb = 2, matching the training env). Five abstract actions: +0 fold, 1 check/call, 2 raise half pot, 3 raise pot, 4 all-in. +""" +import sys, json, os, torch, numpy as np +from collections import OrderedDict +import rlcard +from rlcard.agents import DQNAgent + +torch.set_num_threads(1) +ck = torch.load(sys.argv[1], weights_only=False) +agent = DQNAgent.from_checkpoint(ck) +c2i = json.load(open(os.path.join(rlcard.__path__[0], 'games/limitholdem/card2index.json'))) +SC = 1.0 / 50.0 +SUIT = {'s': 'S', 'h': 'H', 'd': 'D', 'c': 'C'} + + +def conv(c): # "As" -> "SA" + return SUIT[c[1]] + c[0] + + +def decide(r): + cards = [conv(c) for c in r['board'] + r['hole']] + obs = np.zeros(54) + obs[[c2i[c] for c in cards]] = 1 + me = r['seat'] + obs[52] = r['contrib'][me] * SC + obs[53] = max(r['contrib']) * SC + L = r['legal'] + legal = [0, 1] + if L['raise']: + legal += [2, 3, 4] + st = {'obs': obs, 'legal_actions': OrderedDict((a, None) for a in legal), 'raw_legal_actions': list(legal)} + a, _ = agent.eval_step(st) + a = int(a) + pot, call, cur = r['pot'], r['call_amount'], r['cur_bet'] + if a == 0: + return {'action': 'fold'} + if a == 1: + return {'action': 'call'} + if a == 2: + return {'action': 'raise', 'to': int(cur + 0.5 * (pot + call))} + if a == 3: + return {'action': 'raise', 'to': int(cur + (pot + call))} + return {'action': 'allin'} + + +for line in sys.stdin: + r = json.loads(line) + try: + out = decide(r) + except Exception as e: # never die: report and let the bridge fall back + print(json.dumps({'id': r['id'], 'error': str(e)}), flush=True) + continue + out['id'] = r['id'] + print(json.dumps(out), flush=True) diff --git a/arena/adapters/rlcard_train.py b/arena/adapters/rlcard_train.py new file mode 100644 index 00000000..ce72138e --- /dev/null +++ b/arena/adapters/rlcard_train.py @@ -0,0 +1,38 @@ +"""Train an RLCard DQN on 6-max no-limit hold'em by self-play (one network, all 6 seats). + +RLCard ships NO pretrained no-limit hold'em model (its model zoo has leduc/limit/uno/...), +so this is "the public learned NLHE agent you can actually obtain": the stock RLCard DQN, +trained here. Runs on the dev box only: ~/extbots/rlcard-env/venv/bin/python -I rlcard_train.py +Env: 100 bb deep (chips_for_each=200, bb=2), 6 players, RLCard's 5 abstract actions. +""" +import sys, time, torch, numpy as np, rlcard +from rlcard.agents import DQNAgent +from rlcard.utils import reorganize + +out = sys.argv[1] +minutes = float(sys.argv[2]) +torch.set_num_threads(int(sys.argv[3]) if len(sys.argv) > 3 else 4) +env = rlcard.make('no-limit-holdem', config={'game_num_players': 6, 'chips_for_each': 200, 'seed': 7}) +agent = DQNAgent(num_actions=env.num_actions, state_shape=env.state_shape[0], mlp_layers=[256, 256], + replay_memory_size=200000, replay_memory_init_size=2000, update_target_estimator_every=1000, + epsilon_decay_steps=int(minutes * 60 * 40 * 12 * 0.5), batch_size=128, learning_rate=5e-5, + train_every=4, device=torch.device('cpu')) +env.set_agents([agent] * 6) +t0 = time.time(); hands = 0; last = t0 +SC = 1.0 / 20.0 # payoff scale: 10 bb = 1 +while time.time() - t0 < minutes * 60: + traj, pay = env.run(is_training=True) + traj = reorganize(traj, pay) + for p in range(6): + for ts in traj[p]: + ts = list(ts) + ts[2] = ts[2] * SC + agent.feed(ts) + hands += 1 + if time.time() - last > 120: + last = time.time() + print(f'{(last-t0)/60:.1f} min hands {hands} ({hands/(last-t0):.1f}/s) eps_step {agent.total_t}', flush=True) + agent.save_checkpoint('/'.join(out.split('/')[:-1]) or '.', filename=out.split('/')[-1]) +agent.save_checkpoint('/'.join(out.split('/')[:-1]) or '.', filename=out.split('/')[-1]) +torch.save(agent.q_estimator.qnet.state_dict(), out + '.qnet.pt') +print('done', hands, flush=True) diff --git a/arena/adapters/run_rlcard.sh b/arena/adapters/run_rlcard.sh new file mode 100755 index 00000000..5be09744 --- /dev/null +++ b/arena/adapters/run_rlcard.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# Dev box only. B-final / chart6 / builtins vs the RLCard DQN (Python bridge). +set -u +cd ~/pluribus +export RAYON_NUM_THREADS=${THREADS:-16} +B=data/eval/B-it20000000000-20261013T1354Z/compact.plcp +BIN=target/extbots/release/bench +OUT=data/extbots-results; mkdir -p $OUT +M=$HOME/extbots/rlcard-models/dqn6-final.pt +cp -n $HOME/extbots/rlcard-models/dqn6 $M +D=${DEALS:-20000} +X="--ext-workers 16 --ext-timeout-ms 10000" +H="--hero compact:$B --sizing local --bucketer tables:data/buckets-200" +echo "### B vs 5x rlcard ($D deals)"; $BIN table $H --field rlcard:$M --deals $D --seed 201 $X 2>&1 | tee $OUT/B-vs-5x-rlcard.txt | grep -v '^$' +echo "### mixed 3: B + chart6, chart6-loose, chart6-tight, rlcard, tag ($D deals)" +$BIN table $H --field chart6,chart6-loose,chart6-tight,rlcard:$M,tag --deals $D --seed 202 $X 2>&1 | tee $OUT/mixed-rlcard.txt | grep -v '^$' +echo "### chart6 vs 5x rlcard (5000 deals)"; $BIN table --hero chart6 --field rlcard:$M --deals 5000 --seed 203 $X 2>&1 | tee $OUT/chart6-vs-5x-rlcard.txt | grep -v '^$' +for f in random station tag lag; do + echo "### rlcard vs 5x $f (3000 deals)"; $BIN table --hero rlcard:$M --field $f --deals 3000 --seed 204 $X 2>&1 | tee $OUT/rlcard-vs-5x-$f.txt | grep -v '^$' +done +echo DONE diff --git a/arena/adapters/run_rules.sh b/arena/adapters/run_rules.sh new file mode 100755 index 00000000..fd4f29bf --- /dev/null +++ b/arena/adapters/run_rules.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# Dev box only. B-final vs rule-based bots: hero vs 5x each, plus mixed tables. Duplicate + AIVAT. +set -u +cd ~/pluribus +export RAYON_NUM_THREADS=${THREADS:-16} +B=data/eval/B-it20000000000-20261013T1354Z/compact.plcp +BIN=target/extbots/release/bench +OUT=data/extbots-results; mkdir -p $OUT +D=${DEALS:-100000} +H="--hero compact:$B --sizing local --bucketer tables:data/buckets-200" +for f in chart6 chart6-loose chart6-tight tag lag nit maniac station; do + echo "### B vs 5x $f ($D deals)"; $BIN table $H --field $f --deals $D --seed 101 2>&1 | grep -v '^report' | tee $OUT/B-vs-5x-$f.txt +done +echo "### mixed 1: B + chart6, chart6-loose, chart6-tight, tag, lag" +$BIN table $H --field chart6,chart6-loose,chart6-tight,tag,lag --deals $D --seed 102 2>&1 | grep -v '^report' | tee $OUT/mixed-rules-1.txt +echo "### mixed 2: B + chart6, chart6-loose, nit, maniac, station" +$BIN table $H --field chart6,chart6-loose,nit,maniac,station --deals $D --seed 103 2>&1 | grep -v '^report' | tee $OUT/mixed-rules-2.txt +echo DONE diff --git a/arena/adapters/svan/agg_stats.py b/arena/adapters/svan/agg_stats.py new file mode 100644 index 00000000..b0269c1a --- /dev/null +++ b/arena/adapters/svan/agg_stats.py @@ -0,0 +1,18 @@ +import json,glob,sys +d=sys.argv[1] +fs=[json.load(open(f)) for f in glob.glob(d+"/w*.json")] +tot={} +for k in ["decisions","replay_mismatch","replay_err","panics","fold_when_free","raise_unavailable","observe_err"]: + tot[k]=sum(x[k] for x in fs) +print("workers",len(fs),tot) +if fs: + n=max(1,tot["decisions"]) + print("ms_mean",round(sum(x["ms_mean"]*x["decisions"] for x in fs)/n,2),"median-of-p50",sorted(x["ms_p50"] for x in fs)[len(fs)//2],"max-p95",max(x["ms_p95"] for x in fs),"max-p99",max(x["ms_p99"] for x in fs),"max",max(x["ms_max"] for x in fs)) + acts={} + for x in fs: + for k,v in x["acts"].items(): acts[k]=acts.get(k,0)+v + print("acts",dict(sorted(acts.items()))) + pre=sum(x["me_preflop"]["hands"] for x in fs) + print("SvanBot first preflop decision: n",pre,"VPIP",round(sum(x["me_preflop"]["vpip"]*x["me_preflop"]["hands"] for x in fs)/max(1,pre),3),"PFR",round(sum(x["me_preflop"]["pfr"]*x["me_preflop"]["hands"] for x in fs)/max(1,pre),3)) + b=max(fs,key=lambda x:x["observed_hands"]) + print("observed hands (largest worker)",b["observed_hands"],"entrant stats (seat-hands, vpip, pfr):",{k:(v["hands"],round(v["vpip"],3),round(v["pfr"],3)) for k,v in b["entrants"].items()}) diff --git a/arena/adapters/svan/cd.sh b/arena/adapters/svan/cd.sh new file mode 100755 index 00000000..8317e459 --- /dev/null +++ b/arena/adapters/svan/cd.sh @@ -0,0 +1,5 @@ +#!/bin/bash +SVAN_LEARN=0 ~/svan/tools/run.sh abl-a-cold svan B 100000 11002 +SVAN_LEARN=0 ~/svan/tools/run.sh abl-b-cold B svan 100000 12002 +~/svan/tools/run.sh c-search-vs-svan search svan 40000 13101 --set flop=0 +~/svan/tools/run.sh d-svan-vs-search svan search 12000 14101 --set flop=0 diff --git a/arena/adapters/svan/extbridge.rs b/arena/adapters/svan/extbridge.rs new file mode 100644 index 00000000..5db51511 --- /dev/null +++ b/arena/adapters/svan/extbridge.rs @@ -0,0 +1,458 @@ +//! `extbridge` — plays SvanBot's REAL live decision policy (`sv10_policy::policy::decide_with`, default +//! `Params`, learning `ModelStore`) inside the Pluribus-reproduction benchmark harness. +//! +//! Protocol: JSON lines over stdin/stdout, as in pluribus `arena/bench/src/ext.rs` +//! (`arena/adapters/rlcard_bot_server.py` is the reference). Two kinds of input line: +//! * a decision request (`id`, `seat`, `hole`, `board`, `stacks`, `contrib`, `history`, `who`, ...) +//! -> one reply line `{"id":N,"action":"fold|check|call|raise|allin","to":T}`; +//! * an `observe` line (a finished hand with all hole cards) -> no reply; feeds the opponent models. +//! +//! The request is converted by REPLAYING the public history through SvanBot's own engine (`Hand`), so the +//! `Situation` (pot, bets, history records, min/max raise, positions) is exactly what its live/sim path +//! builds (`Situation::from_hand`). Opponent names are `es` so identical bots in different seats +//! keep separate, persistent profiles; our own seat is `me`. +//! +//! Env: `SVAN_STATS_DIR` (per-process stats json), `SVAN_LEARN=0` to freeze models (cold priors only). +//! `extbridge selftest` runs the conversion unit tests on hand-written spots. + +use serde_json::{Value, json}; +use std::collections::HashMap; +use std::io::{BufRead, Write}; +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::time::Instant; +use sv10_core::cards::Card; +use sv10_core::engine::{Action, ActionKind, Hand}; +use sv10_core::model::{HandSummary, ModelStore, aggressive}; +use sv10_core::policy::{Params, decide_with}; +use sv10_core::situation::Situation; +use sv10_rng::SeedableRng; +use sv10_rng::rngs::SmallRng; + +#[derive(Default)] +struct EntStat { + hands: u64, + vpip: u64, + pfr: u64, +} + +#[derive(Default)] +struct Stats { + decisions: u64, + ms_total: f64, + ms: Vec, + replay_mismatch: u64, + replay_err: u64, + panics: u64, + fold_when_free: u64, + raise_unavailable: u64, + observed: u64, + observe_err: u64, + /// my action counts by street name and kind + acts: HashMap, + ents: HashMap, + /// preflop first decision tallies for "me": hands seen / vpip / pfr (decision level) + me_pre_hands: u64, + me_pre_vpip: u64, + me_pre_pfr: u64, +} + +struct Bot { + models: ModelStore, + params: Params, + learn: bool, + stats: Stats, + stats_path: Option, +} + +fn cards(v: &Value) -> Result, String> { + v.as_array() + .ok_or("cards not an array")? + .iter() + .map(|c| Card::parse(c.as_str().unwrap_or("")).ok_or_else(|| format!("bad card {c}"))) + .collect() +} + +fn unused(used: &[Card], k: usize) -> Vec { + (0..52u8).map(Card).filter(|c| !used.contains(c)).take(k).collect() +} + +/// Replay `hist` (public events) through SvanBot's engine. Seat 0 = SB, 1 = BB, last = button (our harness). +fn build_hand(n: usize, sb: i64, bb: i64, start: &[i64], holes: &[[Card; 2]], runout: [Card; 5], hist: &[Value]) -> Result { + let seats = (0..n).map(|s| Hand::seat_state(start[s], holes[s])).collect(); + let mut h = Hand::with_cards(seats, runout, n - 1, sb, bb); + for (i, e) in hist.iter().enumerate() { + let seat = e["seat"].as_u64().ok_or("event seat")? as usize; + if h.actor() != Some(seat) { + return Err(format!("event {i}: engine actor {:?} != {seat}", h.actor())); + } + let a = match e["kind"].as_str().unwrap_or("") { + "fold" => Action::Fold, + "check" => Action::Check, + "call" => Action::Call, + "raise" => Action::RaiseTo(e["to"].as_i64().ok_or("raise to")?), + k => return Err(format!("unknown kind {k}")), + }; + h.apply(a).map_err(|m| format!("event {i} {e}: {m}"))?; + } + Ok(h) +} + +fn names_for(me: usize, who: &[usize], n: usize) -> Vec { + (0..n) + .map(|s| { + if s == me { + "me".to_string() + } else if who.len() == n { + format!("e{}s{}", who[s], s) + } else { + format!("s{s}") + } + }) + .collect() +} + +fn who_of(r: &Value, n: usize) -> Vec { + match r["who"].as_array() { + Some(a) if a.len() == n => a.iter().map(|x| x.as_u64().unwrap_or(0) as usize).collect(), + _ => Vec::new(), + } +} + +/// Request -> (SvanBot `Situation`, replay mismatch flag). +fn situation_from_request(r: &Value) -> Result<(Situation, bool), String> { + let n = r["players"].as_u64().ok_or("players")? as usize; + let me = r["seat"].as_u64().ok_or("seat")? as usize; + let (sb, bb) = (r["sb"].as_i64().ok_or("sb")?, r["bb"].as_i64().ok_or("bb")?); + let hole = cards(&r["hole"])?; + let board = cards(&r["board"])?; + let stacks: Vec = r["stacks"].as_array().ok_or("stacks")?.iter().map(|x| x.as_i64().unwrap_or(0)).collect(); + let contrib: Vec = r["contrib"].as_array().ok_or("contrib")?.iter().map(|x| x.as_i64().unwrap_or(0)).collect(); + let start: Vec = (0..n).map(|s| stacks[s] + contrib[s]).collect(); + let mut used: Vec = hole.clone(); + used.extend(board.iter().copied()); + let filler = unused(&used, 2 * n + 5); + let mut it = filler.into_iter(); + let holes: Vec<[Card; 2]> = (0..n).map(|s| if s == me { [hole[0], hole[1]] } else { [it.next().unwrap(), it.next().unwrap()] }).collect(); + let mut runout: Vec = board.clone(); + while runout.len() < 5 { + runout.push(it.next().unwrap()); + } + let runout: [Card; 5] = [runout[0], runout[1], runout[2], runout[3], runout[4]]; + let hist = r["history"].as_array().ok_or("history")?; + let h = build_hand(n, sb, bb, &start, &holes, runout, hist)?; + // The replay must land exactly on the harness state. + let mut bad = h.actor() != Some(me) || h.board != board || h.pot() != r["pot"].as_i64().unwrap_or(-1); + for s in 0..n { + bad |= h.seats[s].stack != stacks[s] || h.seats[s].invested != contrib[s]; + } + let who = who_of(r, n); + let names = names_for(me, &who, n); + Ok((Situation::from_hand(&h, me, &names), bad)) +} + +fn action_json(id: u64, a: Action, sit: &Situation, st: &mut Stats) -> Value { + match a { + Action::Fold => { + if sit.can_check { + st.fold_when_free += 1; + } + json!({"id": id, "action": "fold"}) + } + Action::Check => json!({"id": id, "action": "check"}), + Action::Call => json!({"id": id, "action": "call"}), + Action::RaiseTo(t) => { + if sit.max_raise_to.is_none() { + st.raise_unavailable += 1; + } + json!({"id": id, "action": "raise", "to": t}) + } + Action::AllIn => { + if sit.max_raise_to.is_none() { + st.raise_unavailable += 1; + } + json!({"id": id, "action": "allin"}) + } + } +} + +impl Bot { + fn decide(&mut self, r: &Value) -> Value { + let id = r["id"].as_u64().unwrap_or(0); + let t0 = Instant::now(); + let (sit, bad) = match situation_from_request(r) { + Ok(x) => x, + Err(e) => { + self.stats.replay_err += 1; + eprintln!("replay error: {e}"); + return json!({"id": id, "error": format!("replay: {e}")}); + } + }; + if bad { + self.stats.replay_mismatch += 1; + } + let seed = id.wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ (std::process::id() as u64); + let res = catch_unwind(AssertUnwindSafe(|| { + let mut rng = SmallRng::seed_from_u64(seed); + decide_with(&sit, &self.models, &self.params, None, &mut rng) + })); + let d = match res { + Ok(d) => d, + Err(_) => { + self.stats.panics += 1; + return json!({"id": id, "error": "panic"}); + } + }; + let ms = t0.elapsed().as_secs_f64() * 1000.0; + self.stats.decisions += 1; + self.stats.ms_total += ms; + if self.stats.ms.len() < 200_000 { + self.stats.ms.push(ms as f32); + } + let kind = match d.action { + Action::Fold => "fold", + Action::Check => "check", + Action::Call => "call", + Action::RaiseTo(_) => "raise", + Action::AllIn => "allin", + }; + *self.stats.acts.entry(format!("{}:{}", sit.street.name(), kind)).or_default() += 1; + if sit.street == sv10_core::engine::Street::Preflop && !sit.history.iter().any(|h| h.seat == sit.hero_seat) { + self.stats.me_pre_hands += 1; + if matches!(d.action, Action::Call | Action::RaiseTo(_) | Action::AllIn) && !sit.can_check { + self.stats.me_pre_vpip += 1; + } + if matches!(d.action, Action::RaiseTo(_) | Action::AllIn) { + self.stats.me_pre_pfr += 1; + } + } + action_json(id, d.action, &sit, &mut self.stats) + } + + fn observe(&mut self, r: &Value) -> Result<(), String> { + let n = r["players"].as_u64().ok_or("players")? as usize; + let (sb, bb) = (r["sb"].as_i64().ok_or("sb")?, r["bb"].as_i64().ok_or("bb")?); + let start: Vec = r["stacks"].as_array().ok_or("stacks")?.iter().map(|x| x.as_i64().unwrap_or(0)).collect(); + let hv = r["holes"].as_array().ok_or("holes")?; + let mut holes = Vec::new(); + for h in hv { + let c = cards(h)?; + holes.push([c[0], c[1]]); + } + let board = cards(&r["board"])?; + // full runout is only needed to deal streets the history reaches; pad with unused cards + let mut used: Vec = holes.iter().flatten().copied().collect(); + used.extend(board.iter().copied()); + let mut runout: Vec = board.clone(); + let mut pad = unused(&used, 5).into_iter(); + while runout.len() < 5 { + runout.push(pad.next().unwrap()); + } + let runout: [Card; 5] = [runout[0], runout[1], runout[2], runout[3], runout[4]]; + let hist = r["history"].as_array().ok_or("history")?; + let h = build_hand(n, sb, bb, &start, &holes, runout, hist)?; + let who = who_of(r, n); + let names: Vec = (0..n).map(|s| if who.len() == n { format!("e{}s{}", who[s], s) } else { format!("s{s}") }).collect(); + let showdown = r["showdown"].as_bool().unwrap_or(false); + let summary = HandSummary { + players: names.iter().cloned().enumerate().collect(), + button: h.button, + bb, + history: h.history.clone(), + board: if showdown { board.clone() } else { h.board.clone() }, + stacks: h.seats.iter().enumerate().map(|(i, s)| (i, s.start_stack)).collect(), + shown: if showdown { h.seats.iter().enumerate().filter(|(_, s)| !s.folded).map(|(i, s)| (i, s.hole)).collect() } else { vec![] }, + }; + // per-entrant VPIP / PFR (diagnostics only) + for s in 0..n { + let e = self.stats.ents.entry(if who.len() == n { who[s] } else { 99 }).or_default(); + e.hands += 1; + let pre = h.history.iter().filter(|a| a.seat == s && a.street == sv10_core::engine::Street::Preflop); + let (mut vp, mut pf) = (false, false); + for a in pre { + if matches!(a.kind, ActionKind::Call | ActionKind::Raise | ActionKind::AllIn) { + vp = true; + } + if aggressive(a) { + pf = true; + } + } + e.vpip += vp as u64; + e.pfr += pf as u64; + } + if self.learn { + self.models.observe(&summary, None); + } + self.stats.observed += 1; + Ok(()) + } + + fn dump(&self) { + let Some(p) = &self.stats_path else { return }; + let s = &self.stats; + let mut ms = s.ms.clone(); + ms.sort_by(|a, b| a.total_cmp(b)); + let q = |f: f64| if ms.is_empty() { 0.0 } else { ms[((ms.len() - 1) as f64 * f) as usize] }; + let ents: Value = s + .ents + .iter() + .map(|(k, e)| (k.to_string(), json!({"hands": e.hands, "vpip": e.vpip as f64 / e.hands.max(1) as f64, "pfr": e.pfr as f64 / e.hands.max(1) as f64}))) + .collect::>() + .into(); + let v = json!({ + "pid": std::process::id(), "decisions": s.decisions, "ms_mean": s.ms_total / s.decisions.max(1) as f64, + "ms_p50": q(0.5), "ms_p95": q(0.95), "ms_p99": q(0.99), "ms_max": q(1.0), + "replay_mismatch": s.replay_mismatch, "replay_err": s.replay_err, "panics": s.panics, + "fold_when_free": s.fold_when_free, "raise_unavailable": s.raise_unavailable, + "observed_hands": s.observed, "observe_err": s.observe_err, + "acts": s.acts, "entrants": ents, + "me_preflop": {"hands": s.me_pre_hands, "vpip": s.me_pre_vpip as f64 / s.me_pre_hands.max(1) as f64, "pfr": s.me_pre_pfr as f64 / s.me_pre_hands.max(1) as f64}, + "learn": self.learn, + }); + let _ = std::fs::write(p, v.to_string()); + } +} + +fn new_bot() -> Bot { + let dir = std::env::var("SVAN_STATS_DIR").ok(); + Bot { + models: ModelStore::default(), + params: Params::default(), + learn: std::env::var("SVAN_LEARN").map(|v| v != "0").unwrap_or(true), + stats: Stats::default(), + stats_path: dir.map(|d| format!("{d}/w{}.json", std::process::id())), + } +} + +fn main() { + if std::env::args().nth(1).as_deref() == Some("selftest") { + selftest(); + return; + } + // One decision at a time per process; the harness runs many processes. + let _ = rayon::ThreadPoolBuilder::new().num_threads(1).build_global(); + let mut bot = new_bot(); + let stdin = std::io::stdin(); + let mut out = std::io::stdout().lock(); + let mut last_dump = Instant::now(); + for line in stdin.lock().lines() { + let Ok(line) = line else { break }; + if line.trim().is_empty() { + continue; + } + let Ok(r) = serde_json::from_str::(&line) else { + eprintln!("bad json line"); + continue; + }; + if r.get("observe").is_some() { + if let Err(e) = bot.observe(&r) { + bot.stats.observe_err += 1; + eprintln!("observe error: {e}"); + } + continue; + } + if last_dump.elapsed().as_secs_f64() > 3.0 { + bot.dump(); + last_dump = Instant::now(); + } + let reply = bot.decide(&r); + if writeln!(out, "{reply}").is_err() || out.flush().is_err() { + break; + } + } + bot.dump(); +} + +// --------------------------------------------------------------------------------------------------------- +// Conversion tests on hand-written spots. Request JSON is exactly what pluribus ext.rs `request_json` emits. + +fn req(v: Value) -> Value { + v +} + +fn run_spot(name: &str, r: Value) -> (Situation, Value) { + let (sit, bad) = situation_from_request(&r).unwrap_or_else(|e| panic!("{name}: {e}")); + assert!(!bad, "{name}: replay mismatch"); + let mut b = new_bot(); + let reply = b.decide(&r); + println!("{name}: pot={} call={} can_check={} min_raise={:?} max_raise={:?} street={:?} -> {reply}", sit.pot, sit.call_amount, sit.can_check, sit.min_raise_to, sit.max_raise_to, sit.street); + (sit, reply) +} + +fn selftest() { + let _ = rayon::ThreadPoolBuilder::new().num_threads(2).build_global(); + // 1. preflop open: UTG (seat 2) with AA, nothing yet. stacks after blinds. + let (s, r) = run_spot( + "open", + req(json!({"id":1,"seat":2,"players":6,"hole":["As","Ah"],"board":[],"street":0,"pot":150,"sb":50,"bb":100, + "stacks":[9950,9900,10000,10000,10000,10000],"street_bets":[50,100,0,0,0,0],"contrib":[50,100,0,0,0,0], + "folded":[false,false,false,false,false,false],"allin":[false,false,false,false,false,false],"cur_bet":100,"call_amount":100, + "legal":{"fold":true,"check":false,"raise":true,"min_raise_to":200,"max_raise_to":10000},"history":[]})), + ); + assert_eq!(s.hero_seat, 2); + assert_eq!(s.call_amount, 100); + assert_eq!(s.min_raise_to, Some(200)); + assert_eq!(s.max_raise_to, Some(10000)); + assert_eq!(r["action"], "raise", "AA UTG must raise: {r}"); + assert!(r["to"].as_i64().unwrap() >= 200 && r["to"].as_i64().unwrap() <= 10000); + + // 2. facing a 3-bet: BTN (seat 5) opened to 250, SB (seat 0) 3-bets to 900; we are BTN with KK... actor is seat 5 again? Order: 2 f,3 f,4 f,5 raise 250, 0 raise 900, 1 fold, 5 to act. + let hist = json!([ + {"seat":2,"street":0,"kind":"fold","to":0},{"seat":3,"street":0,"kind":"fold","to":0},{"seat":4,"street":0,"kind":"fold","to":0}, + {"seat":5,"street":0,"kind":"raise","to":250},{"seat":0,"street":0,"kind":"raise","to":900},{"seat":1,"street":0,"kind":"fold","to":0}]); + let (s, r) = run_spot( + "facing-3bet", + req(json!({"id":2,"seat":5,"players":6,"hole":["Ks","Kh"],"board":[],"street":0,"pot":1250,"sb":50,"bb":100, + "stacks":[9100,9900,10000,10000,10000,9750],"street_bets":[900,0,0,0,0,250],"contrib":[900,100,0,0,0,250], + "folded":[false,true,true,true,true,false],"allin":[false,false,false,false,false,false],"cur_bet":900,"call_amount":650, + "legal":{"fold":true,"check":false,"raise":true,"min_raise_to":1550,"max_raise_to":10000},"history":hist})), + ); + assert_eq!(s.call_amount, 650); + assert_eq!(s.min_raise_to, Some(1550)); + assert_ne!(r["action"], "fold", "KK vs 3bet must not fold: {r}"); + + // 3. flop c-bet: BTN raised 250, BB (seat 1) called; flop A72r, BB checks -> we (BTN) act with AK. + let hist = json!([ + {"seat":2,"street":0,"kind":"fold","to":0},{"seat":3,"street":0,"kind":"fold","to":0},{"seat":4,"street":0,"kind":"fold","to":0}, + {"seat":5,"street":0,"kind":"raise","to":250},{"seat":0,"street":0,"kind":"fold","to":0},{"seat":1,"street":0,"kind":"call","to":0}, + {"seat":1,"street":1,"kind":"check","to":0}]); + let (s, r) = run_spot( + "flop-cbet", + req(json!({"id":3,"seat":5,"players":6,"hole":["Ac","Kd"],"board":["As","7h","2c"],"street":1,"pot":550,"sb":50,"bb":100, + "stacks":[9950,9750,10000,10000,10000,9750],"street_bets":[0,0,0,0,0,0],"contrib":[50,250,0,0,0,250], + "folded":[true,false,true,true,true,false],"allin":[false,false,false,false,false,false],"cur_bet":0,"call_amount":0, + "legal":{"fold":false,"check":true,"raise":true,"min_raise_to":100,"max_raise_to":9750},"history":hist})), + ); + assert!(s.can_check); + assert_eq!(s.pot, 550); + assert_eq!(s.board.len(), 3); + assert!(matches!(r["action"].as_str(), Some("raise") | Some("check")), "{r}"); + + // 4. all-in facing: river, BB shoves 2000 into 1000 pot, hero (BTN) has the nuts. + let hist = json!([ + {"seat":2,"street":0,"kind":"fold","to":0},{"seat":3,"street":0,"kind":"fold","to":0},{"seat":4,"street":0,"kind":"fold","to":0}, + {"seat":5,"street":0,"kind":"raise","to":250},{"seat":0,"street":0,"kind":"fold","to":0},{"seat":1,"street":0,"kind":"call","to":0}, + {"seat":1,"street":1,"kind":"check","to":0},{"seat":5,"street":1,"kind":"raise","to":200},{"seat":1,"street":1,"kind":"call","to":0}, + {"seat":1,"street":2,"kind":"check","to":0},{"seat":5,"street":2,"kind":"check","to":0}, + {"seat":1,"street":3,"kind":"raise","to":9550}]); + let (s, r) = run_spot( + "river-allin", + req(json!({"id":4,"seat":5,"players":6,"hole":["Ad","As"],"board":["Ah","Ac","2c","7d","9s"],"street":3,"pot":10500,"sb":50,"bb":100, + "stacks":[9950,0,10000,10000,10000,9550],"street_bets":[0,9550,0,0,0,0],"contrib":[50,10000,0,0,0,450], + "folded":[true,false,true,true,true,false],"allin":[false,true,false,false,false,false],"cur_bet":9550,"call_amount":9550, + "legal":{"fold":true,"check":false,"raise":false,"min_raise_to":0,"max_raise_to":0},"history":hist})), + ); + let _ = s; + assert_eq!(r["action"], "call", "quad aces vs shove must call: {r}"); + + // 5. observe a finished hand (fold-out) and replay. + let mut b = new_bot(); + let obs = json!({"observe":1,"players":6,"stacks":[10000,10000,10000,10000,10000,10000],"sb":50,"bb":100,"button":5, + "holes":[["2c","3d"],["4c","5d"],["As","Ah"],["7c","8d"],["9c","Td"],["Jc","Qd"]],"board":[],"showdown":false, + "history":[{"seat":2,"street":0,"kind":"raise","to":250},{"seat":3,"street":0,"kind":"fold","to":0},{"seat":4,"street":0,"kind":"fold","to":0}, + {"seat":5,"street":0,"kind":"fold","to":0},{"seat":0,"street":0,"kind":"fold","to":0},{"seat":1,"street":0,"kind":"fold","to":0}], + "who":[1,1,0,1,1,1]}); + b.observe(&obs).unwrap(); + assert_eq!(b.stats.observed, 1); + assert!(b.models.players.contains_key("e0s2")); + println!("selftest ok"); +} diff --git a/arena/adapters/svan/run.sh b/arena/adapters/svan/run.sh new file mode 100755 index 00000000..11a0b738 --- /dev/null +++ b/arena/adapters/svan/run.sh @@ -0,0 +1,14 @@ +#!/bin/bash +# usage: run.sh TAG HERO FIELD DEALS SEED [extra vsbp args...] (runs from ~/pbench; logs in logs/svan/TAG.*) +TAG=$1; HERO=$2; FIELD=$3; DEALS=$4; SEED=$5; shift 5 +cd ~/pbench || exit 1 +mkdir -p logs/svan/stats-$TAG +export SVAN_STATS_DIR=$PWD/logs/svan/stats-$TAG RAYON_NUM_THREADS=${THREADS:-64} +SV="ext:svan+obs=[\"/home/ubuntu/svan/target/release/extbridge\"]" +sub() { case "$1" in svan) echo "$SV";; *) echo "$1";; esac; } +H=$(sub "$HERO"); F=$(sub "$FIELD") +echo "CMD hero=$H field=$F deals=$DEALS seed=$SEED $@" > logs/svan/$TAG.log +START=$(date +%s) +./target/release/examples/vsbp --compact data/C477/compact.plcp --sizing medium --buckets data/buckets-200 --hero "$H" --field "$F" --deals $DEALS --seed $SEED --ext-workers ${WORKERS:-48} --ext-timeout-ms 120000 "$@" >> logs/svan/$TAG.log 2>&1 +echo "WALL $(($(date +%s)-START)) s" >> logs/svan/$TAG.log +python3 ~/svan/tools/agg_stats.py logs/svan/stats-$TAG >> logs/svan/$TAG.log 2>&1 diff --git a/arena/bench/Cargo.toml b/arena/bench/Cargo.toml new file mode 100644 index 00000000..6dc380aa --- /dev/null +++ b/arena/bench/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "bench" +edition.workspace = true +version.workspace = true +description = "Evaluation harness: policies, gauntlet, duplicate matches, AIVAT, LBR, Slumbot adapter." + +[dependencies] +cards.workspace = true +rayon.workspace = true +serde.workspace = true +serde_json.workspace = true +nlhe = { path = "../../engine/nlhe" } +abstraction = { path = "../../sharingan-1/abstraction" } +blueprint = { path = "../../sharingan-1/blueprint" } +ureq = { version = "2.10", features = ["json"] } + +[[bin]] +name = "bench" +path = "src/main.rs" diff --git a/arena/bench/EXTERNAL_BOTS.md b/arena/bench/EXTERNAL_BOTS.md new file mode 100644 index 00000000..fff150f9 --- /dev/null +++ b/arena/bench/EXTERNAL_BOTS.md @@ -0,0 +1,185 @@ +# External-bot evaluation: how does blueprint B do against opponents we did not build? + +Researched and run 2026-10-13. Everything computational ran on the dev box (`scripts/dev.sh`); third-party +code lives in `~/extbots//` there (own directory per package, run with `python3 -I` / the venv's +`python -I`). Nothing was executed on the Mac. Local evaluation only; no third-party code is redistributed. +Tags: **[V]** = read on the primary page today, **[S]** = search snippet / secondary. + +## 1. Research: what strong NLHE bots can one actually run or play today? + +Headline: **there is no strong, openly runnable, pretrained 6-max NLHE agent anywhere** (learned or +rule-based). Pluribus, Libratus, DeepStack and ReBeL weights/poker code were never released; every +open-source "Pluribus" is a trainer you must run for days with your own abstraction. The only strong +opponent one can *play* is heads-up (Slumbot, and GTO Wizard's key-gated API). So external 6-max +assurance has to come from (a) a disciplined rule-based bot, (b) the one learned NLHE agent the public +toolkits can produce (RLCard), (c) our own diverse bot field, and (d) the HU Slumbot check for the +shared machinery (blueprint quality, translation, play code). + +| Name | Format | Type / strength evidence | License | Runnable today? | Integration effort | Decision | +|---|---|---|---|---|---|---| +| **Slumbot** (slumbot.com; [GTO Wizard Benchmark paper](https://arxiv.org/abs/2603.23660)) | HU, 200 bb, 50/100 | Fixed CFR strategy, ACPC 2018 HU winner; GTO Wizard AI beats it by 19.4 +/- 4.1 bb/100 [V] | public free service | **Yes, HTTP API live today** (`new_hand`/`act`, verified) | client already in `bench::slumbot` | **Played live (section 4)** | +| **GTO Wizard Benchmark API** ([paper](https://arxiv.org/abs/2603.23660)) | HU 200 bb | Strongest public HU bot (proprietary) | key by manual request | **No key** | adapt the Slumbot grammar | Not run (no key) | +| [slumbot2019 source](https://github.com/ericgjackson/slumbot2019) | HU (MCCFR also multiplayer, partial) | Solver toolkit; no strategy files or playable bot shipped [V] | MIT | Build yes, but you must solve it yourself (100M-iteration MCCFR examples + card abstraction) | days of compute | Skipped (would be our own trainer again) | +| [DecisionHoldem](https://arxiv.org/abs/2201.11580) / [OpenI repo](https://openi.pcl.ac.cn/chenhao/DecisionHoldem) | HU | Paper: beats Slumbot by >730 mbb/h (~73 bb/100, methodology unverified) [V abstract] | AGPL-3.0 | Source only; blueprint file is on a Baidu drive or 3-4 days on 48 cores to rebuild; some code only as binaries [V] | high; AGPL | Skipped (no obtainable weights; HU only) | +| [DeepHoldem](https://github.com/happypepper/DeepHoldem) | HU (DeepStack-style) | Author claims +42 bb/100 vs Slumbot 2017 over ~2.6k hands (noisy) [V] | none stated | Lua/Torch; only the preflop net ships, flop/turn/river nets must be generated (GPU, long) | very high | Skipped | +| [fedden/poker_ai](https://github.com/fedden/poker_ai) | "6-max", 20-card short deck | MCCFR blueprint trainer, no strength claim; archived 2024 [V] | GPL-3.0 | needs its own clustering + training | n/a | Skipped (not a strong bot) | +| [ozzi7/Poker-MCCFRM](https://github.com/ozzi7/Poker-MCCFRM) | any N players | Loose Pluribus re-implementation, no results; no releases; Windows/VS build; >128 GB RAM advised [V] | MIT | Build-it-yourself | n/a | Skipped | +| [PokerRL](https://github.com/EricSteinberger/PokerRL) (Deep CFR, SD-CFR) | small NL poker, N players in engine | Research framework, no pretrained agents [V] | MIT | Framework only | n/a | Skipped | +| [OpenSpiel](https://github.com/deepmind/open_spiel/blob/master/docs/games.md) `universal_poker` | ACPC-style NLHE expressible | Game engine; no pretrained NLHE agents [V] | Apache-2.0 | Engine only | n/a | Skipped | +| [ReBeL](https://github.com/facebookresearch/rebel) | Liar's Dice only in the repo | Poker agent never released [V] | Apache-2.0 | no poker | n/a | n/a | +| Pluribus / Libratus / DeepStack | 6-max / HU | Superhuman; code and weights withheld ([Pluribus](https://en.wikipedia.org/wiki/Pluribus_(poker_bot))) | - | **No** | - | n/a | +| [OpenHoldem](https://documentation.help/OpenHoldem/) (GPL-3.0) + profiles | any table via screen scraping | Framework with a default "Gecko" profile; strong commercial profiles ("Shanky" style) are paid, closed products | GPL-3.0 | Needs a poker client to scrape | high, and profiles unobtainable legally | Replaced by our own chart bot (below) | +| **RLCard** NLHE ([RLCard](https://pypi.org/project/rlcard)) DQN / NFSP / DMC | NLHE, N players, 5 abstract actions | Model zoo has **no** NLHE model (only Leduc, limit rule, UNO, Dou Dizhu, gin) [S]; but the toolkit trains a DQN you can run | MIT | **Yes** (pip, CPU) | JSON-lines bridge + train script (done) | **Integrated: `rlcard:` (learned)** | +| **chart-based rule bot** (published-chart shape: RFI charts + 3/4-bet bands + equity/pot-odds postflop) | 6-max, 100 bb | Not a downloaded product: a native Rust re-implementation of the standard "chart + pot odds" regime human regs and rule bots use | ours | Yes | done (`chart6`, `-loose`, `-tight`) | **Integrated: `chart6*` (deterministic rule)** | +| Open Poker (openpoker.ai) | 6-max, live bots | Other developers' bots; already running (separate live bot) | free | Yes | existing adapter | Not part of this study | + +Notes on strength evidence: Slumbot is a fixed non-adaptive strategy, hard to beat head-to-head yet +highly exploitable in the LBR sense; ~2018 ACPC level. "GTO Wizard AI beat it by ~19 bb/100" is the +yardstick for the HU play in section 4. Nothing external certifies 6-max strength; claims in this +document are therefore "beats every opponent we could obtain or build" and no more. + +## 2. What was integrated + +All opponents are bench `PolicyFactory` specs usable in `bench match|table|gauntlet|matrix`: + +| spec | what | where | +|---|---|---| +| `chart6`, `chart6-loose`, `chart6-tight` | Deterministic rule bots. Preflop: position RFI charts (UTG ~16 %, HJ ~21 %, CO ~27 %, BTN ~44 %, SB ~42 % raise-or-fold), 3-bet/call bands by hero x opener position, 4-bet/5-bet-jam bands. Postflop: Monte-Carlo equity vs a range proxy (top fraction of villain's hands by expected future strength; narrower vs bigger bets and raises), pot-odds calls, value bets/raises, c-bets, hash-seeded bluffs. `-loose` (x1.45) / `-tight` (x0.7) scale widths and aggression. Pure function of (history, hole): `exposes_probs` is true, so AIVAT also corrects *their* decisions. The charts are approximations written from memory of commonly published ranges, **not** solver output. | `arena/bench/src/chart.rs` | +| `rlcard:` | Learned agent: stock RLCard DQN (256x256 MLP, 5 abstract actions: fold, check/call, 1/2 pot, pot, all-in) self-play-trained on 6-max 100 bb NLHE (RLCard ships no NLHE weights). Runs in a Python worker pool behind the bridge. | `arena/adapters/rlcard_train.py`, `rlcard_bot_server.py` | +| `ext:=` | Generic bridge for any other bot: JSON lines over stdin/stdout, stateless protocol (full public state + history in every request), worker pool shared by all rayon threads, per-request timeout, first-request startup grace, kill+respawn of hung/dead workers, legalization of every answer (raise clamped to legal range, impossible raise becomes call/check, fold of a free check becomes check, malformed/timeout becomes check-or-fold and is counted in the end-of-run `report`). | `arena/bench/src/ext.rs` (protocol documented at the top) | +| `bench table --hero SPEC --field a,b,c,d,e` | Mixed tables (or one field spec = 5 copies); every cyclic rotation of the seating on every deal (duplicate), CRN, AIVAT. | `arena/bench/src/main.rs` | +| `bench slumbot` | Live HU client with `--pace-ms` (one request in flight, spaced), retry/backoff, per-hand JSONL log, and an all-in-EV "luck adjusted" estimate (Slumbot is not a known strategy so true AIVAT is impossible; every hand that reached showdown all-in before the river is replaced by its exact EV). | `arena/bench/src/slumbot.rs` | +| `pluribus train --stack N` | New flag (default 10000 = 100 bb) so a 200 bb HU blueprint can be trained. | `sharingan-1/pluribus/src/main.rs` | + +Unit tests (`cargo test -p bench --lib -- chart:: ext:: slumbot::`, 10 pass): chart widths in the expected +bands and AA/72o ordering; chart6 legal, zero-sum and independent of the random stream; bridge request +contains the full public state; responses legalized (clamp, allin, check-vs-call, free-check fold, wrong id, +garbage, unknown action); a real Python subprocess plays full 6-handed hands with 0 fallbacks; a hung bot +(timeout) and a crashing bot (process exit) both fall back safely and are counted; all-in-EV maths +(AA v KK preflop ~ +12.8k chips). + +## 3. 6-max results: blueprint B-final vs the external field + +B = `data/eval/B-it20000000000-20261013T1354Z/compact.plcp` (2e10 iterations, snapshot-averaged, 2.38 B +infosets), `--sizing local`, buckets `data/buckets-200`, translation = default (deterministic +pseudo-harmonic, shadow state). Protocol: 100 bb, 50/100 blinds, **duplicate deals** (every cyclic +rotation of the seating on every deal, common random numbers), **AIVAT** (full mode; the rule bots and +built-ins expose their probabilities so their decisions are corrected too; RLCard is a sampling-free +black box, so only chance and B's own actions are corrected for it). All numbers: mbb/game for the entrant +(mean over the seats it occupies), AIVAT estimate with **95 % CI**. 100,000 deals = 600,000 hands per row +(20 s - 2 min on 16 threads). Raw (non-AIVAT) values and per-seat splits are in +`~/pluribus/data/extbots-results/*.txt` on the dev box. Seeds are fixed per row (see +`arena/adapters/run_rules.sh`, `run_rlcard.sh`). + +### 3a. Hero B vs 5 copies of one bot (B's number; the bot's number is -1/5 of it) + +| opponent | B mbb/game (AIVAT) | per-opponent-seat | +|---|---|---| +| chart6 (rule, standard charts) | **+134.4 +/- 17.5** | -26.9 +/- 3.5 | +| chart6-loose (rule, LAG-ish) | **+173.5 +/- 19.5** | -34.7 +/- 3.9 | +| chart6-tight (rule, nit-ish) | **+129.5 +/- 16.4** | -25.9 +/- 3.3 | +| rlcard DQN (learned) | **+587.0 +/- 40.9** | -117.4 +/- 8.2 | +| nit (built-in) | +138.3 +/- 15.0 | -27.7 +/- 3.0 | +| tag (built-in) | +366.4 +/- 24.6 | -73.3 +/- 4.9 | +| lag (built-in) | +888.9 +/- 37.8 | -177.8 +/- 7.6 | +| maniac (built-in) | +1498.8 +/- 44.4 | -299.8 +/- 8.9 | +| station (built-in) | +3511.7 +/- 67.4 | -702.3 +/- 13.5 | + +B is positive against every opponent, all CIs exclude 0 by 7 sigma or more, and every row reaches the +requested +/- 50 mbb/game (tightest +/- 15, widest +/- 67). B wins in every seat except the blinds, as +expected (e.g. vs chart6: SB -74, BB -265, UTG..BTN +187/+211/+282/+489 raw). + +### 3b. The inverse view: ONE external bot at a table of 5 B's (the paper's "1 human + 5 AI" setup) + +| lone opponent | its mbb/game (AIVAT) | +|---|---| +| chart6 | -111.9 +/- 17.0 | +| chart6-loose | -177.1 +/- 20.6 | +| chart6-tight | -98.9 +/- 14.9 | +| tag | -416.8 +/- 26.1 | +| lag | -1,308.3 +/- 48.3 | +| maniac | -2,397.5 +/- 81.5 | +| rlcard DQN | -1,778.8 +/- 48.3 | + +None of them can beat five B's; the best of them (chart6-tight) still loses ~100 mbb/game. (For reference +the exploiter trained against B with B's own bet menu lost -205 +/- 57; none of these opponents is an +adaptive best-response, so this is a lower bound on exploitability, not a measurement of it.) + +### 3c. Mixed tables (1 B + 5 *different* bots), 100,000 deals, all rotations + +| table | B | chart6 | chart6-loose | chart6-tight | tag | lag | rlcard | nit | maniac | station | +|---|---|---|---|---|---|---|---|---|---|---| +| T1: B + chart6, loose, tight, tag, lag | **+430.1 +/- 25.0** | +583.1 +/- 28.3 | +571.1 +/- 31.5 | +514.0 +/- 25.5 | +241.5 +/- 36.1 | -2339.8 +/- 55.1 | | | | | +| T2: B + chart6, loose, nit, maniac, station | **+1864.5 +/- 42.8** | +3362.8 +/- 57.7 | +3910.7 +/- 65.5 | | | | | +2779.9 +/- 50.9 | +4064.3 +/- 111.2 | -15982.2 +/- 120.4 | +| T3: B + chart6, loose, tight, rlcard, tag | **+446.0 +/- 24.9** | +780.8 +/- 29.3 | +741.5 +/- 32.6 | +618.0 +/- 25.9 | +386.3 +/- 38.9 | | -2972.5 +/- 57.8 | | | | + +Read these carefully: every table contains a donor (lag, station, rlcard) and the zero-sum identity makes +all the other seats positive. B is positive in all three, **but the chart rule bots earn more than B at +the same table** (e.g. T3: chart6 +781 vs B +446). This is not a head-to-head loss (3a/3b show B beats and +is not beaten by those bots); it says B is a fixed, non-adapting strategy that takes less from a leaking +opponent than a looser, more aggressive bot does (chart6 is 3-bet/c-bet heavy against calling stations). +So B is "unbeatable by these bots", not "the best exploiter at a mixed table". That is expected of an +equilibrium-style blueprint; exploiting weak tables is the job of the opponent-modelling layer. + +### 3d. Context: how good are the external bots themselves? + +| matchup (hero vs 5x) | hero mbb/game (AIVAT) | deals | +|---|---|---| +| chart6 vs tag / lag / nit / maniac / station | +603 / +1,723 / +169 / +2,137 / +15,796 | 3,000 | +| chart6 vs rlcard | +1,984 +/- 199 | 5,000 | +| rlcard vs random / station | +9,696 +/- 696 / +14,638 +/- 1,045 | 3,000 | +| rlcard vs tag / lag | -2,838 +/- 398 / +240 +/- 422 | 3,000 | + +So chart6 is a genuinely competent rule bot (beats every built-in and the learned agent by a wide margin, +beats B's own gauntlet numbers on weak fields). The RLCard DQN (~380k self-play hands, 90 min, 4 threads; it +only sees cards plus two chip counts, no betting history) is a weak learned agent: it crushes random and +stations but loses to a TAG. It is the best *learned* NLHE agent obtainable off the shelf, which says +more about the public landscape than about the agent. + +## 4. Heads-up vs Slumbot (public API, 200 bb, blinds 50/100) + +* **Blueprint:** `pluribus train --players 2 --stack 20000 --sizing local --iters 700000000 --mem-gb 60` + (new `--stack` flag; 32 threads, ~80 min on the loaded shared box, 6.26 M infosets, buckets-200) + then `pluribus compact` (76 MB). The run dir is `data/run-hu200`, the policy `data/hu200/compact.plcp`. + Blueprint only, no real-time search, Slumbot's off-tree bet sizes handled by the same translation as in + 6-max play. +* **Match:** 2,400 live hands (`bench slumbot --hands 2400 --pace-ms 400`; one request in flight at a time, + >= 0.4 s apart, ~1.5 s per hand, 60 min total, ~12k requests; the log of every hand is + `data/extbots-results/slumbot-hu200.jsonl` on the dev box). Slumbot's API reported no errors. +* **Result:** **+13.9 bb/100, 95 % CI +/- 68.7** raw; luck-adjusted (exact all-in EV for every hand that went + all-in before the river) **+14.1 +/- 65.5 bb/100**. By seat: BB -24.9 +/- 91.3, SB/button +52.8 +/- 102.5. + Hand standard deviation ~16 bb, so 2,400 hands cannot resolve anything under ~65 bb/100. + +Honest reading: the blueprint is **not losing** to Slumbot (point estimate positive, CI [-55, +83]) but +this match does not demonstrate that it *beats* it. Slumbot (ACPC 2018 champion level) is beaten by GTO +Wizard AI by 19.4 +/- 4.1 bb/100 (150k hands, AIVAT); to detect a ~15 bb/100 edge at 95 % one needs +~40-50k hands (~15-20 h at the polite pace used here), so we stopped at the requested 2,000+ rather than +hammer a free service. Caveats: our HU blueprint is small (only 6.3 M infosets, `local` menus, 700 M +iterations), and 6-max-tuned B itself was never trained heads-up. + +## 5. Reproduce + +``` +scripts/dev.sh run 'cargo build --release -p bench -p pluribus' # DEV_TARGET=extbots for a private target dir +DEV_TARGET=extbots scripts/dev.sh run 'cargo test --release -p bench --lib -- chart:: ext:: slumbot::' +# RLCard (dev box): ~/extbots/rlcard-env/venv (rlcard 1.2.0, torch cpu), then +# ~/extbots/rlcard-env/venv/bin/python -I arena/adapters/rlcard_train.py ~/extbots/rlcard-models/dqn6 90 4 +arena/adapters/run_rules.sh # B vs chart6* / built-ins, mixed rule tables +arena/adapters/run_rlcard.sh # B / chart6 / built-ins vs the RLCard DQN (DEALS=100000 for the final rows) +bench table --hero compact:B.plcp --sizing local --bucketer tables:data/buckets-200 --field chart6,chart6-loose,chart6-tight,rlcard:MODEL,tag +bench slumbot --policy compact:data/hu200/compact.plcp --sizing local --bucketer tables:data/buckets-200 --hands 2400 --pace-ms 400 --log data/extbots-results/slumbot-hu200.jsonl +``` + +## 6. Limits, and what would make the assurance stronger + +* "Strongest bots" turned out to be mostly unobtainable: no public strong 6-max agent exists. Our external + field is (1) a rule bot we wrote to the shape of published charts (not solver output; it is competent but + exploitable and tuned by feel, with three style settings), (2) a weak off-the-shelf learned agent, (3) the + built-in archetypes. Beating these says B has no gross leaks against sane human-style and bot-style + play; it does not certify equilibrium quality. +* Stronger checks that need access we do not have: the GTO Wizard Benchmark key (HU, would give an + AIVAT-corrected bb/100 against a bot 19 bb/100 better than Slumbot), and long Open Poker sessions + (live 6-max bots of unknown strength). +* Worth doing next with the bridge already in place: wrap a locally trained slumbot2019/DecisionHoldem + blueprint (HU) as an `ext:` bot, and replace the DQN by a longer or architecture-improved RLCard run (DMC) + with betting history in the observation. diff --git a/arena/bench/RESULTS.md b/arena/bench/RESULTS.md new file mode 100644 index 00000000..6c1c0742 --- /dev/null +++ b/arena/bench/RESULTS.md @@ -0,0 +1,70 @@ +# bench: baseline results + +Generated with `bench matrix --deals 20000 --seed 7` (release, M4 Max; matrix ~2.5 min) and +`bench lbr`. Built-ins are untuned heuristics (see `src/builtin.rs`); numbers are for +orientation and regression, not strength claims. Each cell is the row policy against copies +of the column policy, mbb/game (milli big blinds per hand) with the AIVAT estimate and 95% CI. +Duplicate format: the hero plays every seat on the same deals (20,000 deals x 6 seatings in +6-max, x 2 in HU). AIVAT = full (chance nodes + all known-policy decisions, equity baseline). + +### 6-max: row hero vs 5 copies of column (mbb/game, AIVAT, 95% CI) + +| hero \ field | random | station | nit | tag | lag | maniac | +|---|---|---|---|---|---|---| +| random | - | -49.3 ± 102.9 | -6383.9 ± 189.7 | -12954.2 ± 251.4 | -14342.3 ± 242.9 | -8831.7 ± 155.9 | +| station | +4040.9 ± 327.6 | - | -4442.0 ± 138.4 | -14752.0 ± 263.2 | -17857.8 ± 315.3 | -6473.5 ± 190.9 | +| nit | +6476.1 ± 212.1 | +7614.6 ± 237.3 | - | +603.9 ± 53.5 | +2229.8 ± 104.9 | +3967.3 ± 117.4 | +| tag | +9977.7 ± 247.5 | +17069.4 ± 343.8 | -624.3 ± 55.8 | - | +2099.0 ± 117.1 | +4672.0 ± 127.1 | +| lag | +12919.2 ± 277.2 | +21459.3 ± 396.5 | -2479.7 ± 121.0 | -2766.0 ± 139.0 | - | +3520.0 ± 112.8 | +| maniac | +10943.9 ± 254.7 | +13490.4 ± 371.0 | -5091.6 ± 213.9 | -6455.9 ± 246.4 | -4570.2 ± 190.3 | - | + +mean per-hand variance ratio raw/AIVAT: 4.5x (min 1.6, max 14.6) + +### 2-max: row hero vs 1 copies of column (mbb/game, AIVAT, 95% CI) + +| hero \ field | random | station | nit | tag | lag | maniac | +|---|---|---|---|---|---|---| +| random | - | -43.7 ± 23.8 | -1399.2 ± 97.3 | -3699.3 ± 151.4 | -6102.7 ± 193.1 | -7966.7 ± 243.2 | +| station | +43.7 ± 23.8 | - | -544.1 ± 30.1 | -1906.8 ± 57.2 | -3726.6 ± 91.7 | -8800.3 ± 218.4 | +| nit | +1399.2 ± 97.3 | +544.1 ± 30.1 | - | +91.9 ± 44.9 | +421.4 ± 82.2 | +822.0 ± 112.8 | +| tag | +3699.3 ± 151.4 | +1906.8 ± 57.2 | -91.9 ± 44.9 | - | +809.3 ± 111.2 | +1652.9 ± 153.1 | +| lag | +6102.7 ± 193.1 | +3726.6 ± 91.7 | -421.4 ± 82.2 | -809.3 ± 111.2 | - | +1653.8 ± 194.2 | +| maniac | +7966.7 ± 243.2 | +8800.3 ± 218.4 | -822.0 ± 112.8 | -1652.9 ± 153.1 | -1653.8 ± 194.2 | - | + +mean per-hand variance ratio raw/AIVAT: 2.4x (min 1.6, max 5.4) + +AIVAT raw/AIVAT variance ratios are per single hand (entrant payoff in one seating); cell-level +range shown above. The ratios are modest compared with the paper's ~9x because the baseline is +cheap check-down equity (no betting model) and the built-ins bet a lot; a better `ValueEstimator` +(e.g. policy rollouts or blueprint values) plugs in without changes elsewhere. +Unbiasedness is tested (`cargo test --release -p bench`): raw and AIVAT means agree within +error for HU and 6-max pairs; self-match is 0 within CI. + +## LBR (lower bound on exploitability, mbb/game won by the LBR player) + +Heads-up, `bench lbr --players 2 --deals 1500 --samples 300`, LBR in both seats, same deals: + +| policy | LBR mbb/game (95% CI) | +|---|---| +| random | +9711 ± 1645 | +| station | +15477 ± 1221 | +| maniac | +2622 ± 1415 | +| lag | +1114 ± 1093 | +| nit | +668 ± 261 | +| tag | +578 ± 559 | +| toy blueprint (HU, 60k iters, coarse buckets, tiny sizing) | +2452 ± 1022 | + +6-max profile LBR (one LBR seat vs 5 copies; NOT an equilibrium-gap bound), +`--players 6 --deals 300 --samples 150`: random +13531 ± 5092, station +20216 ± 4815, +maniac +3380 ± 3168, tag +1906 ± 1823, nit +1664 ± 820, lag +201 ± 2715. + +LBR here is a weak exploiter (menu fold/call/0.5 pot/1 pot/all-in, check-down continuation +model, re-raises treated as calls), so every figure understates true exploitability. Tight +heuristics look "safe" because LBR cannot exploit their folding well, not because they are +close to equilibrium. + +## Notes / limitations + +- Blueprint checkpoints (`blueprint::io`) store only the `Store`; the bucketer and sizing are + chosen by name at load (`--bucketer coarse|tables:`, `--sizing tiny|local|paper`). +- `bench slumbot` has not been run live. diff --git a/arena/bench/TRANSLATION.md b/arena/bench/TRANSLATION.md new file mode 100644 index 00000000..cbc17eac --- /dev/null +++ b/arena/bench/TRANSLATION.md @@ -0,0 +1,159 @@ +# Off-menu action translation: historical study and current tracking + +The B-model measurements below describe the earlier shadow-game fix. They predate the +November 2026 tiny-bet exploit and `keep_sync` fix. Current defaults are +`BelowMenu::Smallest`, deterministic translation, `keep_sync = true`, and a strength-based +fallback. See [the current experiments](../../docs/RESULTS.md#action-translation-leak-and-fix-nov-2026), +including the model-input audit and independently reproduced frozen attack. Historical +`Check` results below do not justify restoring the old default. + +Question: why does a trained exploiter whose menu is richer than the blueprint's ("paper" learner vs +blueprint B, sizing "local") win +26,224 +- 501 mbb/game, while the same-menu exploiter loses +-205 +- 57? Genuine translation exploit, bug in the target's off-menu handling, or evaluation artefact? + +## Historical B-study result + +**Mostly a bug in how the target policy handled off-menu actions (BlueprintPolicy/CompactPolicy +history tracking), not the pseudo-harmonic mapping itself. Not an evaluation artefact.** After the +fix the same exploiter wins +700 +- 149 (final B, 12M iterations), a 37x reduction. The remainder is +a residual attack against that historical configuration; its mechanism does not establish +the cause of every later attack. + +* Not an artefact: raw (non-AIVAT) and AIVAT estimates agree (26,156 vs 26,224; 25,614 vs 25,625 + in the re-runs), the exploiter and target are the same objects in training and evaluation, and + payoffs are zero-sum chip counts from the game engine. +* Root cause (bug): after the target observes an off-menu raise it appended the *translated index* + to its abstract history, but kept computing its action list from the *real* state. The blueprint + node reached by the translated history has a different action list than the real state (different + raise depth menu, different clamping, a raise turned into a "check", an overbet turned into + "all-in"), so + 1. the infoset lookup usually failed (`n_actions` mismatch) -> **fallback "check/call"**: after + an off-menu action the target missed **92%** of its decisions and played fold 4.9% / call 2.8% + / raise 0.6% of probability mass, i.e. it **never folds and never raises** - a calling + station for the rest of the hand; + 2. when `n_actions` happened to match, index `i` of the *check node* was applied to the real + `[Fold, Call, ...]` list (probability of "check" became probability of **fold**); + 3. an overbet translated to the abstract all-in always landed on a node with `[Fold, Call]`, + 100% miss, so every overbet >= 3x pot was called with everything. + A learner with 14 preflop open sizes lives off-menu constantly (every size not in B's 4-size + menu), so it found "value bet / shove into a station" in all positions: +51 bb/hand from UTG. +* Probes confirm (bench `probe:` bots, `research/experiments/probes.sh`, B-final, AIVAT, 8000 deals x 6 seats, + probe's mbb/game; the always-call station baseline is -6704): legacy target `bet=0.1` -956, + `bet=0.2` -1828, `bet=1.5` -16171... i.e. the target is wildly more or less exploitable by *size* + alone, with miss rates 20-100% after the bet. After the fix `bet=0.1` -7317, `bet=0.2` -7582, + `bet=3` -7438, `bet=5` -8560: all at or below the station baseline. + +## Current tracking (updated 2026-11-04) + +`nlhe::abstraction`: +* `Shadow`: the policy tracks a **shadow game** in which every off-menu raise is replaced by its + translated abstract action. Action lists, history key and node identity come from the shadow, so + the blueprint is always queried at a node of its own tree. The chosen abstract action is mapped + back to a real action by pot fraction (`real_action`; abstract all-in = real all-in; clamped to + the legal range). The policy's own actions are mapped back to the list entry they came from (no + random re-translation). If the shadow cannot follow the real game (different actor/street, shadow + terminal, unrepresentable fold), it is flagged desynced. With the current default + `keep_sync`, the policy uses `bench::bp::fallback_action`, based on hand strength against + random opponent hands and the actual call price. This fallback is heuristic, not range-aware. +* `keep_sync` checks each proposed translation one action ahead. It preserves terminal status, + actor/street and every seat's folded/all-in status. If necessary, it chooses the nearest + abstract action that stays in step. If none exists, such as a non-all-in raise past the tree's + cap, it hands off explicitly with reason 4. It does not guarantee correct pot prices or ranges. +* `BelowMenu::{Check, Smallest}`: bets below the smallest abstract raise. `Check` = pseudo-harmonic + between "check/call" (size 0) and the smallest raise. That historical rule could lose the real + game after a tiny bet. `Smallest` = always the smallest raise, and **is the current default**. + The old B-table comparison was made before the current synchronization and fallback fixes. +* `allin_snap` (default 0.5): a non-all-in raise maps to the abstract all-in only if it leaves + at most 0.5 x pot behind; otherwise to the largest smaller size. (Mapping a 3x-pot bet to a + 10x-pot "all-in" made the shadow all-in while the real players still had chips.) +* `Translation::Random` (paper: randomised pseudo-harmonic when not searching): between two raise + sizes only; "is it a bet at all" stays deterministic because a randomly ignored bet desynchronises + the shadow (first attempt, random everywhere: +1,479 with 32% desync). Not AIVAT-exposable. +* `bench::bp::BlueprintPolicy` / `CompactPolicy` use `Shadow` (shared `bp::Source` code); exploit + `abr.rs` tracks the target with the same `Shadow` so training and evaluation see the same + target. `TrackOpts::PRE_SYNC_FIX` / `--pre-sync-fix` reproduce the tiny-bet-vulnerable + configuration (shadow enabled, below-menu Check, no keep-sync). `TrackOpts::LEGACY` / + `--legacy` reproduce the still earlier real-state-list tracking. Other diagnostic selectors: + `--translation det|random`, `--below check|smallest`, `--allin-snap X`. +* Diagnostics: `PolicyFactory::report()`; bench prints per-policy decisions split by + on-menu / after-off-menu: miss rate, desync rate (+reasons), fold/call/raise mass. +* Probes: `bench::probe` (`probe:pre=..,bet=..,raise=..,street=..`), `research/experiments/probes.sh`. +* Tests: `nlhe::abstraction::shadow_tests`, `bench/tests/harness.rs::off_menu_bets_keep_the_policy_in_its_tree`. + +## Historical numbers (before the November keep-sync fix) + +Exploiter = trained best response, "paper" learner menu, 1 learner seat vs 5 frozen target copies, all +seats, 20,000 eval deals, AIVAT (mbb/game, positive = target exploited). + +Final B (2e10 it, sizing local), 12M exploiter iterations: + +| target tracking | exploiter vs B | +|---|---| +| legacy (before) | **+26,007 +- 500** (seats 12708/7116/51413/38515/29004/17285), target miss after off-menu 91.7% | +| fixed: Check, allin_snap 0.5, deterministic | **+700 +- 149** (seats 1080/68/324/756/727/1244), miss 5.0% (all desync) | +| fixed + random between sizes | +619 +- 134 (seats 881/127/258/500/699/1248); within noise of deterministic | +| (reference) same-menu "local" learner, old B 12M | -205 +- 57 | + +Ablation on the earlier B (4.5e9 it), 4M exploiter iterations (legacy +25,625): + +| variant | exploiter | +|---|---| +| shadow, Smallest, snap 0 | +2,053 +- 236 | +| shadow, Smallest, snap 0, random | +1,944 +- 239 | +| shadow, Smallest, snap 0.5 | +2,141 +- 235 | +| shadow, Check, snap 0 | +256 +- 135 | +| **shadow, Check, snap 0.5 (then default)** | **+281 +- 136** | +| shadow, Check, snap 2 | +460 +- 129 | +| shadow, Check, snap 0.5, random everywhere | +1,479 +- 175 | +| shadow, Check, snap 0.5, random between sizes only | +151 +- 125 | + +Against A (sizing paper, same-menu exploiter, 4M iterations; no off-menu actions exist so nothing +should change): legacy -452 +- 104, fixed -427 +- 104. (12M earlier: +470 +- 127.) + +Probes vs B-final (probe's mbb/game; station baseline -6704; legacy -> fixed (default)): +`pre=8` -6257 -> -6990; `bet=0.1` -956 -> -7317; `bet=0.2` -1828 -> -7582; `bet=0.3` -5612 -> -5884; +`bet=0.75` -7625 -> -5513; `bet=1.5` -16171 -> -7462; `bet=2` -17011 -> -7593; `bet=3` -15440 -> -7438; +`bet=5` -14412 -> -8560; `bet=0.5,raise=3` -9001 -> -7505; `bet=3` river -8202 -> -8499. +Full tables: `research/experiments/probes.sh` (legacy, default, `--below smallest`), logs on the box. +Remaining relative gain of a probe over the station is <= ~1 bb/hand and similar to the on-menu +control (`bet=1`: -5954). + +SearchPolicy (HU, tiny-menu 3M blueprint `data/search-bp/hu_tiny_3m.bin`, 2,000 search iterations, +3,000 deals, `sharingan-1/search/examples/probe.rs`; probe's mbb/game, lower = better for the agent): + +| probe | bp legacy | bp fixed | search | +|---|---|---|---| +| station | -2434 | -2434 | -146 | +| bet 0.1 pot | -1125 | -2846 | -9723 | +| bet 0.3 | -1422 | -3600 | -9400 | +| bet 3 | -354 | -4679 | -13011 | +| bet 3, river | -1843 | -5877 | -9608 | +| pre 8bb | -694 | -4737 | -4749 | + +Search (off-tree actions added to the subgame) beats every off-menu probe by far more than the +blueprint, even the fixed one; the old blueprint was the worst (+2 bb/hand over the station on +`bet=3`). Caveat: search is oddly weak vs the station here (-146), a property of that small test +setup, not of translation. + +## Current limitations and historical caveats + +* The current fixed C blueprint still admits a profitable frozen attack: the 1M policy has + reproduced exactly at +419.5 ± 95.4 mbb/game on an independently verified public model. + Stronger original-host figures remain subject to the input audit. Final-model confirmation + and attack-specific causes are tracked in [RESULTS](../../docs/RESULTS.md#action-translation-leak-and-fix-nov-2026). +* The historical B study found +700 from a 12M learner. Random translation between raises + gave +619 ± 134 versus +700 ± 149; that comparison did not establish an improvement. + Neither result measures the present default configuration. +* In the historical Check/no-keep-sync configuration, tiny bets could desynchronize the + shadow and trigger check/call. Current defaults avoid ignoring the tiny bet and use an + explicit hand-off with a strength fallback when synchronization is impossible. +* Off-menu pot sizes still differ between the real and shadow games. Whether sizes near + translation thresholds, overbets, or raise-cap hand-offs explain a particular attack must + be measured. A later price-mass correction was reverted after an adaptive regression. +* Search now uses `search::bp::Blueprint` with `Shadow`, including the same tracking options + and strength fallback. The earlier warning that search used legacy real-state histories + is obsolete. Adversarial testing of the full search/API path remains separate work. +* Historical off-menu LBR/head-to-head measurements made with old tracking do not describe + the fixed target. Use the command, model identity and tracking options recorded for each run. +* The scripted sizing probes are weak opponents. Their losses do not bound what a trained + or adaptive attacker can earn. No six-player bot is proved unexploitable by these tests. diff --git a/arena/bench/src/aivat.rs b/arena/bench/src/aivat.rs new file mode 100644 index 00000000..a870ef37 --- /dev/null +++ b/arena/bench/src/aivat.rs @@ -0,0 +1,375 @@ +//! AIVAT (Burch et al. 2018) in the multi-player form of the Pluribus supplement. +//! +//! For one hand, with realised payoffs `u` (per seat), the estimate for every seat is +//! +//! ```text +//! u + sum over chance nodes ( E_c[v(h.c)] - v(h.c*) ) +//! + sum over known-policy decisions ( sum_a sigma(a) v(h.a) - v(h.a*) ) +//! ``` +//! +//! where `v` is any [`ValueEstimator`] that only looks at what has been dealt/played so far +//! (never at undealt board cards). Each bracketed term has conditional mean zero (the sampled +//! card/action is drawn from exactly the distribution inside the sum), so the estimate is +//! unbiased for any `v`; a good `v` merely lowers the variance. Chance nodes are the hole-card +//! deal and each board reveal (including all-in run-outs); decision nodes are those of players +//! that expose their probabilities. Decisions of non-exposing players get no correction. +//! +//! [`EquityEstimator`] is the default baseline: every live player calls the outstanding bet and +//! the hand is checked down; the value is the exact expected (fractional-chop) payoff given +//! all hole cards, enumerating the remaining board postflop and sampling it preflop. Its +//! chance-node mean is exact by the tower property (E_c[v(h.c)] = v(h)). Fractional chop means +//! AIVAT's target differs from integer-chip payoffs only by odd-chip rounding (< 0.5 chip on +//! a tied odd pot, i.e. << 0.1 mbb). +//! +//! `Mode::CardsOnly` is the paper's simpler baseline: only the deal is corrected. + +use crate::policy::Dist; +use cards::{bit, evaluate, mask_of, Card, Rng, FULL_DECK}; +use nlhe::{Deal, State, MAX_PLAYERS}; +use std::collections::HashMap; + +pub struct Query<'a> { + pub state: &'a State, + pub holes: &'a [[Card; 2]; MAX_PLAYERS], + /// Board cards revealed at this node (never pass undealt cards). + pub board: &'a [Card], +} + +/// Per-deal scratch: independent RNG for sampling inside estimators and a result cache. +pub struct Scratch { + pub rng: Rng, + cache: HashMap<(u8, u8), [f64; MAX_PLAYERS]>, +} + +impl Scratch { + pub fn new(seed: u64) -> Self { + Scratch { + rng: Rng::new(seed), + cache: HashMap::new(), + } + } +} + +pub trait ValueEstimator: Send + Sync { + fn value(&self, q: &Query, sc: &mut Scratch) -> [f64; MAX_PLAYERS]; + + /// E over the next board cards (up to `next_len` visible) of `value`. Default: Monte Carlo + /// with fresh independent samples (unbiased). + fn chance_mean(&self, q: &Query, next_len: usize, sc: &mut Scratch) -> [f64; MAX_PLAYERS] { + const M: usize = 32; + let n = q.state.num_players(); + let dead = q.holes[..n] + .iter() + .fold(mask_of(q.board), |m, h| m | bit(h[0]) | bit(h[1])); + let mut acc = [0.0; MAX_PLAYERS]; + for _ in 0..M { + let mut b = q.board.to_vec(); + let mut d = dead; + while b.len() < next_len { + let c = sc.rng.draw(d); + d |= bit(c); + b.push(c); + } + let v = self.value( + &Query { + state: q.state, + holes: q.holes, + board: &b, + }, + sc, + ); + for i in 0..MAX_PLAYERS { + acc[i] += v[i] / M as f64; + } + } + acc + } + + /// E over all hole-card deals of `value(root, cards, [])`. Default: Monte Carlo. + fn deal_mean(&self, root: &State, sc: &mut Scratch) -> [f64; MAX_PLAYERS] { + const M: usize = 128; + let mut acc = [0.0; MAX_PLAYERS]; + for _ in 0..M { + let d = Deal::random(&mut sc.rng); + let v = self.value( + &Query { + state: root, + holes: &d.holes, + board: &[], + }, + sc, + ); + for i in 0..MAX_PLAYERS { + acc[i] += v[i] / M as f64; + } + } + acc + } +} + +/// Check-down equity baseline (see module docs). +pub struct EquityEstimator { + /// Preflop board samples (postflop is exact enumeration). + pub preflop_samples: usize, +} + +impl Default for EquityEstimator { + fn default() -> Self { + EquityEstimator { + preflop_samples: 256, + } + } +} + +/// Call-up totals: everyone live and not all-in matches the outstanding bet. +fn callup_totals(s: &State) -> [i32; MAX_PLAYERS] { + let mut t = [0; MAX_PLAYERS]; + for (i, ti) in t.iter_mut().enumerate().take(s.num_players()) { + *ti = s.contributed(i); + if !s.is_folded(i) && !s.is_all_in(i) { + *ti += (s.cur_bet() - s.street_bet(i)).clamp(0, s.stack(i)); + } + } + t +} + +impl EquityEstimator { + /// Expected fractional win share of each member of `elig` (bitmask) at showdown. + fn shares(&self, q: &Query, elig: u8, sc: &mut Scratch) -> [f64; MAX_PLAYERS] { + let len = q.board.len(); + if let Some(v) = sc.cache.get(&(elig, len as u8)) { + return *v; + } + let n = q.state.num_players(); + let members: Vec = (0..n).filter(|&i| elig >> i & 1 != 0).collect(); + let bm = mask_of(q.board); + let hm: Vec = (0..n) + .map(|i| bit(q.holes[i][0]) | bit(q.holes[i][1])) + .collect(); + let dead = hm.iter().fold(bm, |m, h| m | h); + let mut out = [0.0; MAX_PLAYERS]; + let mut count = 0.0; + let score = |run: u64, out: &mut [f64; MAX_PLAYERS]| { + let mut best = 0; + let mut w = [0usize; MAX_PLAYERS]; + let mut nw = 0; + for &i in &members { + let r = evaluate(hm[i] | bm | run); + if r > best { + best = r; + nw = 0; + } + if r == best { + w[nw] = i; + nw += 1; + } + } + for &i in &w[..nw] { + out[i] += 1.0 / nw as f64; + } + }; + let live: Vec = cards::cards_in(FULL_DECK & !dead).collect(); + match 5 - len { + 0 => { + score(0, &mut out); + count = 1.0; + } + 1 => { + for &c in &live { + score(bit(c), &mut out); + count += 1.0; + } + } + 2 => { + for (a, &c1) in live.iter().enumerate() { + for &c2 in &live[a + 1..] { + score(bit(c1) | bit(c2), &mut out); + count += 1.0; + } + } + } + _ => { + for _ in 0..self.preflop_samples { + let mut run = 0; + for _ in 0..5 - len { + run |= bit(sc.rng.draw(dead | run)); + } + score(run, &mut out); + count += 1.0; + } + } + } + out.iter_mut().for_each(|x| *x /= count); + sc.cache.insert((elig, len as u8), out); + out + } +} + +impl ValueEstimator for EquityEstimator { + fn value(&self, q: &Query, sc: &mut Scratch) -> [f64; MAX_PLAYERS] { + let s = q.state; + let n = s.num_players(); + let mut out = [0.0; MAX_PLAYERS]; + if s.live_count() == 1 { + for (i, o) in out.iter_mut().enumerate().take(n) { + *o = -(s.contributed(i) as f64); + if !s.is_folded(i) { + *o += s.pot() as f64; + } + } + return out; + } + let t = callup_totals(s); + let live = (0..n) + .filter(|&i| !s.is_folded(i)) + .fold(0u8, |m, i| m | 1 << i); + let mut levels: Vec = (0..n) + .filter(|&i| live >> i & 1 != 0) + .map(|i| t[i]) + .collect(); + levels.sort_unstable(); + levels.dedup(); + let mut prev = 0; + for &lv in &levels { + if lv <= prev { + continue; + } + let pot: i32 = (0..n).map(|i| t[i].min(lv) - t[i].min(prev)).sum(); + let elig = (0..n) + .filter(|&i| live >> i & 1 != 0 && t[i] >= lv) + .fold(0u8, |m, i| m | 1 << i); + if elig.count_ones() == 1 { + out[elig.trailing_zeros() as usize] += pot as f64; + } else { + let sh = self.shares(q, elig, sc); + for i in 0..n { + out[i] += pot as f64 * sh[i]; + } + } + prev = lv; + } + for i in 0..n { + out[i] -= t[i] as f64; + } + out + } + + fn chance_mean(&self, q: &Query, _next_len: usize, sc: &mut Scratch) -> [f64; MAX_PLAYERS] { + self.value(q, sc) // tower property + } + + fn deal_mean(&self, root: &State, sc: &mut Scratch) -> [f64; MAX_PLAYERS] { + let t = callup_totals(root); + let n = root.num_players(); + let live: Vec = (0..n) + .filter(|&i| !root.is_folded(i)) + .map(|i| t[i]) + .collect(); + if live.len() == n && live.iter().all(|&x| x == live[0]) { + return [0.0; MAX_PLAYERS]; // exchangeable seats: share = pot/n = own total + } + let mut acc = [0.0; MAX_PLAYERS]; + for _ in 0..128 { + let d = Deal::random(&mut sc.rng); + let v = self.value( + &Query { + state: root, + holes: &d.holes, + board: &[], + }, + &mut Scratch::new(sc.rng.next_u64()), + ); + for i in 0..MAX_PLAYERS { + acc[i] += v[i] / 128.0; + } + } + acc + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Mode { + /// Chance nodes and every known-policy decision. + Full, + /// Only the hole-card deal (the paper's per-human baseline). + CardsOnly, +} + +/// Accumulates the AIVAT correction over one hand. +pub struct Tracker<'a> { + pub est: &'a dyn ValueEstimator, + pub sc: &'a mut Scratch, + pub mode: Mode, + pub deal: Deal, + pub corr: [f64; MAX_PLAYERS], +} + +impl<'a> Tracker<'a> { + pub fn new(est: &'a dyn ValueEstimator, sc: &'a mut Scratch, mode: Mode, deal: Deal) -> Self { + Tracker { + est, + sc, + mode, + deal, + corr: [0.0; MAX_PLAYERS], + } + } + fn val(&mut self, st: &State, len: usize) -> [f64; MAX_PLAYERS] { + let (est, deal) = (self.est, self.deal); + est.value( + &Query { + state: st, + holes: &deal.holes, + board: &deal.board[..len], + }, + self.sc, + ) + } + pub fn start(&mut self, root: &State) { + let m = self.est.deal_mean(root, self.sc); + let v = self.val(root, 0); + for i in 0..MAX_PLAYERS { + self.corr[i] += m[i] - v[i]; + } + } + /// A known-policy player at `st` drew entry `chosen` of `dist`. + pub fn decision(&mut self, st: &State, len: usize, dist: &Dist, chosen: usize) { + if self.mode != Mode::Full { + return; + } + let mut sampled = [0.0; MAX_PLAYERS]; + let mut mean = [0.0; MAX_PLAYERS]; + for a in 0..dist.len() { + let mut s2 = *st; + s2.apply(dist.action(a)); + let v = self.val(&s2, len); + let p = dist.prob(a); + for i in 0..MAX_PLAYERS { + mean[i] += p * v[i]; + if a == chosen { + sampled[i] = v[i]; + } + } + } + for i in 0..MAX_PLAYERS { + self.corr[i] += mean[i] - sampled[i]; + } + } + /// Board reveal from `from` to `to` visible cards at (post-action) state `st`. + pub fn chance(&mut self, st: &State, from: usize, to: usize) { + if self.mode != Mode::Full { + return; + } + let deal = self.deal; + let q = Query { + state: st, + holes: &deal.holes, + board: &deal.board[..from], + }; + let m = self.est.chance_mean(&q, to, self.sc); + let v = self.val(st, to); + for i in 0..MAX_PLAYERS { + self.corr[i] += m[i] - v[i]; + } + } +} diff --git a/arena/bench/src/bp.rs b/arena/bench/src/bp.rs new file mode 100644 index 00000000..565dcc47 --- /dev/null +++ b/arena/bench/src/bp.rs @@ -0,0 +1,555 @@ +//! Blueprint-backed policy, biased continuation variants, a coarse test bucketer, and +//! checkpoint loading (via `blueprint::io`, which stores only the `Store`; the bucketer and +//! sizing are chosen by name, see [`bucketer_by_name`] / [`sizing_by_name`]). + +use crate::policy::{Dist, Player, PolicyFactory, View}; +use blueprint::store::Store; +use blueprint::trainer::Bucketer; +use cards::{Card, Rng}; +use nlhe::abstraction::{ActionList, BetSizing, Shadow}; +pub use nlhe::abstraction::{BelowMenu, TrackOpts, Translation}; +use nlhe::{Action, GameConfig, State, Street}; +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; +use std::sync::Arc; + +/// Preflop lossless (169); postflop made-hand category only. For tests and toy blueprints. +pub struct CoarseBucketer; +impl Bucketer for CoarseBucketer { + fn bucket(&self, street: Street, hole: [Card; 2], board: &[Card]) -> u32 { + if street == Street::Preflop { + return cards::preflop_class(hole[0], hole[1]) as u32; + } + let m = cards::mask_of(board) | cards::bit(hole[0]) | cards::bit(hole[1]); + cards::category(cards::evaluate(m)) as u32 + } + fn n_buckets(&self, street: Street) -> u32 { + if street == Street::Preflop { + 169 + } else { + 9 + } + } +} + +/// Real abstraction: `abstraction::tables::BucketTables` (preflop 169 lossless, postflop k-means). +pub struct TableBucketer(pub abstraction::tables::BucketTables); +impl Bucketer for TableBucketer { + fn bucket(&self, _street: Street, hole: [Card; 2], board: &[Card]) -> u32 { + self.0.bucket(hole, board) + } + fn n_buckets(&self, street: Street) -> u32 { + match street { + Street::Preflop => 169, + s => self.0.buckets[s.idx() - 1] as u32, + } + } +} + +/// Registry hook: add real abstraction tables here when they exist. +pub fn bucketer_by_name(name: &str) -> Option> { + match name { + "coarse" => Some(Arc::new(CoarseBucketer)), + // "tables:", e.g. tables:data/buckets-200 + n if n.starts_with("tables:") => { + let t = abstraction::tables::BucketTables::load(std::path::Path::new(&n[7..])).ok()?; + Some(Arc::new(TableBucketer(t))) + } + _ => None, + } +} + +pub fn sizing_by_name(name: &str) -> Option { + match name { + "tiny" => Some(BetSizing::tiny()), + "pluribus" | "paper" => Some(BetSizing::pluribus_blueprint()), + "local" => { + use nlhe::abstraction::Menu; + let m = Menu::new; + let pre = [ + m(&[0.4, 0.6, 1.0, 2.0], true), + m(&[0.75, 1.25], true), + m(&[1.0], true), + m(&[], true), + ]; + let flop = [m(&[0.5, 1.0], true), m(&[1.0], true)]; + let late = [m(&[0.5, 1.0], true), m(&[1.0], true)]; + Some(BetSizing::new([&pre, &flop, &late, &late], [4, 3, 3, 3])) + } + "medium" => { + // Between `local` and `paper`: 8 preflop opening sizes (~2–8.5bb), richer 3-bet and + // flop menus; turn/river exactly as published. + use nlhe::abstraction::Menu; + let m = Menu::new; + let pre = [ + m(&[0.4, 0.5, 0.6, 0.75, 1.0, 1.5, 2.0, 3.0], true), + m(&[0.5, 0.75, 1.0, 1.5], true), + m(&[0.75, 1.25], true), + m(&[], true), + ]; + let flop = [m(&[0.33, 0.5, 1.0], true), m(&[0.5, 1.0], true)]; + let late = [m(&[0.5, 1.0], true), m(&[1.0], true)]; + Some(BetSizing::new([&pre, &flop, &late, &late], [4, 3, 3, 3])) + } + "adversarial" => { + // Attacker menu for exploitability tests against a `medium` target (never a target + // itself): tiny bets and near-min raises, sizes just past the target's pseudo-harmonic + // midpoints, overbets, and one more raise per street than the target's tree allows. + use nlhe::abstraction::Menu; + let m = Menu::new; + let pre = [ + m(&[0.05, 0.15, 0.3, 0.45, 0.7, 1.0, 2.0], true), + m(&[0.05, 0.3, 0.6, 1.0, 2.0], true), + m(&[0.05, 0.5, 1.0], true), + m(&[0.05], true), + m(&[0.05], true), + ]; + let post = [ + m(&[0.05, 0.15, 0.25, 0.42, 0.7, 1.3, 2.5], true), + m(&[0.05, 0.4, 1.0], true), + m(&[0.05], true), + m(&[0.05], true), + ]; + Some(BetSizing::new([&pre, &post, &post, &post], [5, 4, 4, 4])) + } + _ => None, + } +} + +/// Final-strategy lookup backend other than a live `Store` (e.g. a compact policy file). +/// Must return the *final* distribution (no street-dependent averaging left to do). +pub trait Source: Send + Sync { + /// Fill `out` (one entry per abstract action) for (history key, bucket); false if the + /// infoset is absent or has a different action count. + fn probs(&self, hist: u64, bucket: u32, out: &mut [f32]) -> bool; +} + +struct Shared { + /// Placeholder (empty) store when `source` is set. + store: Arc, + source: Option>, + bucketer: Arc, + sizing: BetSizing, + opts: TrackOpts, + avg_preflop: bool, + misses: AtomicU64, + lookups: AtomicU64, + /// Decision diagnostics split by whether an earlier action was off-menu: `[on, off]`. + diag: [Diag; 2], +} + +/// Per-class decision counters; probability masses are in micro-units. +#[derive(Default)] +struct Diag { + lookups: AtomicU64, + misses: AtomicU64, + desync: AtomicU64, + /// Desync reasons (index = `Shadow::sync_reason`). + why: [AtomicU64; 6], + fold: AtomicU64, + call: AtomicU64, + raise: AtomicU64, +} + +pub struct BlueprintPolicy { + name: String, + sh: Arc, +} + +impl BlueprintPolicy { + pub fn new( + name: &str, + store: Arc, + bucketer: Arc, + sizing: BetSizing, + ) -> Self { + BlueprintPolicy { + name: name.to_string(), + sh: Arc::new(Shared { + store, + source: None, + bucketer, + sizing, + opts: TrackOpts::default(), + avg_preflop: true, + misses: AtomicU64::new(0), + lookups: AtomicU64::new(0), + diag: Default::default(), + }), + } + } + /// Policy over a non-`Store` backend ([`Source`]): same history tracking, translation and + /// fallback as the store-backed policy. `store()` then returns an empty placeholder. + pub fn from_source( + name: &str, + source: Arc, + bucketer: Arc, + sizing: BetSizing, + ) -> Self { + let mut p = Self::new(name, Arc::new(Store::new(16)), bucketer, sizing); + Arc::get_mut(&mut p.sh).expect("unshared").source = Some(source); + p + } + pub fn with_translation(mut self, t: Translation) -> Self { + Arc::get_mut(&mut self.sh).expect("unshared").opts.translation = t; + self + } + pub fn with_below(mut self, b: BelowMenu) -> Self { + Arc::get_mut(&mut self.sh).expect("unshared").opts.below = b; + self + } + /// All translation options at once (`TrackOpts::LEGACY` reproduces the pre-fix policy). + pub fn with_opts(mut self, o: TrackOpts) -> Self { + Arc::get_mut(&mut self.sh).expect("unshared").opts = o; + self + } + pub fn opts(&self) -> TrackOpts { + self.sh.opts + } + /// One-line JSON of the decision diagnostics (on-menu vs after-off-menu histories). + pub fn diag_json(&self) -> String { + let one = |d: &Diag| { + let n = d.lookups.load(Relaxed).max(1) as f64; + let m = |x: &AtomicU64| x.load(Relaxed) as f64 / 1e6 / n; + format!( + "{{\"decisions\":{},\"miss\":{:.4},\"desync\":{:.4},\"why\":[{},{},{},{},{}],\"p_fold\":{:.4},\"p_call\":{:.4},\"p_raise\":{:.4}}}", + d.lookups.load(Relaxed), + d.misses.load(Relaxed) as f64 / n, + d.desync.load(Relaxed) as f64 / n, + d.why[1].load(Relaxed), + d.why[2].load(Relaxed), + d.why[3].load(Relaxed), + d.why[4].load(Relaxed), + d.why[5].load(Relaxed), + m(&d.fold), + m(&d.call), + m(&d.raise) + ) + }; + format!("{{\"on_menu\":{},\"after_off_menu\":{}}}", one(&self.sh.diag[0]), one(&self.sh.diag[1])) + } + pub fn with_avg_preflop(mut self, on: bool) -> Self { + Arc::get_mut(&mut self.sh).expect("unshared").avg_preflop = on; + self + } + pub fn store(&self) -> &Store { + &self.sh.store + } + /// Fraction of decisions whose infoset was missing from the store (fallback: check/call). + pub fn miss_rate(&self) -> f64 { + self.sh.misses.load(Relaxed) as f64 / self.sh.lookups.load(Relaxed).max(1) as f64 + } + pub fn from_file( + path: &std::path::Path, + bucketer: &str, + sizing: &str, + capacity: usize, + ) -> Result { + let store = blueprint::io::load(path, capacity, 0).map_err(|e| e.to_string())?; + let b = bucketer_by_name(bucketer).ok_or(format!("unknown bucketer {bucketer}"))?; + let s = sizing_by_name(sizing).ok_or(format!("unknown sizing {sizing}"))?; + Ok(Self::new( + &format!("bp:{}", path.display()), + Arc::new(store), + b, + s, + )) + } +} + +impl PolicyFactory for BlueprintPolicy { + fn name(&self) -> String { + self.name.clone() + } + fn report(&self) -> Option { + Some(self.diag_json()) + } + fn new_player(&self, _seat: usize, _cfg: &GameConfig, seed: u64) -> Box { + Box::new(BpPlayer { + sh: self.sh.clone(), + seat: _seat, + track: Shadow::new(&State::new(_cfg), self.sh.opts), + rng: Rng::new(seed), + }) + } +} + +#[derive(Clone)] +struct BpPlayer { + sh: Arc, + seat: usize, + track: Shadow, + rng: Rng, +} + +impl Player for BpPlayer { + fn observe(&mut self, pre: &State, seat: usize, a: Action) { + self.track + .observe(pre, &self.sh.sizing, a, seat == self.seat, &mut self.rng); + } + + fn dist(&mut self, v: &View, hole: [Card; 2]) -> Dist { + let sh = &self.sh; + let diag = &sh.diag[usize::from(self.track.off_tree())]; + sh.lookups.fetch_add(1, Relaxed); + diag.lookups.fetch_add(1, Relaxed); + let passive = |st: &State| { + if st.legal().can_check { + Action::Check + } else { + Action::Call + } + }; + let mut d = Dist::new(); + let why = self.track.sync_reason(v.state); + if why != 0 { + sh.misses.fetch_add(1, Relaxed); + diag.misses.fetch_add(1, Relaxed); + diag.desync.fetch_add(1, Relaxed); + if diag.why[why as usize].fetch_add(1, Relaxed) < 6 && std::env::var_os("PLURIBUS_DEBUG_DESYNC").is_some() { + eprintln!("DESYNC why={why}\n real {:?}\n shadow {:?}\n hist {:?}", v.state, self.track, v.history); + } + if sh.opts.keep_sync { + d.push(fallback_action(v.state, v.board, hole), 1.0); + } else { + d.push(passive(v.state), 1.0); + } + return d; + } + let mut list = ActionList::new(); + self.track.actions(v.state, &sh.sizing, &mut list); + let n = list.len(); + let street = v.state.street(); + let bucket = sh.bucketer.bucket(street, hole, v.board); + let key = self.track.key(); + let mut p = [0f32; nlhe::abstraction::MAX_ACTIONS]; + let found = if let Some(src) = &sh.source { + src.probs(key, bucket, &mut p[..n]) + } else if let Some(slot) = sh + .store + .lookup(key, bucket) + .filter(|q| q.n_actions as usize == n) + { + if sh.avg_preflop && street == Street::Preflop { + sh.store.average(slot, &mut p[..n]); + } else { + sh.store.strategy(slot, &mut p[..n]); + } + true + } else { + false + }; + if !found { + sh.misses.fetch_add(1, Relaxed); + diag.misses.fetch_add(1, Relaxed); + if sh.opts.keep_sync { + d.push(fallback_action(v.state, v.board, hole), 1.0); + } else { + d.push(passive(v.state), 1.0); + } + return d; + } + let tot: f32 = p[..n].iter().sum::().max(1e-12); + for i in 0..n { + let w = (p[i] / tot * 1e6) as u64; + match list.get(i) { + Action::Fold => diag.fold.fetch_add(w, Relaxed), + Action::Check | Action::Call => diag.call.fetch_add(w, Relaxed), + Action::RaiseTo(_) => diag.raise.fetch_add(w, Relaxed), + }; + d.push(self.track.real_action(v.state, &list, i), p[i]); + } + d + } + + fn exposes_probs(&self) -> bool { + self.sh.opts.translation == Translation::Deterministic + } + fn fork(&self) -> Option> { + Some(Box::new(self.clone())) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Bias { + Fold, + Call, + Raise, +} + +/// Pluribus continuation strategy: multiply one action class by 5 and renormalise. +pub struct Biased { + pub inner: Arc, + pub bias: Bias, + pub factor: f32, +} + +impl Biased { + pub fn new(inner: Arc, bias: Bias) -> Self { + Biased { + inner, + bias, + factor: 5.0, + } + } +} + +impl PolicyFactory for Biased { + fn name(&self) -> String { + format!( + "{}+{}x{}", + self.inner.name(), + format!("{:?}", self.bias).to_lowercase(), + self.factor + ) + } + fn report(&self) -> Option { + self.inner.report() + } + fn new_player(&self, seat: usize, cfg: &GameConfig, seed: u64) -> Box { + Box::new(BiasedPlayer { + inner: self.inner.new_player(seat, cfg, seed), + bias: self.bias, + factor: self.factor, + }) + } +} + +struct BiasedPlayer { + inner: Box, + bias: Bias, + factor: f32, +} + +impl Player for BiasedPlayer { + fn observe(&mut self, pre: &State, seat: usize, a: Action) { + self.inner.observe(pre, seat, a) + } + fn observe_board(&mut self, b: &[Card]) { + self.inner.observe_board(b) + } + fn dist(&mut self, v: &View, hole: [Card; 2]) -> Dist { + let d = self.inner.dist(v, hole); + let mut out = Dist::new(); + for i in 0..d.len() { + let a = d.action(i); + let hit = match (self.bias, a) { + (Bias::Fold, Action::Fold) + | (Bias::Call, Action::Call | Action::Check) + | (Bias::Raise, Action::RaiseTo(_)) => true, + _ => false, + }; + out.push(a, d.prob(i) as f32 * if hit { self.factor } else { 1.0 }); + } + out + } + fn exposes_probs(&self) -> bool { + self.inner.exposes_probs() + } + fn fork(&self) -> Option> { + Some(Box::new(BiasedPlayer { + inner: self.inner.fork()?, + bias: self.bias, + factor: self.factor, + })) + } +} + +/// Train a small blueprint (toy schedule) for tests and demos. +pub fn train_toy(players: usize, iters: u64, seed: u64) -> BlueprintPolicy { + use blueprint::trainer::{Schedule, Trainer}; + let game = GameConfig::new(players); + let sched = Schedule { + discount_interval: 1000, + lcfr_until: iters / 3, + prune_after: iters / 6, + prune_prob: 0.95, + prune_threshold: -3_000_000, + strategy_interval: 10, + avg_after: 0, + }; + let tr = Trainer::new( + game, + BetSizing::tiny(), + sched, + &CoarseBucketer, + 1 << 25, + seed, + ); + tr.run(0, iters, |_, _, _| {}); + BlueprintPolicy::new( + "toy-bp", + tr.store, + Arc::new(CoarseBucketer), + BetSizing::tiny(), + ) +} + +/// Equity of `hole` against `opps` random hands with the board completed at random (Monte Carlo, +/// seeded by the cards so the same spot always gets the same number). +fn mc_equity(hole: [Card; 2], board: &[Card], opps: usize, samples: u32) -> f64 { + let dead = cards::mask_of(&hole) | cards::mask_of(board); + let deck: Vec = cards::cards_in(cards::FULL_DECK & !dead).collect(); + let mut rng = Rng::new(dead ^ 0x9E37_79B9_7F4A_7C15); + let need_board = 5 - board.len(); + let need = need_board + 2 * opps; + let mut buf = deck.clone(); + let mut share = 0.0; + for _ in 0..samples { + for k in 0..need { + let j = k + rng.below((buf.len() - k) as u32) as usize; + buf.swap(k, j); + } + let mut b = cards::mask_of(board); + for &c in &buf[..need_board] { + b |= cards::bit(c); + } + let me = cards::eval::evaluate(b | cards::mask_of(&hole)); + let (mut best, mut ties) = (true, 1u32); + for o in 0..opps { + let h = &buf[need_board + 2 * o..need_board + 2 * o + 2]; + let r = cards::eval::evaluate(b | cards::mask_of(h)); + if r > me { + best = false; + break; + } + if r == me { + ties += 1; + } + } + if best { + share += 1.0 / ties as f64; + } + } + share / samples as f64 +} + +/// Play when the blueprint cannot be queried (the shadow lost the real game, or the infoset is +/// missing): by hand strength against the players still in, never a blind check/call. Facing a +/// bet it continues only with equity clearly above the price (betting ranges are stronger than +/// random hands); strong hands bet or raise about pot. +pub fn fallback_action(st: &State, board: &[Card], hole: [Card; 2]) -> Action { + let me = st.to_act().unwrap_or(0); + let opps = (0..st.num_players()) + .filter(|&s| s != me && !st.is_folded(s)) + .count() + .max(1); + let e = mc_equity(hole, board, opps, 400); + let l = st.legal(); + let pot = st.pot() as f64; + let raise = |frac: f64| { + let to = st.cur_bet() + ((pot + l.call_amount as f64) * frac).round() as i32; + Action::RaiseTo(to.clamp(l.min_raise_to, l.max_raise_to)) + }; + if l.can_check { + return if l.can_raise && e > 0.70 { raise(0.75) } else { Action::Check }; + } + let c = l.call_amount as f64; + let price = c / (pot + c); + if l.can_raise && e > 0.85 { + raise(1.0) + } else if e > price + 0.12 { + Action::Call + } else { + Action::Fold + } +} diff --git a/arena/bench/src/builtin.rs b/arena/bench/src/builtin.rs new file mode 100644 index 00000000..f5eb2a6f --- /dev/null +++ b/arena/bench/src/builtin.rs @@ -0,0 +1,270 @@ +//! Gauntlet opponents: simple heuristics on preflop hand percentile and postflop +//! made-hand percentile (current strength vs a random hand, no draws). Not tuned. + +use crate::policy::{Dist, Player, PolicyFactory, View}; +use cards::{all_holes, bit, evaluate, mask_of, Card, Hand}; +use nlhe::{Action, GameConfig, Street}; +use std::sync::{Arc, OnceLock}; + +#[derive(Clone, Copy, Debug)] +pub enum Kind { + Random, + Station, + Heur(Style), +} + +#[derive(Clone, Copy, Debug)] +pub struct Style { + /// Preflop percentile (0..1, higher = better hand) needed to open-raise. + pub open: f32, + /// ... to re-raise a raise. + pub reraise: f32, + /// ... to call a raise. + pub call_pre: f32, + /// Postflop percentile to bet / raise for value. + pub bet: f32, + /// Postflop percentile to continue vs a bet. + pub call_post: f32, + /// Probability of raising when the hand is strong enough. + pub aggr: f32, + /// Probability of bluff-raising otherwise. + pub bluff: f32, + /// Postflop bet size, pot fraction. + pub size: f32, +} + +pub const NIT: Style = Style { + open: 0.88, + reraise: 0.97, + call_pre: 0.90, + bet: 0.85, + call_post: 0.70, + aggr: 0.8, + bluff: 0.01, + size: 0.66, +}; +pub const TAG: Style = Style { + open: 0.75, + reraise: 0.93, + call_pre: 0.80, + bet: 0.70, + call_post: 0.50, + aggr: 0.85, + bluff: 0.08, + size: 0.66, +}; +pub const LAG: Style = Style { + open: 0.55, + reraise: 0.85, + call_pre: 0.60, + bet: 0.55, + call_post: 0.35, + aggr: 0.85, + bluff: 0.20, + size: 0.75, +}; +pub const MANIAC: Style = Style { + open: 0.30, + reraise: 0.60, + call_pre: 0.35, + bet: 0.35, + call_post: 0.25, + aggr: 0.95, + bluff: 0.45, + size: 1.0, +}; + +pub struct Builtin { + pub name: &'static str, + pub kind: Kind, +} + +pub fn all_builtins() -> Vec> { + ["random", "station", "nit", "tag", "lag", "maniac"] + .iter() + .map(|n| builtin(n).unwrap()) + .collect() +} + +pub fn builtin(name: &str) -> Option> { + let (name, kind) = match name { + "random" => ("random", Kind::Random), + "station" => ("station", Kind::Station), + "nit" => ("nit", Kind::Heur(NIT)), + "tag" => ("tag", Kind::Heur(TAG)), + "lag" => ("lag", Kind::Heur(LAG)), + "maniac" => ("maniac", Kind::Heur(MANIAC)), + _ => return None, + }; + Some(Arc::new(Builtin { name, kind })) +} + +impl PolicyFactory for Builtin { + fn name(&self) -> String { + self.name.to_string() + } + fn new_player(&self, _seat: usize, _cfg: &GameConfig, _seed: u64) -> Box { + Box::new(HeurPlayer { + kind: self.kind, + cache_board: u64::MAX, + sorted: Vec::new(), + }) + } +} + +#[derive(Clone)] +struct HeurPlayer { + kind: Kind, + cache_board: Hand, + sorted: Vec, +} + +/// Chen formula score. +fn chen(a: Card, b: Card) -> f32 { + let (hi, lo) = ( + cards::rank_of(a).max(cards::rank_of(b)), + cards::rank_of(a).min(cards::rank_of(b)), + ); + let pts = |r: u8| match r { + 12 => 10.0, + 11 => 8.0, + 10 => 7.0, + 9 => 6.0, + r => (r as f32 + 2.0) / 2.0, + }; + let mut s = pts(hi); + if hi == lo { + return (s * 2.0).max(5.0).ceil(); + } + if cards::suit_of(a) == cards::suit_of(b) { + s += 2.0; + } + let gap = hi - lo - 1; + s -= [0.0, 1.0, 2.0, 4.0][gap.min(3) as usize] + if gap >= 4 { 1.0 } else { 0.0 }; + if gap <= 1 && hi < 10 { + s += 1.0; + } + s.ceil() +} + +/// Preflop percentile of every hole pair (by Chen score), indexed by `hole_index`. +fn preflop_pct(hole: [Card; 2]) -> f32 { + static T: OnceLock> = OnceLock::new(); + let t = T.get_or_init(|| { + let hs = all_holes(); + let sc: Vec = hs.iter().map(|h| chen(h[0], h[1])).collect(); + sc.iter() + .map(|&x| { + let below = sc.iter().filter(|&&y| y < x).count() as f32; + let eq = sc.iter().filter(|&&y| y == x).count() as f32; + (below + 0.5 * eq) / sc.len() as f32 + }) + .collect() + }); + t[cards::hole_index(hole[0], hole[1])] +} + +impl HeurPlayer { + /// Percentile of the made hand among all hole pairs on this board. + fn post_pct(&mut self, hole: [Card; 2], board: &[Card]) -> f32 { + let bm = mask_of(board); + if self.cache_board != bm { + self.cache_board = bm; + self.sorted = all_holes() + .iter() + .filter(|h| bit(h[0]) & bm == 0 && bit(h[1]) & bm == 0) + .map(|h| evaluate(bit(h[0]) | bit(h[1]) | bm)) + .collect(); + self.sorted.sort_unstable(); + } + let r = evaluate(bit(hole[0]) | bit(hole[1]) | bm); + let lo = self.sorted.partition_point(|&x| x < r); + let hi = self.sorted.partition_point(|&x| x <= r); + (lo as f32 + 0.5 * (hi - lo) as f32) / self.sorted.len() as f32 + } +} + +fn soft(s: f32, th: f32) -> f32 { + ((s - th) / 0.05 + 0.5).clamp(0.0, 1.0) +} + +fn raise_target(v: &View, frac: f32, preflop_triple: bool) -> Option { + let l = v.state.legal(); + if !l.can_raise { + return None; + } + let to = if preflop_triple { + v.state.cur_bet() * 3 + } else { + v.state.cur_bet() + (frac * (v.state.pot() + l.call_amount) as f32).round() as i32 + }; + Some(Action::RaiseTo(to.clamp(l.min_raise_to, l.max_raise_to))) +} + +impl Player for HeurPlayer { + fn fork(&self) -> Option> { + Some(Box::new(self.clone())) + } + + fn dist(&mut self, v: &View, hole: [Card; 2]) -> Dist { + let l = v.state.legal(); + let passive = if l.can_check { + Action::Check + } else { + Action::Call + }; + let mut d = Dist::new(); + match self.kind { + Kind::Station => d.push(passive, 1.0), + Kind::Random => { + let r = raise_target(v, 1.0, false); + let (pf, pr) = ( + if l.can_fold { 0.15 } else { 0.0 }, + if r.is_some() { 0.25 } else { 0.0 }, + ); + d.push(passive, 1.0 - pf - pr); + if pf > 0.0 { + d.push(Action::Fold, pf); + } + if let Some(r) = r { + d.push(r, pr); + } + } + Kind::Heur(st) => { + let pre = v.state.street() == Street::Preflop; + let s = if pre { + preflop_pct(hole) + } else { + self.post_pct(hole, v.board) + }; + let raised = v.state.raises_this_street() > 0; + let (raise_th, call_th) = if pre { + (if raised { st.reraise } else { st.open }, st.call_pre) + } else { + (st.bet, st.call_post) + }; + let odds = l.call_amount as f32 / (v.state.pot() + l.call_amount).max(1) as f32; + let call_th = if l.can_fold { + call_th.min(1.0) + 0.35 * odds * (1.0 - call_th) + } else { + 0.0 + }; + let strong = soft(s, raise_th); + let mut pr = st.aggr * strong + st.bluff * (1.0 - strong); + let rt = raise_target(v, st.size, pre); + if rt.is_none() { + pr = 0.0; + } + if let Some(r) = rt { + d.push(r, pr); + } + let cont = if l.can_fold { soft(s, call_th) } else { 1.0 }; + d.push(passive, (1.0 - pr) * cont); + if l.can_fold && cont < 1.0 { + d.push(Action::Fold, (1.0 - pr) * (1.0 - cont)); + } + } + } + d + } +} diff --git a/arena/bench/src/chart.rs b/arena/bench/src/chart.rs new file mode 100644 index 00000000..811c02e0 --- /dev/null +++ b/arena/bench/src/chart.rs @@ -0,0 +1,577 @@ +//! `chart6`: a deterministic, rule-based 6-max bot in the style of a "GTO-chart + pot-odds" +//! player (what a disciplined human reg or a commercial rule-based bot does), implemented +//! natively so it can be a fast, reproducible opponent. +//! +//! * Preflop: position-dependent open-raise charts (hand lists in the shape of commonly +//! published 100 bb 6-max RFI charts: UTG ~16 %, HJ ~21 %, CO ~27 %, BTN ~44 %, SB ~42 % +//! raise-or-fold), then 3-bet / call / 4-bet / 5-bet-jam bands that depend on the +//! opener's and hero's position. Response bands are percentile cut-offs on a hand +//! ranking (equity vs a random hand, computed once at start-up). These are *approximations* +//! of published charts written from memory, not a copy of any solver output. +//! * Postflop: Monte-Carlo equity against a range proxy (top fraction of villain's hands by +//! expected future strength, narrower when facing bigger bets or raises), then pot-odds +//! calls, value bets/raises, c-bets and a few hash-driven bluffs. +//! +//! Everything is a pure function of (public history, hole cards): the "randomness" (bluffs, +//! MC sampling) is seeded from a hash of the situation, so `dist` is a deterministic point +//! mass and AIVAT can treat the bot as a known strategy. + +use crate::mix; +use crate::policy::{Dist, Player, PolicyFactory, View}; +use cards::{bit, cards_in, evaluate, mask_of, Card, Hand, Rng, FULL_DECK}; +use nlhe::{Action, GameConfig, Street}; +use std::sync::OnceLock; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Pos { + Sb, + Bb, + Utg, + Hj, + Co, + Btn, +} + +fn pos_of(seat: usize, n: usize) -> Pos { + if n == 2 { + return if seat == 0 { Pos::Btn } else { Pos::Bb }; + } + match seat { + 0 => Pos::Sb, + 1 => Pos::Bb, + s if s == n - 1 => Pos::Btn, + s if s == n - 2 => Pos::Co, + s if s == n - 3 => Pos::Hj, + _ => Pos::Utg, + } +} + +/// 13x13 class membership parsed from tokens like `22+`, `A2s+`, `ATo+`, `T9s`, `KQo`. +fn parse_range(s: &str) -> [bool; 169] { + let mut out = [false; 169]; + let rk = |c: char| "23456789TJQKA".find(c).unwrap(); + let class = |hi: usize, lo: usize, suited: bool| { + if hi == lo { + hi + } else { + let tri = hi * (hi - 1) / 2 + lo; + if suited { + 13 + tri + } else { + 91 + tri + } + } + }; + for tok in s.split(',').map(str::trim).filter(|t| !t.is_empty()) { + let c: Vec = tok.chars().collect(); + let (a, b) = (rk(c[0]), rk(c[1])); + let plus = tok.ends_with('+'); + let suited = c.get(2) == Some(&'s'); + if a == b { + let top = if plus { 12 } else { a }; + for r in a..=top { + out[class(r, r, false)] = true; + } + } else { + let (hi, lo) = (a.max(b), a.min(b)); + let top = if plus { hi - 1 } else { lo }; + for l in lo..=top { + out[class(hi, l, suited)] = true; + } + } + } + out +} + +struct Tables { + /// Percentile (0 = best) of each class: fraction of combos strictly better + half of own. + pct: [f32; 169], + rfi: [[bool; 169]; 6], + /// Fraction of combos in each RFI chart (for the scaled styles). + rfi_width: [f32; 6], +} + +fn tables() -> &'static Tables { + static T: OnceLock = OnceLock::new(); + T.get_or_init(|| { + // Equity vs a random hand for each class (deterministic MC). + let mut eq = [0f64; 169]; + let mut combos = [0f64; 169]; + let mut rng = Rng::new(0xC0FFEE); + for hi in 0..13u8 { + for lo in 0..=hi { + for suited in [false, true] { + if hi == lo && suited { + continue; + } + let (c1, c2) = (cards::card(hi, 0), cards::card(lo, if suited { 0 } else { 1 })); + let cls = cards::preflop_class(c1, c2); + combos[cls] = if hi == lo { 6.0 } else if suited { 4.0 } else { 12.0 }; + let (mut w, n) = (0.0, 3000); + for _ in 0..n { + let mut dead: Hand = bit(c1) | bit(c2); + let o1 = rng.draw(dead); + dead |= bit(o1); + let o2 = rng.draw(dead); + dead |= bit(o2); + let mut board: Hand = 0; + for _ in 0..5 { + let c = rng.draw(dead | board); + board |= bit(c); + } + let (a, b) = (evaluate(bit(c1) | bit(c2) | board), evaluate(bit(o1) | bit(o2) | board)); + w += if a > b { 1.0 } else if a == b { 0.5 } else { 0.0 }; + } + eq[cls] = w / n as f64; + } + } + } + let total: f64 = combos.iter().sum(); + let mut pct = [0f32; 169]; + for i in 0..169 { + if combos[i] == 0.0 { + pct[i] = 1.0; + continue; + } + let (mut better, mut same) = (0.0, 0.0); + for j in 0..169 { + if eq[j] > eq[i] { + better += combos[j]; + } else if eq[j] == eq[i] { + same += combos[j]; + } + } + pct[i] = ((better + same / 2.0) / total) as f32; + } + let rfi = [ + // SB (raise-or-fold) + parse_range("22+,A2s+,K2s+,Q4s+,J6s+,T6s+,96s+,86s+,75s+,65s,54s,A2o+,K8o+,Q9o+,J9o+,T9o"), + // BB (unused as an opener; iso-raise range vs limpers) + parse_range("77+,ATs+,KJs+,AJo+,KQo"), + // UTG + parse_range("22+,A4s+,K9s+,Q9s+,J9s+,T9s,98s,87s,76s,ATo+,KQo"), + // HJ + parse_range("22+,A2s+,K8s+,Q9s+,J9s+,T8s+,97s+,87s,76s,65s,ATo+,KJo+,QJo"), + // CO + parse_range("22+,A2s+,K5s+,Q8s+,J8s+,T8s+,97s+,86s+,75s+,65s,54s,A9o+,KTo+,QTo+,JTo"), + // BTN + parse_range("22+,A2s+,K2s+,Q4s+,J6s+,T6s+,96s+,85s+,75s+,64s+,54s,43s,A2o+,K8o+,Q9o+,J9o+,T9o,98o"), + ]; + let rfi_width = std::array::from_fn(|i| { + (0..169).filter(|&c| rfi[i][c]).map(|c| combos[c]).sum::() as f32 / 1326.0 + }); + Tables { pct, rfi, rfi_width } + }) +} + +fn pos_idx(p: Pos) -> usize { + match p { + Pos::Sb => 0, + Pos::Bb => 1, + Pos::Utg => 2, + Pos::Hj => 3, + Pos::Co => 4, + Pos::Btn => 5, + } +} + +/// (3-bet top-%, call top-% above the 3-bet band) for hero position vs opener position. +fn response_band(hero: Pos, opener: Pos) -> (f32, f32) { + let o = match opener { + Pos::Utg => 0, + Pos::Hj => 1, + Pos::Co => 2, + Pos::Btn => 3, + Pos::Sb => 4, + Pos::Bb => 4, + }; + let t: [(f32, f32); 5] = match hero { + Pos::Bb => [(0.05, 0.17), (0.06, 0.22), (0.08, 0.28), (0.12, 0.40), (0.13, 0.46)], + Pos::Sb => [(0.05, 0.0), (0.06, 0.0), (0.08, 0.02), (0.12, 0.06), (0.12, 0.06)], + Pos::Btn => [(0.04, 0.07), (0.05, 0.09), (0.08, 0.13), (0.08, 0.13), (0.08, 0.13)], + Pos::Co => [(0.04, 0.06), (0.05, 0.08), (0.05, 0.08), (0.05, 0.08), (0.05, 0.08)], + Pos::Hj => [(0.04, 0.05), (0.04, 0.05), (0.04, 0.05), (0.04, 0.05), (0.04, 0.05)], + Pos::Utg => [(0.04, 0.04), (0.04, 0.04), (0.04, 0.04), (0.04, 0.04), (0.04, 0.04)], + }; + t[o] +} + +/// The chart bot; `style` scales every preflop width and band and the postflop aggression: +/// 1.0 = `chart6` (the published-chart shape), 1.45 = `chart6-loose` (loose-aggressive), +/// 0.7 = `chart6-tight` (nit). +pub struct Chart6 { + pub style: f32, +} + +impl Chart6 { + pub const STD: Chart6 = Chart6 { style: 1.0 }; + pub fn by_name(name: &str) -> Option { + match name { + "chart6" => Some(Chart6 { style: 1.0 }), + "chart6-loose" => Some(Chart6 { style: 1.45 }), + "chart6-tight" => Some(Chart6 { style: 0.7 }), + _ => None, + } + } +} + +impl PolicyFactory for Chart6 { + fn name(&self) -> String { + match self.style { + s if s > 1.1 => "chart6-loose", + s if s < 0.9 => "chart6-tight", + _ => "chart6", + } + .into() + } + fn new_player(&self, _seat: usize, _cfg: &GameConfig, _seed: u64) -> Box { + Box::new(ChartPlayer { style: self.style }) + } +} + +#[derive(Clone)] +struct ChartPlayer { + style: f32, +} + +fn situation_hash(v: &View, hole: [Card; 2]) -> u64 { + let mut h = mix(0x51ED, (bit(hole[0]) | bit(hole[1])) ^ mask_of(v.board).rotate_left(7)); + h = mix(h, v.history.len() as u64 * 131 + v.seat as u64); + for e in v.history.iter().rev().take(6) { + h = mix(h, e.seat as u64 * 7919 + e.street.idx() as u64 * 31 + action_code(e.action)); + } + h +} + +fn action_code(a: Action) -> u64 { + match a { + Action::Fold => 1, + Action::Check => 2, + Action::Call => 3, + Action::RaiseTo(x) => 4 + x as u64 * 8, + } +} + +fn unit(h: u64) -> f64 { + (h >> 11) as f64 / (1u64 << 53) as f64 +} + +impl Player for ChartPlayer { + fn fork(&self) -> Option> { + Some(Box::new(self.clone())) + } + fn dist(&mut self, v: &View, hole: [Card; 2]) -> Dist { + let a = if v.state.street() == Street::Preflop { + preflop(v, hole, self.style) + } else { + postflop(v, hole, self.style) + }; + Dist::pure(legalize(v, a)) + } +} + +/// Make any intent legal: raise sizes clamped, impossible raises become calls/checks, folds +/// of a free check become checks. +fn legalize(v: &View, a: Action) -> Action { + let l = v.state.legal(); + match a { + Action::RaiseTo(t) => { + if l.can_raise { + let t = t.clamp(l.min_raise_to, l.max_raise_to); + // Do not leave a sliver behind: jam when the raise commits most of the stack. + let st = v.state; + let rem = l.max_raise_to - t; + if rem * 4 < (t - st.street_bet(v.seat)).max(1) { + Action::RaiseTo(l.max_raise_to) + } else { + Action::RaiseTo(t) + } + } else if l.can_check { + Action::Check + } else { + Action::Call + } + } + Action::Fold if l.can_check => Action::Check, + Action::Check if !l.can_check => Action::Call, + Action::Call if l.can_check => Action::Check, + x => x, + } +} + +fn preflop(v: &View, hole: [Card; 2], style: f32) -> Action { + let t = tables(); + let st = v.state; + let n = st.num_players(); + let pos = pos_of(v.seat, n); + let bb = v.cfg.big_blind; + let cls = cards::preflop_class(hole[0], hole[1]); + let pct = t.pct[cls]; + let raises = st.raises_this_street(); + let me_bet = st.street_bet(v.seat); + let cur = st.cur_bet(); + let l = st.legal(); + let preflop_events: Vec<_> = v.history.iter().filter(|e| e.street == Street::Preflop).collect(); + let limpers = preflop_events.iter().filter(|e| e.action == Action::Call).count() as i32; + let in_position = matches!(pos, Pos::Btn | Pos::Co); + + if raises == 0 { + let open_sz = if matches!(pos, Pos::Sb) { bb * 3 } else { bb * 5 / 2 }; + if pos == Pos::Bb && l.can_check { + // Option: raise only the very top over limpers. + if limpers > 0 && pct < 0.07 { + return Action::RaiseTo(bb * 35 / 10 + limpers * bb); + } + return Action::Check; + } + let in_range = if style == 1.0 { + t.rfi[pos_idx(pos)][cls] + } else { + pct < t.rfi_width[pos_idx(pos)] * style + }; + if in_range { + return Action::RaiseTo(open_sz + limpers * bb); + } + return Action::Fold; + } + + let opener = preflop_events + .iter() + .find(|e| matches!(e.action, Action::RaiseTo(_))) + .map(|e| pos_of(e.seat as usize, n)) + .unwrap_or(Pos::Utg); + let callers = preflop_events.iter().filter(|e| e.action == Action::Call).count() as i32; + let i_raised = me_bet > bb; + let pot_after_call = st.pot() + l.call_amount; + let shove_zone = |to: i32| to * 10 >= (me_bet + st.stack(v.seat)) * 4; + let big = |to: i32| if shove_zone(to) { l.max_raise_to } else { to }; + + match raises { + 1 => { + let (b3, bc) = response_band(pos, opener); + let (b3, bc) = (b3 * style, bc * style); + // Wider callers behind us -> squeeze bigger; multiway -> tighten the calling band. + if pct < b3 { + let to = if in_position { cur * 3 } else { cur * 37 / 10 } + callers * cur; + Action::RaiseTo(big(to)) + } else if pct < b3 + bc * if callers > 0 { 0.7 } else { 1.0 } { + Action::Call + } else { + Action::Fold + } + } + 2 => { + if i_raised { + let (b4, bc) = (0.025 * style, (if in_position { 0.09 } else { 0.07 }) * style); + if pct < b4 { + Action::RaiseTo(big(cur * 23 / 10)) + } else if pct < b4 + bc && pot_after_call > 0 { + Action::Call + } else { + Action::Fold + } + } else if pct < 0.012 { + Action::RaiseTo(big(cur * 23 / 10)) + } else if pct < 0.03 { + Action::Call + } else { + Action::Fold + } + } + _ => { + if pct < 0.010 { + Action::RaiseTo(l.max_raise_to) + } else if pct < 0.024 { + Action::Call + } else { + Action::Fold + } + } + } +} + +/// Expected-future-strength score of a villain combo on the current board. +fn future_score(c: [Card; 2], board: Hand, bl: usize, fut: &[Card]) -> f64 { + let base = bit(c[0]) | bit(c[1]) | board; + if bl == 5 { + return evaluate(base) as f64; + } + let mut s = 0.0; + let mut k = 0.0; + for &f in fut { + if bit(f) & base == 0 { + s += evaluate(base | bit(f)) as f64; + k += 1.0; + } + } + if k == 0.0 { + evaluate(base) as f64 + } else { + s / k + } +} + +fn postflop(v: &View, hole: [Card; 2], style: f32) -> Action { + let st = v.state; + let l = st.legal(); + let bl = v.board.len(); + let board = mask_of(v.board); + let hm = bit(hole[0]) | bit(hole[1]); + let h = situation_hash(v, hole); + let mut rng = Rng::new(h); + let pot = st.pot(); + let bb = v.cfg.big_blind; + let opps = (st.live_count() as i32 - 1).max(1); + let facing = l.call_amount > 0; + let raises = st.raises_this_street(); + let eff = (0..st.num_players()) + .filter(|&s| s != v.seat && !st.is_folded(s)) + .map(|s| st.stack(s) + st.street_bet(s)) + .max() + .unwrap_or(0) + .min(st.stack(v.seat) + st.street_bet(v.seat)); + + // Villain range proxy: top `keep` fraction by expected future strength. + let frac_bet = if facing { + l.call_amount as f64 / (pot - l.call_amount).max(bb) as f64 + } else { + 0.0 + }; + let keep = if !facing { + 0.85 + } else if raises >= 2 { + 0.20 + } else { + (0.78 - 0.36 * frac_bet.min(1.3)).clamp(0.28, 0.75) + }; + let fut: Vec = { + let mut r = Rng::new(h ^ 0xABCD); + let mut dead = board | hm; + (0..6) + .map(|_| { + let c = r.draw(dead); + dead |= bit(c); + c + }) + .collect() + }; + let mut combos: Vec<([Card; 2], f64)> = Vec::with_capacity(1100); + let free = FULL_DECK & !(board | hm); + let cs: Vec = cards_in(free).collect(); + for i in 0..cs.len() { + for j in i + 1..cs.len() { + combos.push(([cs[i], cs[j]], future_score([cs[i], cs[j]], board, bl, &fut))); + } + } + combos.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap()); + let kept = ((combos.len() as f64 * keep) as usize).max(8); + let range = &combos[..kept]; + + let samples = 220; + let mut wins = 0.0; + for _ in 0..samples { + let o = range[rng.below(range.len() as u32) as usize].0; + let mut b = board; + let mut dead = board | hm | bit(o[0]) | bit(o[1]); + for _ in bl..5 { + let c = rng.draw(dead); + dead |= bit(c); + b |= bit(c); + } + let (x, y) = (evaluate(hm | b), evaluate(bit(o[0]) | bit(o[1]) | b)); + wins += if x > y { 1.0 } else if x == y { 0.5 } else { 0.0 }; + } + let eq = wins / samples as f64; + let multi = 0.05 * (opps - 1) as f64; + let u = unit(mix(h, 99)); + + // Did we take the last preflop raise? (c-bet candidate) + let last_pf_raiser = v + .history + .iter() + .filter(|e| e.street == Street::Preflop && matches!(e.action, Action::RaiseTo(_))) + .last() + .map(|e| e.seat as usize); + let aggressor = last_pf_raiser == Some(v.seat); + + let size = |frac: f64| Action::RaiseTo(st.cur_bet() + (frac * (pot + l.call_amount) as f64).round() as i32); + if !facing { + let value_thr = 0.64 + multi - 0.08 * (style as f64 - 1.0); + if eq >= value_thr { + let f = if eq > 0.88 { if bl == 5 { 1.0 } else { 0.75 } } else { 0.5 }; + return size(f); + } + if aggressor && bl == 3 && opps <= 2 && eq >= 0.40 { + return size(0.33); + } + if (0.26..0.42).contains(&eq) && bl < 5 && u < (if aggressor { 0.30 } else { 0.12 }) * style as f64 { + return size(0.5); + } + return Action::Check; + } + let call = l.call_amount as f64; + let po = call / (pot as f64 + call); + let spr_low = eff as f64 <= 1.2 * (pot as f64); + if eq >= 0.83 + multi && raises <= 1 { + return if spr_low || eq > 0.94 { + Action::RaiseTo(l.max_raise_to) + } else { + Action::RaiseTo(st.cur_bet() * 3) + }; + } + if (0.34..0.46).contains(&eq) && bl < 5 && raises <= 1 && u < 0.07 * style as f64 && !spr_low { + return Action::RaiseTo(st.cur_bet() * 3); + } + if eq >= po + (0.03 + multi) / style as f64 { + Action::Call + } else { + Action::Fold + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::matchrun::play_hand; + use cards::Rng; + use nlhe::Deal; + + #[test] + fn charts_have_expected_widths() { + let t = tables(); + let combos = |r: &[bool; 169]| { + (0..169) + .filter(|&i| r[i]) + .map(|i| if i < 13 { 6 } else if i < 91 { 4 } else { 12 }) + .sum::() as f64 + / 1326.0 + }; + let w: Vec = (0..6).map(|i| combos(&t.rfi[i])).collect(); + assert!((0.14..0.20).contains(&w[2]), "UTG {:?}", w); + assert!((0.18..0.25).contains(&w[3]), "HJ {:?}", w); + assert!((0.24..0.31).contains(&w[4]), "CO {:?}", w); + assert!((0.40..0.48).contains(&w[5]), "BTN {:?}", w); + // AA is the best hand, 72o among the worst. + assert!(t.pct[12] < 0.01 && t.pct[cards::preflop_class(cards::card(5, 0), cards::card(0, 1))] > 0.9); + } + + #[test] + fn plays_legal_hands_and_is_deterministic() { + let cfg = GameConfig::new(6); + let f = Chart6::STD; + let mut rng = Rng::new(5); + let mut tot = 0i64; + for k in 0..60 { + let deal = Deal::random(&mut rng); + let mk = || (0..6).map(|s| f.new_player(s, &cfg, k)).collect::>(); + let mut a = mk(); + let o1 = play_hand(&cfg, &deal, &mut a, &mut Rng::new(k), None); + let mut b = mk(); + let o2 = play_hand(&cfg, &deal, &mut b, &mut Rng::new(k + 1000), None); + assert_eq!(o1.payoffs, o2.payoffs, "chart6 must not depend on the random stream"); + assert_eq!(o1.payoffs.iter().sum::(), 0); + tot += o1.actions as i64; + } + assert!(tot > 60 * 3); + } +} diff --git a/arena/bench/src/compact.rs b/arena/bench/src/compact.rs new file mode 100644 index 00000000..37dd4f2b --- /dev/null +++ b/arena/bench/src/compact.rs @@ -0,0 +1,74 @@ +//! `CompactPolicy`: a [`PolicyFactory`] over a `blueprint::compact::Compact` file (mmap). +//! +//! It *is* a [`BlueprintPolicy`] (same abstract-history tracking, pseudo-harmonic translation +//! and check/call fallback for unknown infosets) whose lookups go to the compact file instead +//! of a `Store`. Probabilities are the file's u8 quantisation (error < 1/255 per action). + +use crate::bp::{BlueprintPolicy, Source}; +use crate::policy::{Player, PolicyFactory}; +use blueprint::compact::Compact; +use blueprint::trainer::Bucketer; +use nlhe::abstraction::BetSizing; +use nlhe::GameConfig; +use std::path::Path; +use std::sync::Arc; + +impl Source for Compact { + #[inline] + fn probs(&self, hist: u64, bucket: u32, out: &mut [f32]) -> bool { + Compact::probs(self, hist, bucket, out) + } +} + +pub struct CompactPolicy { + inner: BlueprintPolicy, + compact: Arc, +} + +impl CompactPolicy { + pub fn new(name: &str, compact: Arc, bucketer: Arc, sizing: BetSizing) -> Self { + CompactPolicy { inner: BlueprintPolicy::from_source(name, compact.clone(), bucketer, sizing), compact } + } + + pub fn open(path: &Path, bucketer: Arc, sizing: BetSizing) -> Result { + let c = Compact::open(path).map_err(|e| format!("{}: {e}", path.display()))?; + Ok(Self::new(&format!("compact:{}", path.display()), Arc::new(c), bucketer, sizing)) + } + + pub fn with_opts(self, o: nlhe::abstraction::TrackOpts) -> Self { + let CompactPolicy { inner, compact } = self; + CompactPolicy { inner: inner.with_opts(o), compact } + } + pub fn with_translation(self, t: nlhe::abstraction::Translation) -> Self { + let CompactPolicy { inner, compact } = self; + CompactPolicy { inner: inner.with_translation(t), compact } + } + pub fn with_below(self, b: nlhe::abstraction::BelowMenu) -> Self { + let CompactPolicy { inner, compact } = self; + CompactPolicy { inner: inner.with_below(b), compact } + } + pub fn inner(&self) -> &BlueprintPolicy { + &self.inner + } + + pub fn compact(&self) -> &Arc { + &self.compact + } + + /// Fraction of decisions whose infoset was missing from the file (fallback: check/call). + pub fn miss_rate(&self) -> f64 { + self.inner.miss_rate() + } +} + +impl PolicyFactory for CompactPolicy { + fn name(&self) -> String { + self.inner.name() + } + fn report(&self) -> Option { + self.inner.report() + } + fn new_player(&self, seat: usize, cfg: &GameConfig, seed: u64) -> Box { + self.inner.new_player(seat, cfg, seed) + } +} diff --git a/arena/bench/src/ext.rs b/arena/bench/src/ext.rs new file mode 100644 index 00000000..21d3d027 --- /dev/null +++ b/arena/bench/src/ext.rs @@ -0,0 +1,456 @@ +//! Subprocess bridge for third-party bots (typically Python): JSON lines over stdin/stdout. +//! +//! One request line per decision, one response line back. The protocol is *stateless* +//! (every request carries the full public hand history), so a pool of long-lived worker +//! processes can be shared by all rayon threads and all seats. +//! +//! Request (one JSON object per line): +//! ```json +//! {"id":7,"seat":2,"players":6,"hole":["As","Kd"],"board":["2c","7h","9d"],"street":1, +//! "pot":450,"sb":50,"bb":100,"stacks":[..remaining..],"street_bets":[..],"contrib":[..], +//! "folded":[..bool..],"allin":[..bool..],"cur_bet":150,"call_amount":150, +//! "legal":{"fold":true,"check":false,"raise":true,"min_raise_to":300,"max_raise_to":9850}, +//! "history":[{"seat":2,"street":0,"kind":"raise","to":250}, ...]} +//! ``` +//! Response: `{"id":7,"action":"fold|check|call|raise|allin","to":N}` (`to` = total committed on +//! the street, only for raise). The bridge makes the answer legal: raise sizes are clamped to +//! the legal range, a raise that is impossible becomes a call/check, a fold of a free check +//! becomes a check, and a malformed answer, a timeout or a dead process becomes the fallback +//! (check if free, else fold) and is counted in [`PolicyFactory::report`]. +//! +//! Stateful bots (bot name ending in `+obs`): every finished hand is also appended, once per hand, to a +//! shared log as an `observe` line (`{"observe":1,"players":6,"sb":..,"bb":..,"button":5,"holes":[..], +//! "board":[..],"showdown":bool,"history":[..],"who":[entrant per seat]}`, no reply expected). Each +//! worker replays the whole log, in order, before answering its next request, so every worker +//! process holds the same opponent model and the run behaves like one persistent bot. Requests +//! also carry `"who"` (entrant index per seat) so a bot can tell identical opponents apart from itself. + +use crate::policy::{Dist, Event, Player, PolicyFactory, View}; +use cards::{card_str, Card}; +use nlhe::{Action, GameConfig}; +use serde_json::{json, Value}; +use std::io::{BufRead, BufReader, Write}; +use std::process::{Child, ChildStdin, Command, Stdio}; +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; +use std::sync::mpsc::{channel, Receiver, RecvTimeoutError}; +use std::sync::{Arc, Mutex}; +use nlhe::Deal; +use std::time::Duration; + +pub fn event_json(e: &Event) -> Value { + let (kind, to) = match e.action { + Action::Fold => ("fold", 0), + Action::Check => ("check", 0), + Action::Call => ("call", 0), + Action::RaiseTo(t) => ("raise", t), + }; + json!({"seat": e.seat, "street": e.street.idx(), "kind": kind, "to": to}) +} + +pub fn request_json(id: u64, v: &View, hole: [Card; 2]) -> Value { + let st = v.state; + let n = st.num_players(); + let l = st.legal(); + json!({ + "id": id, + "seat": v.seat, + "players": n, + "hole": [card_str(hole[0]), card_str(hole[1])], + "board": v.board.iter().map(|&c| card_str(c)).collect::>(), + "street": st.street().idx(), + "pot": st.pot(), + "sb": v.cfg.small_blind, + "bb": v.cfg.big_blind, + "stacks": (0..n).map(|s| st.stack(s)).collect::>(), + "street_bets": (0..n).map(|s| st.street_bet(s)).collect::>(), + "contrib": (0..n).map(|s| st.contributed(s)).collect::>(), + "folded": (0..n).map(|s| st.is_folded(s)).collect::>(), + "allin": (0..n).map(|s| st.is_all_in(s)).collect::>(), + "cur_bet": st.cur_bet(), + "call_amount": l.call_amount, + "legal": {"fold": l.can_fold, "check": l.can_check, "raise": l.can_raise, + "min_raise_to": l.min_raise_to, "max_raise_to": l.max_raise_to}, + "history": v.history.iter().map(event_json).collect::>(), + }) +} + +fn fallback(v: &View) -> Action { + if v.state.legal().can_check { + Action::Check + } else { + Action::Fold + } +} + +/// Parse and legalize a response; `None` if malformed (caller falls back). +pub fn parse_response(line: &str, id: u64, v: &View) -> Option { + let r: Value = serde_json::from_str(line).ok()?; + if r.get("id")?.as_u64()? != id { + return None; + } + let l = v.state.legal(); + let raise = |to: i64| { + if l.can_raise { + Action::RaiseTo((to.clamp(l.min_raise_to as i64, l.max_raise_to as i64)) as i32) + } else if l.can_check { + Action::Check + } else { + Action::Call + } + }; + Some(match r.get("action")?.as_str()? { + "fold" => { + if l.can_check { + Action::Check + } else { + Action::Fold + } + } + "check" | "call" => { + if l.can_check { + Action::Check + } else { + Action::Call + } + } + "raise" | "bet" => raise(r.get("to").and_then(|x| x.as_f64()).unwrap_or(0.0).round() as i64), + "allin" => raise(i64::MAX / 4), + _ => return None, + }) +} + +/// Extra time allowed for a worker's first answer (interpreter + model load on a busy box). +const DEFAULT_STARTUP_GRACE: Duration = Duration::from_secs(180); + +struct Worker { + /// Next entry of the shared observation log this worker has not been sent yet. + cursor: usize, + /// False until the first answer: the first request gets `STARTUP_GRACE` extra (model load). + warm: bool, + child: Child, + stdin: ChildStdin, + rx: Receiver, +} + +impl Worker { + fn spawn(cmd: &[String]) -> std::io::Result { + let mut child = Command::new(&cmd[0]) + .args(&cmd[1..]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn()?; + let stdin = child.stdin.take().unwrap(); + let out = child.stdout.take().unwrap(); + let (tx, rx) = channel(); + std::thread::spawn(move || { + for line in BufReader::new(out).lines() { + match line { + Ok(l) => { + if tx.send(l).is_err() { + break; + } + } + Err(_) => break, + } + } + }); + Ok(Worker { cursor: 0, warm: false, child, stdin, rx }) + } + fn ask(&mut self, pre: &[Arc], req: &Value, id: u64, timeout: Duration, grace: Duration) -> Option { + for l in pre { + writeln!(self.stdin, "{l}").ok()?; + } + self.cursor += pre.len(); + writeln!(self.stdin, "{req}").ok()?; + self.stdin.flush().ok()?; + let timeout = if self.warm { timeout } else { timeout + grace }; + let deadline = std::time::Instant::now() + timeout; + loop { + let left = deadline.saturating_duration_since(std::time::Instant::now()); + match self.rx.recv_timeout(left) { + Ok(l) => { + // Skip stale answers to earlier (timed-out) ids. + if serde_json::from_str::(&l).ok().and_then(|v| v.get("id")?.as_u64()) == Some(id) { + self.warm = true; + return Some(l); + } + } + Err(RecvTimeoutError::Timeout) | Err(RecvTimeoutError::Disconnected) => return None, + } + } + } +} + +impl Drop for Worker { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +pub struct ExtBot { + name: String, + cmd: Vec, + timeout: Duration, + grace: Duration, + pool: Vec>>, + next: AtomicU64, + ids: AtomicU64, + requests: AtomicU64, + fallbacks: AtomicU64, + restarts: AtomicU64, + /// Feed finished hands to the workers (bot name ends in `+obs`). + observe: bool, + log: Mutex>>, +} + +impl ExtBot { + /// `cmd` = program + args, e.g. `["python3","-I","bot.py","model.pt"]`. + pub fn new(name: &str, cmd: Vec, workers: usize, timeout: Duration) -> Arc { + assert!(!cmd.is_empty() && workers > 0); + Arc::new(ExtBot { + name: name.to_string(), + cmd, + timeout, + grace: DEFAULT_STARTUP_GRACE, + pool: (0..workers).map(|_| Mutex::new(None)).collect(), + next: AtomicU64::new(0), + ids: AtomicU64::new(1), + requests: AtomicU64::new(0), + fallbacks: AtomicU64::new(0), + restarts: AtomicU64::new(0), + observe: name.ends_with("+obs"), + log: Mutex::new(Vec::new()), + }) + } + + /// Extra time for a worker's first answer (default 180 s: interpreter + model load). + pub fn with_grace(self: Arc, grace: Duration) -> Arc { + let mut me = Arc::try_unwrap(self).ok().expect("unshared"); + me.grace = grace; + Arc::new(me) + } + + /// As a bench `PolicyFactory`. + pub fn factory(self: Arc) -> Arc { + Arc::new(self) + } + + fn decide(&self, v: &View, hole: [Card; 2], who: &[usize]) -> Action { + let id = self.ids.fetch_add(1, Relaxed); + self.requests.fetch_add(1, Relaxed); + let mut req = request_json(id, v, hole); + if !who.is_empty() { + req["who"] = json!(who); + } + let n = self.pool.len(); + let start = self.next.fetch_add(1, Relaxed) as usize % n; + let mut guard = (0..n) + .find_map(|k| self.pool[(start + k) % n].try_lock().ok()) + .unwrap_or_else(|| self.pool[start].lock().unwrap()); + if guard.is_none() { + *guard = Worker::spawn(&self.cmd).ok(); + } + let pre: Vec> = match (self.observe, guard.as_ref()) { + (true, Some(w)) => { + let l = self.log.lock().unwrap(); + l[w.cursor.min(l.len())..].to_vec() + } + _ => Vec::new(), + }; + let answer = guard.as_mut().and_then(|w| w.ask(&pre, &req, id, self.timeout, self.grace)); + match answer.as_deref().and_then(|l| parse_response(l, id, v)) { + Some(a) => a, + None => { + self.fallbacks.fetch_add(1, Relaxed); + // No answer at all (hung/dead worker): drop it (kills it); the next call respawns. + // A well-formed id'd but invalid answer (e.g. an error object) keeps the worker. + if answer.is_none() && guard.take().is_some() { + self.restarts.fetch_add(1, Relaxed); + } + fallback(v) + } + } + } +} + +impl PolicyFactory for Arc { + fn name(&self) -> String { + self.name.clone() + } + fn new_player(&self, seat: usize, cfg: &GameConfig, _seed: u64) -> Box { + Box::new(ExtPlayer { bot: self.clone(), seat, who: Vec::new(), blinds: (cfg.small_blind, cfg.big_blind), stacks: cfg.stacks.unwrap_or([cfg.stack; nlhe::MAX_PLAYERS])[..cfg.players].to_vec() }) + } + fn new_player_ctx(&self, seat: usize, cfg: &GameConfig, _seed: u64, who: &[usize]) -> Box { + Box::new(ExtPlayer { bot: self.clone(), seat, who: who.to_vec(), blinds: (cfg.small_blind, cfg.big_blind), stacks: cfg.stacks.unwrap_or([cfg.stack; nlhe::MAX_PLAYERS])[..cfg.players].to_vec() }) + } + fn report(&self) -> Option { + Some( + json!({"bot": self.name, "requests": self.requests.load(Relaxed), + "fallbacks": self.fallbacks.load(Relaxed), "restarts": self.restarts.load(Relaxed)}) + .to_string(), + ) + } +} + +struct ExtPlayer { + bot: Arc, + seat: usize, + who: Vec, + blinds: (i32, i32), + stacks: Vec, +} + +impl Player for ExtPlayer { + fn dist(&mut self, v: &View, hole: [Card; 2]) -> Dist { + Dist::pure(self.bot.decide(v, hole, &self.who)) + } + fn exposes_probs(&self) -> bool { + false + } + fn act(&mut self, v: &View, hole: [Card; 2], _u: f64) -> Action { + self.bot.decide(v, hole, &self.who) + } + fn finish(&mut self, deal: &Deal, hist: &[Event], end: &nlhe::State) { + if !self.bot.observe || self.who.is_empty() { + return; + } + // One observation per hand: only the lowest seat held by this bot's entrant reports it. + let mine = self.who[self.seat]; + if (0..self.seat).any(|s| self.who[s] == mine) { + return; + } + let n = self.who.len(); + let showdown = end.showdown(); + let blen = if showdown { 5 } else { hist.last().map_or(0, |e| e.street.board_len()) }; + let msg = json!({ + "observe": 1, "players": n, "stacks": self.stacks, "sb": self.blinds.0, "bb": self.blinds.1, "button": n - 1, + "holes": (0..n).map(|s| [card_str(deal.holes[s][0]), card_str(deal.holes[s][1])]).collect::>(), + "board": deal.board[..blen].iter().map(|&c| card_str(c)).collect::>(), + "showdown": showdown, + "history": hist.iter().map(event_json).collect::>(), + "who": self.who, + }); + self.bot.log.lock().unwrap().push(Arc::from(msg.to_string())); + } +} + +/// Resolve an external/rule-bot spec (`chart6`, `chart6-loose`, `chart6-tight`, `rlcard:`, +/// `ext:=`) to a factory; `None` if the spec is not one of these. `py`/`dir` locate the +/// python interpreter and the `arena/adapters` directory for `rlcard:`. +pub fn parse_external(base: &str, py: &str, dir: &str, workers: usize, timeout: Duration) -> Option, String>> { + if let Some(c) = crate::chart::Chart6::by_name(base) { + return Some(Ok(Arc::new(c))); + } + if let Some(model) = base.strip_prefix("rlcard:") { + let cmd = vec![py.to_string(), "-I".into(), format!("{dir}/rlcard_bot_server.py"), model.to_string()]; + return Some(Ok(ExtBot::new("rlcard", cmd, workers, timeout).factory())); + } + if let Some(json) = base.strip_prefix("ext:") { + return Some((|| { + let (name, arr) = json.split_once('=').ok_or("ext:=")?; + let cmd: Vec = serde_json::from_str(arr).map_err(|e| format!("bad ext argv: {e}"))?; + Ok(ExtBot::new(name, cmd, workers, timeout).factory()) + })()); + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::matchrun::play_hand; + use cards::Rng; + use nlhe::{Deal, State}; + + fn view_fixture<'a>(cfg: &'a GameConfig, st: &'a State, hist: &'a [Event]) -> View<'a> { + View { cfg, state: st, board: &[], history: hist, seat: st.to_act().unwrap() } + } + + #[test] + fn request_has_full_public_state() { + let cfg = GameConfig::new(6); + let st = State::new(&cfg); + let v = view_fixture(&cfg, &st, &[]); + let r = request_json(3, &v, [cards::parse_card("As").unwrap(), cards::parse_card("Kd").unwrap()]); + assert_eq!(r["seat"], 2); + assert_eq!(r["hole"], json!(["As", "Kd"])); + assert_eq!(r["pot"], 150); + assert_eq!(r["call_amount"], 100); + assert_eq!(r["legal"]["fold"], true); + assert_eq!(r["stacks"].as_array().unwrap().len(), 6); + assert_eq!(r["contrib"][1], 100); + } + + #[test] + fn responses_are_legalized() { + let cfg = GameConfig::new(6); + let st = State::new(&cfg); + let v = view_fixture(&cfg, &st, &[]); + let l = st.legal(); + // raise below min -> min; above max -> max + assert_eq!(parse_response(r#"{"id":1,"action":"raise","to":5}"#, 1, &v), Some(Action::RaiseTo(l.min_raise_to))); + assert_eq!(parse_response(r#"{"id":1,"action":"raise","to":99999999}"#, 1, &v), Some(Action::RaiseTo(l.max_raise_to))); + assert_eq!(parse_response(r#"{"id":1,"action":"allin"}"#, 1, &v), Some(Action::RaiseTo(l.max_raise_to))); + assert_eq!(parse_response(r#"{"id":1,"action":"check"}"#, 1, &v), Some(Action::Call)); // cannot check facing the BB + assert_eq!(parse_response(r#"{"id":2,"action":"call"}"#, 1, &v), None); // wrong id + assert_eq!(parse_response("garbage", 1, &v), None); + assert_eq!(parse_response(r#"{"id":1,"action":"dance"}"#, 1, &v), None); + // free check: fold becomes check + let mut st2 = st; + for a in [Action::Call, Action::Call, Action::Call, Action::Call, Action::Call] { + st2.apply(a); + } + let v2 = view_fixture(&cfg, &st2, &[]); + assert!(st2.legal().can_check); + assert_eq!(parse_response(r#"{"id":1,"action":"fold"}"#, 1, &v2), Some(Action::Check)); + } + + const PY_ECHO: &str = "import sys,json\nfor l in sys.stdin:\n r=json.loads(l)\n print(json.dumps({'id':r['id'],'action':'raise','to':r['cur_bet']*3}),flush=True)\n"; + + fn py(code: &str) -> Vec { + vec!["python3".into(), "-I".into(), "-c".into(), code.into()] + } + + #[test] + fn subprocess_roundtrip_plays_full_hands() { + let bot = ExtBot::new("pyraiser", py(PY_ECHO), 2, Duration::from_secs(5)).with_grace(Duration::ZERO); + let cfg = GameConfig::new(6); + let mut rng = Rng::new(1); + for k in 0..10 { + let deal = Deal::random(&mut rng); + let mut ps: Vec<_> = (0..6).map(|s| bot.new_player(s, &cfg, k)).collect(); + let o = play_hand(&cfg, &deal, &mut ps, &mut Rng::new(k), None); + assert_eq!(o.payoffs.iter().sum::(), 0); + } + let rep: Value = serde_json::from_str(&bot.report().unwrap()).unwrap(); + assert!(rep["requests"].as_u64().unwrap() > 10); + assert_eq!(rep["fallbacks"], 0); + } + + #[test] + fn timeout_and_crash_fall_back_safely() { + // Never answers: every decision times out -> fallback (fold/check); hands still finish. + let hung = ExtBot::new("hung", py("import sys,time\nfor l in sys.stdin:\n time.sleep(60)\n"), 1, Duration::from_millis(150)).with_grace(Duration::ZERO); + // Crashes on first request. + let crash = ExtBot::new("crash", py("import sys\nsys.stdin.readline()\nsys.exit(3)\n"), 1, Duration::from_millis(500)); + let cfg = GameConfig::new(6); + for bot in [hung, crash] { + let deal = Deal::random(&mut Rng::new(9)); + let mut ps: Vec<_> = (0..6).map(|s| bot.new_player(s, &cfg, 0)).collect(); + let o = play_hand(&cfg, &deal, &mut ps, &mut Rng::new(0), None); + assert_eq!(o.payoffs.iter().sum::(), 0); + let rep: Value = serde_json::from_str(&bot.report().unwrap()).unwrap(); + assert!(rep["fallbacks"].as_u64().unwrap() >= 1, "{rep}"); + } + } + #[test] + fn parse_external_specs() { + let t = Duration::from_secs(1); + assert!(parse_external("chart6-tight", "python3", "x", 1, t).unwrap().is_ok()); + assert!(parse_external("tag", "python3", "x", 1, t).is_none()); + assert!(parse_external("ext:a", "python3", "x", 1, t).unwrap().is_err()); + assert!(parse_external("ext:a=[\"python3\"]", "python3", "x", 1, t).unwrap().is_ok()); + } +} diff --git a/arena/bench/src/lbr.rs b/arena/bench/src/lbr.rs new file mode 100644 index 00000000..7d49febd --- /dev/null +++ b/arena/bench/src/lbr.rs @@ -0,0 +1,445 @@ +//! Local Best Response (Lisý & Bowling 2017) against any exposing, forkable policy. +//! +//! The LBR player tracks each opponent's range by Bayes: after every opponent decision the +//! reach weight of each of the 1326 hole pairs is multiplied by the policy's probability of +//! that action with those cards (`Player::dist` queried for hypothetical holes). At its own +//! decisions it evaluates {fold, call/check, raise 0.5 pot, raise 1 pot, all-in} by Monte +//! Carlo over opponent holes drawn from the posterior and board run-outs, assuming that after +//! the action all remaining live players check/call down to showdown. Opponent responses to a +//! raise use the policy's own fold probability for the sampled hole (computed on a forked +//! player, sequentially for multiple opponents; a re-raise is treated as a call). The chosen +//! action is actually played and the real chip winnings are measured, so the reported +//! mbb/game is a genuine lower bound on the target's exploitability (heads-up) -- LBR is +//! a weak exploiter, so it understates it. +//! +//! `Mode::Hu` (2 players): LBR sits in each seat on every deal. `Mode::Profile` (n players): +//! LBR sits in each seat against n-1 copies of the policy. The profile variant measures +//! exploitability of the policy *profile* by one deviator and is NOT an equilibrium-gap bound +//! for n > 2 players. + +use crate::mix; +use crate::policy::{Event, Player, PolicyFactory, View}; +use crate::stats::{Acc, Est}; +use cards::{all_holes, bit, evaluate, hole_index, mask_of, Card, Rng, FULL_DECK}; +use nlhe::{Action, Deal, GameConfig, State, Step, MAX_PLAYERS}; +use rayon::prelude::*; +use std::sync::Arc; + +#[derive(Clone, Debug)] +pub struct LbrConfig { + /// Monte Carlo samples per decision. + pub samples: usize, + /// Raise sizes as pot fractions (all-in is always added). + pub fracs: Vec, +} + +impl Default for LbrConfig { + fn default() -> Self { + LbrConfig { + samples: 300, + fracs: vec![0.5, 1.0], + } + } +} + +#[derive(Clone, Debug)] +pub struct LbrReport { + pub name: String, + pub lbr: Est, + pub by_seat: Vec, + pub deals: u64, +} + +impl std::fmt::Display for LbrReport { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, "LBR vs {:<22} {} mbb/g (seats: ", self.name, self.lbr)?; + for s in &self.by_seat { + write!(f, "{:+.0} ", s.mbb)?; + } + write!(f, ")") + } +} + +/// Gross fractional-chop pot shares given per-seat totals, live mask and ranks. +fn settle( + n: usize, + totals: &[i32; MAX_PLAYERS], + live: u8, + ranks: &[u32; MAX_PLAYERS], +) -> [f64; MAX_PLAYERS] { + let mut out = [0.0; MAX_PLAYERS]; + let mut prev = 0; + loop { + let Some(lv) = (0..n) + .filter(|&i| live >> i & 1 != 0 && totals[i] > prev) + .map(|i| totals[i]) + .min() + else { + break; + }; + let pot: i32 = (0..n) + .map(|i| totals[i].min(lv) - totals[i].min(prev)) + .sum(); + let elig: Vec = (0..n) + .filter(|&i| live >> i & 1 != 0 && totals[i] >= lv) + .collect(); + let best = elig.iter().map(|&i| ranks[i]).max().unwrap(); + let w: Vec = elig.into_iter().filter(|&i| ranks[i] == best).collect(); + for &i in &w { + out[i] += pot as f64 / w.len() as f64; + } + prev = lv; + } + out +} + +/// Cumulative distribution over hole indices (zero weight on dead cards). +fn cum_weights(w: &[f32], dead: u64) -> Vec { + let hs = all_holes(); + let mut acc = 0.0; + hs.iter() + .enumerate() + .map(|(i, h)| { + if bit(h[0]) & dead == 0 && bit(h[1]) & dead == 0 { + acc += w[i] as f64; + } + acc + }) + .collect() +} + +fn sample_hole(cum: &[f64], rng: &mut Rng) -> Option<[Card; 2]> { + let total = *cum.last().unwrap(); + if total <= 0.0 { + return None; + } + let x = rng.f64() * total; + let i = cum.partition_point(|&c| c <= x).min(cum.len() - 1); + Some(all_holes()[i]) +} + +struct Option_ { + action: Action, + /// For raises: per chained opponent seat, fold probability by hole index. + fold: Vec<(usize, Vec)>, +} + +#[allow(clippy::too_many_arguments)] +fn decide( + cfg: &GameConfig, + cfgl: &LbrConfig, + st: &State, + me: usize, + my_hole: [Card; 2], + board: &[Card], + hist: &[Event], + players: &[Option>], + w: &[Vec], + rng: &mut Rng, +) -> Action { + let n = cfg.players; + let l = st.legal(); + let passive = if l.can_check { + Action::Check + } else { + Action::Call + }; + let mut opts: Vec = Vec::new(); + if l.can_fold { + opts.push(Option_ { + action: Action::Fold, + fold: vec![], + }); + } + opts.push(Option_ { + action: passive, + fold: vec![], + }); + if l.can_raise { + let mut tos: Vec = cfgl + .fracs + .iter() + .map(|f| { + (st.cur_bet() + (f * (st.pot() + l.call_amount) as f32).round() as i32) + .clamp(l.min_raise_to, l.max_raise_to) + }) + .collect(); + tos.push(l.max_raise_to); + tos.sort_unstable(); + tos.dedup(); + for to in tos { + let a = Action::RaiseTo(to); + // Opponent fold probabilities on forks, chaining calls through the round. + let mut forks: Vec>> = players + .iter() + .map(|p| { + p.as_ref() + .map(|p| p.fork().expect("LBR target must support fork()")) + }) + .collect(); + let mut h2 = hist.to_vec(); + let mut s2 = *st; + let street = st.street(); + let mut act = a; + let mut actor = me; + let mut fold = Vec::new(); + loop { + let pre = s2; + h2.push(Event { + seat: actor as u8, + street: s2.street(), + action: act, + }); + let step = s2.apply(act); + for f in forks.iter_mut().flatten() { + f.observe(&pre, actor, act); + } + if step != Step::Continue { + break; + } + let j = s2.to_act().unwrap(); + if j == me { + break; + } + let view = View { + cfg, + state: &s2, + board, + history: &h2, + seat: j, + }; + let mut fp = vec![0f32; 1326]; + for (i, hc) in all_holes().iter().enumerate() { + if (bit(hc[0]) | bit(hc[1])) + & (mask_of(board) | bit(my_hole[0]) | bit(my_hole[1])) + == 0 + { + fp[i] = forks[j] + .as_mut() + .unwrap() + .dist(&view, *hc) + .prob_of(Action::Fold) as f32; + } + } + fold.push((j, fp)); + actor = j; + act = Action::Call; + if s2.street() != street { + break; + } + } + opts.push(Option_ { action: a, fold }); + } + } + + // Monte Carlo evaluation with common samples across options. + let dead0 = mask_of(board) | bit(my_hole[0]) | bit(my_hole[1]); + let opp: Vec = (0..n).filter(|&j| j != me && !st.is_folded(j)).collect(); + let cums: Vec> = opp.iter().map(|&j| cum_weights(&w[j], dead0)).collect(); + let mut ev = vec![0.0f64; opts.len()]; + let mut got = 0usize; + let totals0: [i32; MAX_PLAYERS] = + std::array::from_fn(|i| if i < n { st.contributed(i) } else { 0 }); + let live0 = (0..n) + .filter(|&i| !st.is_folded(i)) + .fold(0u8, |m, i| m | 1 << i); + for _ in 0..cfgl.samples { + let mut dead = dead0; + let mut holes = [[0u8; 2]; MAX_PLAYERS]; + holes[me] = my_hole; + let mut ok = true; + for (k, &j) in opp.iter().enumerate() { + let mut tries = 0; + loop { + match sample_hole(&cums[k], rng) { + Some(h) if bit(h[0]) & dead == 0 && bit(h[1]) & dead == 0 => { + holes[j] = h; + dead |= bit(h[0]) | bit(h[1]); + break; + } + _ => { + tries += 1; + if tries > 30 { + ok = false; + break; + } + } + } + } + if !ok { + break; + } + } + if !ok { + continue; + } + let mut run = mask_of(board); + for _ in 0..5 - board.len() { + run |= bit(rng.draw(dead | run)); + } + let mut ranks = [0u32; MAX_PLAYERS]; + for i in 0..n { + if live0 >> i & 1 != 0 { + ranks[i] = evaluate(bit(holes[i][0]) | bit(holes[i][1]) | run); + } + } + for (oi, o) in opts.iter().enumerate() { + let mut totals = totals0; + let mut live = live0; + let v = match o.action { + Action::Fold => -(totals0[me] as f64), + Action::Check | Action::Call => { + totals[me] += l.call_amount; + settle(n, &totals, live, &ranks)[me] - totals[me] as f64 + } + Action::RaiseTo(to) => { + totals[me] += to - st.street_bet(me); + for (j, fp) in &o.fold { + if rng.f32() < fp[hole_index(holes[*j][0], holes[*j][1])] { + live &= !(1 << j); + } else { + totals[*j] += (to - st.street_bet(*j)).min(st.stack(*j)).max(0); + } + } + if live.count_ones() == 1 { + totals.iter().take(n).sum::() as f64 - totals[me] as f64 + } else { + settle(n, &totals, live, &ranks)[me] - totals[me] as f64 + } + } + }; + ev[oi] += v; + } + got += 1; + } + if got == 0 { + return passive; + } + let best = (0..opts.len()).fold(0, |b, i| if ev[i] > ev[b] + 1e-9 { i } else { b }); + // Prefer the passive option on exact ties (index of passive is 0 or 1). + let pi = opts.iter().position(|o| o.action == passive).unwrap(); + if ev[best] <= ev[pi] + 1e-9 { + return passive; + } + opts[best].action +} + +/// Play one hand with LBR in `me` against `target` copies elsewhere; returns LBR's payoff. +pub fn lbr_hand( + cfg: &GameConfig, + cfgl: &LbrConfig, + target: &dyn PolicyFactory, + deal: &Deal, + me: usize, + seed: u64, +) -> i32 { + let n = cfg.players; + let mut rng = Rng::new(seed); + let mut players: Vec>> = (0..n) + .map(|s| (s != me).then(|| target.new_player(s, cfg, mix(seed, s as u64)))) + .collect(); + assert!( + players.iter().flatten().all(|p| p.exposes_probs()), + "LBR target must expose probabilities" + ); + let mut w: Vec> = vec![vec![1.0; 1326]; n]; + let mut st = State::new(cfg); + let mut hist: Vec = Vec::new(); + let mut len = 0; + let holes_all = all_holes(); + while !st.is_terminal() { + let seat = st.to_act().unwrap(); + let board = &deal.board[..len]; + let action = if seat == me { + decide( + cfg, + cfgl, + &st, + me, + deal.holes[me], + board, + &hist, + &players, + &w, + &mut rng, + ) + } else { + let view = View { + cfg, + state: &st, + board, + history: &hist, + seat, + }; + let p = players[seat].as_mut().unwrap(); + let d = p.dist(&view, deal.holes[seat]); + let a = d.action(d.sample(rng.f64())); + let dead = mask_of(board) | bit(deal.holes[me][0]) | bit(deal.holes[me][1]); + for (i, hc) in holes_all.iter().enumerate() { + if (bit(hc[0]) | bit(hc[1])) & dead == 0 { + w[seat][i] *= p.dist(&view, *hc).prob_of(a) as f32; + } + } + a + }; + let pre = st; + let street = st.street(); + let step = st.apply(action); + hist.push(Event { + seat: seat as u8, + street, + action, + }); + for p in players.iter_mut().flatten() { + p.observe(&pre, seat, action); + } + let reveal = |to: usize, players: &mut Vec>>, len: &mut usize| { + *len = to; + for p in players.iter_mut().flatten() { + p.observe_board(&deal.board[..to]); + } + }; + match step { + Step::NewStreet(s) => reveal(s.board_len(), &mut players, &mut len), + Step::Terminal if st.showdown() => reveal(5, &mut players, &mut len), + _ => {} + } + } + st.payoffs(deal)[me] +} + +/// Run LBR over `deals` random deals, with LBR in every seat on every deal. +pub fn run_lbr( + cfg: &GameConfig, + cfgl: &LbrConfig, + target: Arc, + deals: u64, + seed: u64, +) -> LbrReport { + let n = cfg.players; + let res: Vec> = (0..deals) + .into_par_iter() + .map(|d| { + let ds = mix(seed, d); + let deal = Deal::random(&mut Rng::new(mix(ds, 1))); + (0..n) + .map(|me| lbr_hand(cfg, cfgl, &*target, &deal, me, mix(ds, 10 + me as u64))) + .collect() + }) + .collect(); + let bb = cfg.big_blind as f64; + let (mut all, mut seat) = (Acc::default(), vec![Acc::default(); n]); + for r in &res { + all.add(r.iter().sum::() as f64 / n as f64); + for (s, &x) in r.iter().enumerate() { + seat[s].add(x as f64); + } + } + let _ = FULL_DECK; + LbrReport { + name: target.name(), + lbr: Est::from_chips(&all, bb), + by_seat: seat.iter().map(|a| Est::from_chips(a, bb)).collect(), + deals, + } +} diff --git a/arena/bench/src/lib.rs b/arena/bench/src/lib.rs new file mode 100644 index 00000000..351584b0 --- /dev/null +++ b/arena/bench/src/lib.rs @@ -0,0 +1,38 @@ +//! Evaluation harness for the Pluribus reproduction. +//! +//! - [`policy`]: `Policy`/`Player` abstraction (per-hand stateful players built by a factory). +//! - [`builtin`]: the gauntlet opponents (Random, Station, Nit, TAG, LAG, Maniac). +//! - [`chart`]: `chart6`, a deterministic 6-max chart + pot-odds rule bot. +//! - [`ext`]: JSON-lines subprocess bridge for third-party (Python) bots. +//! - [`bp`]: `BlueprintPolicy` (store + bucketer + sizing, with action translation) and the +//! biased continuation-strategy wrapper (fold x5 / call x5 / raise x5). +//! - [`matchrun`]: seeded, rayon-parallel duplicate matches with mbb/game statistics. +//! - [`aivat`]: AIVAT variance reduction with pluggable [`aivat::ValueEstimator`]. +//! - [`lbr`]: Local Best Response (heads-up bound, 6-max profile variant). +//! - [`slumbot`]: heads-up Slumbot client/parser on the nlhe engine. +//! +//! Seeding rule: every random stream is seeded per item (deal index, hand, seat) via +//! [`mix`], never per rayon thread, so results are reproducible regardless of scheduling. + +pub mod aivat; +pub mod bp; +pub mod builtin; +pub mod chart; +pub mod compact; +pub mod ext; +pub mod lbr; +pub mod matchrun; +pub mod policy; +pub mod probe; +pub mod slumbot; +pub mod stats; + +/// Deterministic 64-bit mixer for deriving per-item seeds. +pub fn mix(a: u64, b: u64) -> u64 { + let mut z = a ^ b + .wrapping_mul(0x9E37_79B9_7F4A_7C15) + .wrapping_add(0xD1B5_4A32_D192_ED03); + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) +} diff --git a/arena/bench/src/main.rs b/arena/bench/src/main.rs new file mode 100644 index 00000000..6d99952e --- /dev/null +++ b/arena/bench/src/main.rs @@ -0,0 +1,290 @@ +//! `bench` CLI: gauntlet / match / matrix / lbr / slumbot / mkbp. +//! +//! Policy specs: `random|station|nit|tag|lag|maniac`, `compact:` (PLCP1, same +//! `--bucketer`/`--sizing`), `bp:` (uses +//! `--bucketer`/`--sizing`, default coarse/tiny), `chart6`, `rlcard:`, +//! `ext:=`, with optional `+fold5|+call5|+raise5`. + +use bench::bp::*; +use bench::builtin::{all_builtins, builtin}; +use bench::lbr::{run_lbr, LbrConfig}; +use bench::matchrun::*; +use bench::policy::PolicyFactory; +use bench::slumbot; +use nlhe::GameConfig; +use std::collections::HashMap; +use std::sync::Arc; + +struct Args(HashMap); +impl Args { + fn get(&self, k: &str, d: &str) -> String { + self.0.get(k).cloned().unwrap_or(d.to_string()) + } + fn num(&self, k: &str, d: T) -> T { + self.0.get(k).and_then(|v| v.parse().ok()).unwrap_or(d) + } + fn flag(&self, k: &str) -> bool { + self.0.contains_key(k) + } +} + +fn parse_spec(spec: &str, a: &Args) -> Result, String> { + let mut parts = spec.split('+'); + let base = parts.next().unwrap(); + let mut p: Arc = if base.starts_with("probe:") { + bench::probe::parse(base)? + } else if let Some(path) = base.strip_prefix("bp:") { + Arc::new( + BlueprintPolicy::from_file( + std::path::Path::new(path), + &a.get("bucketer", "coarse"), + &a.get("sizing", "tiny"), + a.num("capacity", 1usize << 26), + )? + .with_opts(track_opts(a)?), + ) + } else if let Some(path) = base.strip_prefix("compact:") { + let b = bucketer_by_name(&a.get("bucketer", "coarse")).ok_or("unknown bucketer")?; + let sz = sizing_by_name(&a.get("sizing", "tiny")).ok_or("unknown sizing")?; + Arc::new(bench::compact::CompactPolicy::open(std::path::Path::new(path), b, sz)?.with_opts(track_opts(a)?)) + } else if let Some(c) = bench::chart::Chart6::by_name(base) { + Arc::new(c) + } else if let Some(model) = base.strip_prefix("rlcard:") { + // RLCard DQN via the Python bridge. --py / --ext-dir override the dev-box defaults. + let home = std::env::var("HOME").unwrap_or_default(); + let py = a.get("py", &format!("{home}/extbots/rlcard-env/venv/bin/python")); + let dir = a.get("ext-dir", "arena/adapters"); + let cmd = vec![py, "-I".into(), format!("{dir}/rlcard_bot_server.py"), model.to_string()]; + bench::ext::ExtBot::new("rlcard", cmd, a.num("ext-workers", 8usize), std::time::Duration::from_millis(a.num("ext-timeout-ms", 5000u64))).factory() + } else if let Some(json) = base.strip_prefix("ext:") { + // ext:=, e.g. ext:mybot=["python3","-I","bot.py"] + let (name, arr) = json.split_once('=').ok_or("ext:=")?; + let cmd: Vec = serde_json::from_str(arr).map_err(|e| format!("bad ext argv: {e}"))?; + bench::ext::ExtBot::new(name, cmd, a.num("ext-workers", 8usize), std::time::Duration::from_millis(a.num("ext-timeout-ms", 5000u64))).factory() + } else { + builtin(base).ok_or(format!("unknown policy {base}"))? + }; + for suf in parts { + let bias = match suf { + "fold5" => Bias::Fold, + "call5" => Bias::Call, + "raise5" => Bias::Raise, + _ => return Err(format!("unknown suffix {suf}")), + }; + p = Arc::new(Biased::new(p, bias)); + } + Ok(p) +} + +/// `--translation det|random`, `--below check|smallest`, `--legacy` (pre-fix: no shadow state). +fn track_opts(a: &Args) -> Result { + use nlhe::abstraction::{BelowMenu, TrackOpts, Translation}; + if a.flag("legacy") { + return Ok(TrackOpts::LEGACY); + } + let mut o = if a.flag("pre-sync-fix") { TrackOpts::PRE_SYNC_FIX } else { TrackOpts::default() }; + match a.get("translation", "det").as_str() { + "det" => o.translation = Translation::Deterministic, + "random" => o.translation = Translation::Random, + x => return Err(format!("unknown --translation {x}")), + } + match a.get("below", "default").as_str() { + "default" => {} + "check" => o.below = BelowMenu::Check, + "smallest" => o.below = BelowMenu::Smallest, + x => return Err(format!("unknown --below {x}")), + } + if let Some(v) = a.0.get("allin-snap") { + o.allin_snap = v.parse().map_err(|_| "bad --allin-snap")?; + } + Ok(o) +} + +fn aivat_mode(a: &Args) -> AivatMode { + match a.get("aivat", "full").as_str() { + "off" => AivatMode::Off, + "cards" => AivatMode::CardsOnly, + _ => AivatMode::Full, + } +} + +fn hero_match( + cfg: GameConfig, + hero: Arc, + field: Arc, + a: &Args, +) -> MatchReport { + let mut spec = MatchSpec::new( + cfg, + vec![hero, field], + Seatings::hero_vs_field(cfg.players), + a.num("deals", 2000), + a.num("seed", 1), + ); + spec.aivat = aivat_mode(a); + spec.crn = !a.flag("no-crn"); + let r = run_match(&spec); + for p in spec.entrants.iter() { + if let Some(rep) = p.report() { + eprintln!("report {}: {rep}", p.name()); + } + } + r +} + +fn main() { + let argv: Vec = std::env::args().collect(); + let cmd = argv.get(1).cloned().unwrap_or_default(); + let mut m = HashMap::new(); + let mut i = 2; + while i < argv.len() { + let k = argv[i].trim_start_matches("--").to_string(); + if i + 1 < argv.len() && !argv[i + 1].starts_with("--") { + m.insert(k, argv[i + 1].clone()); + i += 2; + } else { + m.insert(k, String::new()); + i += 1; + } + } + let a = Args(m); + if let Err(e) = run(&cmd, &a) { + eprintln!("error: {e}"); + std::process::exit(1); + } +} + +fn run(cmd: &str, a: &Args) -> Result<(), String> { + match cmd { + "gauntlet" => { + let hero = parse_spec(&a.get("hero", "tag"), a)?; + for players in [6usize, 2] { + println!( + "== {} vs each built-in, {players}-max (hero rotates through every seat) ==", + hero.name() + ); + for f in all_builtins() { + let r = hero_match(GameConfig::new(players), hero.clone(), f.clone(), a); + let e = &r.entrants[0]; + print!(" vs {:<8} raw {}", f.name(), e.raw); + if let Some(av) = &e.aivat { + print!(" aivat {av} var-ratio {:.1}x", e.var_ratio_hand.unwrap()); + } + println!(); + } + } + } + "match" => { + let (x, y) = ( + parse_spec(&a.get("a", "tag"), a)?, + parse_spec(&a.get("b", "random"), a)?, + ); + let players: usize = a.num("players", 2); + hero_match(GameConfig::new(players), x, y, a).print(); + } + "matrix" => { + let bs = all_builtins(); + for players in [6usize, 2] { + println!("\n### {players}-max: row hero vs {} copies of column (mbb/game, AIVAT, 95% CI)\n", players - 1); + print!("| hero \\ field |"); + bs.iter().for_each(|b| print!(" {} |", b.name())); + println!("\n|---|{}", "---|".repeat(bs.len())); + let mut ratios = Vec::new(); + for h in &bs { + print!("| {} |", h.name()); + for f in &bs { + if h.name() == f.name() { + print!(" - |"); + continue; + } + let r = hero_match(GameConfig::new(players), h.clone(), f.clone(), a); + let e = &r.entrants[0]; + let est = e.aivat.unwrap_or(e.raw); + print!(" {} |", est); + ratios.push(e.var_ratio_hand.unwrap_or(1.0)); + } + println!(); + } + let mean = ratios.iter().sum::() / ratios.len().max(1) as f64; + println!( + "\nmean per-hand variance ratio raw/AIVAT: {mean:.1}x (min {:.1}, max {:.1})", + ratios.iter().cloned().fold(f64::MAX, f64::min), + ratios.iter().cloned().fold(0.0, f64::max) + ); + } + } + "table" => { + // Mixed table: --hero SPEC --field "specA,specB,..." (up to 5 distinct opponents, + // seated cyclically: entrant 0 = hero, then the field in order; every rotation is + // played on every deal). With a single field spec it is hero vs 5 copies. + let hero = parse_spec(&a.get("hero", "tag"), a)?; + let specs: Vec = a.get("field", "tag").split(',').map(str::to_string).collect(); + let players: usize = a.num("players", 6); + let mut entrants = vec![hero]; + for sp in &specs { + entrants.push(parse_spec(sp, a)?); + } + let base: Vec = if specs.len() == 1 { + std::iter::once(0).chain(std::iter::repeat(1).take(players - 1)).collect() + } else { + assert_eq!(specs.len(), players - 1, "--field needs {} specs or 1", players - 1); + (0..players).collect() + }; + let cfg = GameConfig::new(players); + let mut spec = MatchSpec::new(cfg, entrants, Seatings::rotations(&base), a.num("deals", 2000), a.num("seed", 1)); + spec.aivat = aivat_mode(a); + spec.crn = !a.flag("no-crn"); + let r = run_match(&spec); + for p in spec.entrants.iter() { + if let Some(rep) = p.report() { + eprintln!("report {}: {rep}", p.name()); + } + } + r.print(); + } + "lbr" => { + let p = parse_spec(&a.get("policy", "tag"), a)?; + let cfg = GameConfig::new(a.num("players", 2)); + let lc = LbrConfig { + samples: a.num("samples", 300), + ..Default::default() + }; + println!( + "{}", + run_lbr(&cfg, &lc, p, a.num("deals", 500), a.num("seed", 1)) + ); + } + "slumbot" => { + let p = parse_spec(&a.get("policy", "tag"), a)?; + let client = slumbot::SlumbotClient::new(a.get("host", "https://slumbot.com")); + let token = a.0.get("token").cloned().filter(|t| !t.is_empty()); + let opts = slumbot::LiveOpts { pace_ms: a.num("pace-ms", 300), log: a.0.get("log").map(std::path::PathBuf::from) }; + let r = slumbot::play_live(&client, &*p, a.num("hands", 100), token, a.num("seed", 1), &opts)?; + println!( + "{} hands: {} chips, raw {} mbb/hand ({:.1} bb/100), luck-adjusted {} mbb/hand ({:.1} bb/100), token {:?}", + r.hands, + r.total_chips, + r.mbb, + r.mbb.mbb / 10.0, + r.mbb_adj, + r.mbb_adj.mbb / 10.0, + r.token + ); + } + "mkbp" => { + let players = a.num("players", 2); + let bp = train_toy(players, a.num("iters", 60_000), a.num("seed", 1)); + let out = a.get("out", "toy.bp"); + blueprint::io::save(bp.store(), std::path::Path::new(&out)) + .map_err(|e| e.to_string())?; + println!( + "saved {} infosets to {out} (bucketer coarse, sizing tiny)", + bp.store().sequences() + ); + } + _ => { + println!("usage: bench [--hero tag] [--a X --b Y] [--players N] [--deals N] [--seed S] [--aivat full|cards|off] [--bucketer coarse] [--sizing tiny]"); + } + } + Ok(()) +} diff --git a/arena/bench/src/matchrun.rs b/arena/bench/src/matchrun.rs new file mode 100644 index 00000000..1af999cc --- /dev/null +++ b/arena/bench/src/matchrun.rs @@ -0,0 +1,388 @@ +//! Seeded, parallel duplicate matches. +//! +//! For every sampled deal the same cards are replayed under each seating (a seat -> entrant +//! assignment). `Seatings::rotations(base)` cyclically shifts a base assignment so each +//! entrant plays every seat the base puts it in, e.g. `hero_vs_field(6)` puts the hero in +//! each of the 6 seats once against 5 copies of the field policy. +//! +//! Randomness: all streams are seeded per deal (`mix(seed, deal_index)`), so results do not +//! depend on rayon scheduling. With `crn` the k-th decision of a hand uses the k-th uniform of +//! a per-deal stream, identical across seatings (common random numbers). +//! +//! Statistics: an entrant's payoff in one seating is the mean over the seats it occupies. +//! The independent sample is the deal (mean over seatings). Everything is in mbb/game. + +use crate::aivat::{EquityEstimator, Mode, Scratch, Tracker, ValueEstimator}; +use crate::mix; +use crate::policy::{Event, PolicyFactory, View}; +use crate::stats::{Acc, Est}; +use cards::Rng; +use nlhe::{Deal, GameConfig, State, Step, MAX_PLAYERS}; +use rayon::prelude::*; +use std::sync::Arc; + +pub struct Seatings(pub Vec>); + +impl Seatings { + /// All cyclic rotations of `base` (seat -> entrant). + pub fn rotations(base: &[usize]) -> Seatings { + let n = base.len(); + Seatings( + (0..n) + .map(|r| (0..n).map(|s| base[(s + r) % n]).collect()) + .collect(), + ) + } + /// Entrant 0 (hero) in seat 0, entrant 1 (field) everywhere else, rotated. + pub fn hero_vs_field(players: usize) -> Seatings { + let mut base = vec![1; players]; + base[0] = 0; + Self::rotations(&base) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum AivatMode { + Off, + Full, + CardsOnly, +} + +pub struct MatchSpec { + pub cfg: GameConfig, + pub entrants: Vec>, + pub seatings: Seatings, + pub deals: u64, + pub seed: u64, + pub crn: bool, + pub aivat: AivatMode, + pub estimator: Arc, +} + +impl MatchSpec { + pub fn new( + cfg: GameConfig, + entrants: Vec>, + seatings: Seatings, + deals: u64, + seed: u64, + ) -> Self { + MatchSpec { + cfg, + entrants, + seatings, + deals, + seed, + crn: true, + aivat: AivatMode::Off, + estimator: Arc::new(EquityEstimator::default()), + } + } +} + +pub struct HandOutcome { + /// Integer chip payoffs per seat. + pub payoffs: [i32; MAX_PLAYERS], + /// AIVAT-corrected payoffs (fractional-chop `u` + corrections), if tracked. + pub aivat: Option<[f64; MAX_PLAYERS]>, + pub actions: usize, +} + +/// Play one hand with fresh players; `crn` supplies one uniform per decision. +pub fn play_hand( + cfg: &GameConfig, + deal: &Deal, + players: &mut [Box], + crn: &mut Rng, + mut tracker: Option, +) -> HandOutcome { + let mut st = State::new(cfg); + let mut len = 0usize; + let mut hist: Vec = Vec::with_capacity(32); + if let Some(t) = tracker.as_mut() { + t.start(&st); + } + let mut actions = 0; + while !st.is_terminal() { + let seat = st.to_act().unwrap(); + let u = crn.f64(); + let view = View { + cfg, + state: &st, + board: &deal.board[..len], + history: &hist, + seat, + }; + let hole = deal.holes[seat]; + let action = if players[seat].exposes_probs() { + let d = players[seat].dist(&view, hole); + let i = d.sample(u); + if let Some(t) = tracker.as_mut() { + t.decision(&st, len, &d, i); + } + d.action(i) + } else { + players[seat].act(&view, hole, u) + }; + let pre = st; + let street = st.street(); + let step = st.apply(action); + hist.push(Event { + seat: seat as u8, + street, + action, + }); + actions += 1; + for p in players.iter_mut() { + p.observe(&pre, seat, action); + } + let reveal = |to: usize, + st: &State, + len: &mut usize, + tracker: &mut Option, + players: &mut [Box]| { + if let Some(t) = tracker.as_mut() { + t.chance(st, *len, to); + } + *len = to; + for p in players.iter_mut() { + p.observe_board(&deal.board[..to]); + } + }; + match step { + Step::Continue => {} + Step::NewStreet(s) => reveal(s.board_len(), &st, &mut len, &mut tracker, players), + Step::Terminal => { + if st.showdown() { + while len < 5 { + let to = if len == 0 { 3 } else { len + 1 }; + reveal(to, &st, &mut len, &mut tracker, players); + } + } + } + } + } + for p in players.iter_mut() { + p.finish(deal, &hist, &st); + } + let payoffs = st.payoffs(deal); + let aivat = tracker.map(|t| { + // Fractional-chop realised value: the estimator at the terminal node (exact). + let mut u = [0.0; MAX_PLAYERS]; + let q = crate::aivat::Query { + state: &st, + holes: &t.deal.holes, + board: &t.deal.board[..len.max(if st.showdown() { 5 } else { 0 })], + }; + let v = t.est.value(&q, t.sc); + for i in 0..MAX_PLAYERS { + u[i] = if st.showdown() || st.live_count() == 1 { + v[i] + } else { + payoffs[i] as f64 + }; + u[i] += t.corr[i]; + } + u + }); + HandOutcome { + payoffs, + aivat, + actions, + } +} + +#[derive(Clone, Debug, Default)] +pub struct SeatReport { + pub raw: Est, + pub aivat: Option, +} + +#[derive(Clone, Debug)] +pub struct EntrantReport { + pub name: String, + pub raw: Est, + pub aivat: Option, + /// Indexed by seat; `None` if the entrant never sat there. + pub by_seat: Vec>, + /// Var(raw)/Var(aivat) per single hand (entrant-seat payoff) and per deal (duplicate mean). + pub var_ratio_hand: Option, + pub var_ratio_deal: Option, +} + +#[derive(Clone, Debug)] +pub struct MatchReport { + pub entrants: Vec, + pub deals: u64, + pub hands: u64, +} + +struct RotOut { + raw: [f64; MAX_PLAYERS], + av: Option<[f64; MAX_PLAYERS]>, +} + +#[derive(Clone, Default)] +struct EntAcc { + raw_deal: Acc, + av_deal: Acc, + raw_hand: Acc, + av_hand: Acc, + seat_raw: Vec, + seat_av: Vec, +} + +fn play_deal(spec: &MatchSpec, d: u64) -> Vec { + let dseed = mix(spec.seed, d); + let deal = Deal::random(&mut Rng::new(mix(dseed, 1))); + let mut sc = Scratch::new(mix(dseed, 2)); + let n = spec.cfg.players; + let mut out = Vec::new(); + for (r, seating) in spec.seatings.0.iter().enumerate() { + let mut players: Vec<_> = (0..n) + .map(|s| { + spec.entrants[seating[s]].new_player_ctx( + s, + &spec.cfg, + mix(dseed, 100 + (r * MAX_PLAYERS + s) as u64), + &seating[..n], + ) + }) + .collect(); + let mut crn = Rng::new(mix(dseed, if spec.crn { 3 } else { 1000 + r as u64 })); + let tracker = match spec.aivat { + AivatMode::Off => None, + m => Some(Tracker::new( + &*spec.estimator, + &mut sc, + if m == AivatMode::Full { + Mode::Full + } else { + Mode::CardsOnly + }, + deal, + )), + }; + let h = play_hand(&spec.cfg, &deal, &mut players, &mut crn, tracker); + let mut raw = [0.0; MAX_PLAYERS]; + for s in 0..n { + raw[s] = h.payoffs[s] as f64; + } + out.push(RotOut { raw, av: h.aivat }); + } + out +} + +pub fn run_match(spec: &MatchSpec) -> MatchReport { + let ne = spec.entrants.len(); + let n = spec.cfg.players; + let bb = spec.cfg.big_blind as f64; + let use_av = spec.aivat != AivatMode::Off; + let mut accs: Vec = (0..ne) + .map(|_| EntAcc { + seat_raw: vec![Acc::default(); n], + seat_av: vec![Acc::default(); n], + ..Default::default() + }) + .collect(); + let chunk = 1024u64; + let mut start = 0; + while start < spec.deals { + let end = (start + chunk).min(spec.deals); + let res: Vec> = (start..end) + .into_par_iter() + .map(|d| play_deal(spec, d)) + .collect(); + for rots in &res { + for (e, acc) in accs.iter_mut().enumerate() { + let (mut sr, mut sa, mut k) = (0.0, 0.0, 0.0); + let mut seat_sum = vec![(0.0, 0.0, 0u32); n]; + for (r, ro) in rots.iter().enumerate() { + let seating = &spec.seatings.0[r]; + let seats: Vec = (0..n).filter(|&s| seating[s] == e).collect(); + if seats.is_empty() { + continue; + } + let m = seats.len() as f64; + let raw = seats.iter().map(|&s| ro.raw[s]).sum::() / m; + let av = ro + .av + .map(|a| seats.iter().map(|&s| a[s]).sum::() / m) + .unwrap_or(raw); + acc.raw_hand.add(raw); + acc.av_hand.add(av); + sr += raw; + sa += av; + k += 1.0; + for &s in &seats { + let x = &mut seat_sum[s]; + x.0 += ro.raw[s]; + x.1 += ro.av.map(|a| a[s]).unwrap_or(ro.raw[s]); + x.2 += 1; + } + } + if k > 0.0 { + acc.raw_deal.add(sr / k); + acc.av_deal.add(sa / k); + } + for s in 0..n { + let x = seat_sum[s]; + if x.2 > 0 { + acc.seat_raw[s].add(x.0 / x.2 as f64); + acc.seat_av[s].add(x.1 / x.2 as f64); + } + } + } + } + start = end; + } + let entrants = accs + .iter() + .enumerate() + .map(|(e, a)| EntrantReport { + name: spec.entrants[e].name(), + raw: Est::from_chips(&a.raw_deal, bb), + aivat: use_av.then(|| Est::from_chips(&a.av_deal, bb)), + by_seat: (0..n) + .map(|s| { + (a.seat_raw[s].n > 0).then(|| SeatReport { + raw: Est::from_chips(&a.seat_raw[s], bb), + aivat: use_av.then(|| Est::from_chips(&a.seat_av[s], bb)), + }) + }) + .collect(), + var_ratio_hand: use_av.then(|| a.raw_hand.var() / a.av_hand.var().max(1e-12)), + var_ratio_deal: use_av.then(|| a.raw_deal.var() / a.av_deal.var().max(1e-12)), + }) + .collect(); + MatchReport { + entrants, + deals: spec.deals, + hands: spec.deals * spec.seatings.0.len() as u64, + } +} + +impl MatchReport { + pub fn print(&self) { + println!("{} deals, {} hands", self.deals, self.hands); + for e in &self.entrants { + print!(" {:<22} raw {} mbb/g", e.name, e.raw); + if let (Some(a), Some(vr)) = (&e.aivat, e.var_ratio_hand) { + print!( + " aivat {a} var-ratio hand {vr:.1}x deal {:.1}x", + e.var_ratio_deal.unwrap_or(0.0) + ); + } + println!(); + let seats: Vec = e + .by_seat + .iter() + .map(|s| { + s.as_ref() + .map_or("-".into(), |s| format!("{:+.0}", s.raw.mbb)) + }) + .collect(); + println!(" by seat (SB,BB,..): {}", seats.join(" ")); + } + } +} diff --git a/arena/bench/src/policy.rs b/arena/bench/src/policy.rs new file mode 100644 index 00000000..dfbb8925 --- /dev/null +++ b/arena/bench/src/policy.rs @@ -0,0 +1,155 @@ +//! The `Policy` abstraction. +//! +//! A [`PolicyFactory`] creates one [`Player`] per seat per hand. The harness feeds the player +//! every action (`observe`) and every board reveal (`observe_board`), then asks for a +//! distribution over concrete legal actions with [`Player::dist`], given a public [`View`] +//! and the player's private cards. +//! +//! Contract for players that expose probabilities (`exposes_probs() == true`, needed for +//! AIVAT and as LBR targets): `dist` is a pure function of (public history observed so far, +//! hole cards) and may be queried for *any* hole cards, not just the real ones (this is the +//! "range strategy"). Players that sample hidden randomness must return `false`. +//! `fork` clones a player mid-hand (needed by LBR for hypothetical responses). + +use cards::Card; +use nlhe::abstraction::MAX_ACTIONS; +use nlhe::{Action, GameConfig, State, Street}; + +/// One public action in real chips (`RaiseTo` = total committed on that street). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Event { + pub seat: u8, + pub street: Street, + pub action: Action, +} + +/// Public game information at a decision. +pub struct View<'a> { + pub cfg: &'a GameConfig, + pub state: &'a State, + /// Board cards visible now (0, 3, 4 or 5). + pub board: &'a [Card], + pub history: &'a [Event], + /// Acting seat. + pub seat: usize, +} + +/// Probability distribution over concrete legal actions. +#[derive(Clone, Copy, Debug)] +pub struct Dist { + n: usize, + acts: [Action; MAX_ACTIONS], + p: [f32; MAX_ACTIONS], +} + +impl Default for Dist { + fn default() -> Self { + Self::new() + } +} + +impl Dist { + pub fn new() -> Dist { + Dist { + n: 0, + acts: [Action::Fold; MAX_ACTIONS], + p: [0.0; MAX_ACTIONS], + } + } + pub fn pure(a: Action) -> Dist { + let mut d = Dist::new(); + d.push(a, 1.0); + d + } + /// Merges probability into an existing identical action. + pub fn push(&mut self, a: Action, p: f32) { + if let Some(i) = (0..self.n).find(|&i| self.acts[i] == a) { + self.p[i] += p; + } else { + assert!(self.n < MAX_ACTIONS); + self.acts[self.n] = a; + self.p[self.n] = p; + self.n += 1; + } + } + pub fn len(&self) -> usize { + self.n + } + pub fn is_empty(&self) -> bool { + self.n == 0 + } + pub fn action(&self, i: usize) -> Action { + self.acts[i] + } + pub fn actions(&self) -> &[Action] { + &self.acts[..self.n] + } + fn total(&self) -> f64 { + self.p[..self.n].iter().map(|&x| x as f64).sum() + } + /// Normalised probability of entry `i` (the exact law used by `sample`). + pub fn prob(&self, i: usize) -> f64 { + let t = self.total(); + if t <= 0.0 { + 1.0 / self.n as f64 + } else { + self.p[i] as f64 / t + } + } + /// Probability of a specific action (0 if absent). + pub fn prob_of(&self, a: Action) -> f64 { + (0..self.n) + .find(|&i| self.acts[i] == a) + .map_or(0.0, |i| self.prob(i)) + } + /// Map a uniform `u` in [0,1) to an entry index. + pub fn sample(&self, u: f64) -> usize { + let mut x = u * 1.0; + for i in 0..self.n { + let p = self.prob(i); + if x < p { + return i; + } + x -= p; + } + self.n - 1 + } +} + +pub trait Player: Send { + fn observe(&mut self, _pre: &State, _seat: usize, _a: Action) {} + fn observe_board(&mut self, _board: &[Card]) {} + fn dist(&mut self, view: &View, hole: [Card; 2]) -> Dist; + /// Choose an action given a uniform draw `u`. Override only for non-exposing players. + fn act(&mut self, view: &View, hole: [Card; 2], u: f64) -> Action { + let d = self.dist(view, hole); + d.action(d.sample(u)) + } + fn exposes_probs(&self) -> bool { + true + } + fn fork(&self) -> Option> { + None + } + /// Diagnostic about the last `dist`/`act` (e.g. "timeout: blueprint fallback"); read-once. + fn take_note(&mut self) -> Option { + None + } + /// Called once per player when the hand is over (full deal, public history, terminal state). + /// Stateful external bots use it to learn about opponents. + fn finish(&mut self, _deal: &nlhe::Deal, _hist: &[Event], _end: &State) {} +} + +pub trait PolicyFactory: Send + Sync { + fn name(&self) -> String; + /// `seed` is unique per (hand, seat); use it for any hidden randomness. + fn new_player(&self, seat: usize, cfg: &GameConfig, seed: u64) -> Box; + /// As `new_player`, also told who sits where (`who[s]` = entrant index at seat `s`). + fn new_player_ctx(&self, seat: usize, cfg: &GameConfig, seed: u64, _who: &[usize]) -> Box { + self.new_player(seat, cfg, seed) + } + /// Optional end-of-run diagnostics (one line of JSON) printed by the `bench` CLI. + fn report(&self) -> Option { + None + } +} diff --git a/arena/bench/src/probe.rs b/arena/bench/src/probe.rs new file mode 100644 index 00000000..83eb73fd --- /dev/null +++ b/arena/bench/src/probe.rs @@ -0,0 +1,161 @@ +//! Scripted "probe" opponents for diagnosing action-translation weaknesses. A probe never +//! folds and never plays for value: it just makes one kind of off-menu bet, so any large loss +//! of a blueprint against it is a translation/handling artefact, not poker skill. +//! +//! Spec (`probe:key=value,...`, all optional): +//! * `pre=X` open-raise preflop to X big blinds when unopened (`pre=min` = min-raise, +//! `pre=allin`); otherwise limp/call. `pp=P` probability of doing so (default 1). +//! * `bet=F` postflop, when checked to, bet F x pot (clamped to the legal range); `bp=P` +//! probability (default 1); `street=flop|turn|river|all` restricts it (default all). +//! * `raise=F` postflop, when facing exactly one bet, raise by F x (pot after calling); +//! `rp=P` probability (default 1). +//! * `pre3=X` preflop facing exactly one raise: re-raise to X x the current bet (`p3=P`). +//! Everything else is check/call. + +use crate::policy::{Dist, Player, PolicyFactory, View}; +use cards::Card; +use nlhe::{Action, GameConfig, State, Street}; +use std::sync::Arc; + +#[derive(Clone, Debug)] +pub struct Probe { + spec: String, + /// Preflop open size in big blinds: `-1` = min-raise, `f64::INFINITY` = all-in, `0` = off. + pub pre: f64, + pub pp: f64, + pub pre3: f64, + pub p3: f64, + pub bet: f64, + pub bp: f64, + /// Bitmask of streets (1 = flop, 2 = turn, 4 = river) where `bet` applies. + pub bet_streets: u8, + pub raise: f64, + pub rp: f64, +} + +pub fn parse(spec: &str) -> Result, String> { + let body = spec.strip_prefix("probe:").ok_or("not a probe spec")?; + let mut p = Probe { + spec: spec.to_string(), + pre: 0.0, + pp: 1.0, + pre3: 0.0, + p3: 1.0, + bet: 0.0, + bp: 1.0, + bet_streets: 7, + raise: 0.0, + rp: 1.0, + }; + for kv in body.split(',').filter(|s| !s.is_empty()) { + let (k, v) = kv.split_once('=').ok_or(format!("bad probe field {kv}"))?; + let num = || v.parse::().map_err(|e| format!("{kv}: {e}")); + match k { + "pre" => { + p.pre = match v { + "min" => -1.0, + "allin" => f64::INFINITY, + _ => num()?, + } + } + "pp" => p.pp = num()?, + "pre3" => { + p.pre3 = match v { + "allin" => f64::INFINITY, + _ => num()?, + } + } + "p3" => p.p3 = num()?, + "bet" => p.bet = num()?, + "bp" => p.bp = num()?, + "street" => { + p.bet_streets = match v { + "flop" => 1, + "turn" => 2, + "river" => 4, + "all" => 7, + _ => return Err(format!("unknown street {v}")), + } + } + "raise" => p.raise = num()?, + "rp" => p.rp = num()?, + _ => return Err(format!("unknown probe field {k}")), + } + } + Ok(Arc::new(p)) +} + +impl PolicyFactory for Probe { + fn name(&self) -> String { + self.spec.clone() + } + fn new_player(&self, _seat: usize, _cfg: &GameConfig, _seed: u64) -> Box { + Box::new(self.clone()) + } +} + +fn mix(passive: Action, aggressive: Action, p: f64) -> Dist { + if p >= 1.0 { + return Dist::pure(aggressive); + } + let mut d = Dist::new(); + d.push(aggressive, p as f32); + d.push(passive, (1.0 - p) as f32); + d +} + +impl Player for Probe { + fn dist(&mut self, v: &View, _hole: [Card; 2]) -> Dist { + let st: &State = v.state; + let l = st.legal(); + let passive = if l.can_check { Action::Check } else { Action::Call }; + if !l.can_raise { + return Dist::pure(passive); + } + let raises = st.raises_this_street(); + let clamp = |to: f64| Action::RaiseTo((to.round() as i64).clamp(l.min_raise_to as i64, l.max_raise_to as i64) as i32); + let frac_to = |f: f64| { + if f.is_infinite() { + return Action::RaiseTo(l.max_raise_to); + } + clamp(st.cur_bet() as f64 + f * (st.pot() + l.call_amount) as f64) + }; + let bb = v.cfg.big_blind as f64; + match st.street() { + Street::Preflop => { + if raises == 0 && self.pre != 0.0 { + let a = if self.pre < 0.0 { + Action::RaiseTo(l.min_raise_to) + } else if self.pre.is_infinite() { + Action::RaiseTo(l.max_raise_to) + } else { + clamp(self.pre * bb) + }; + return mix(passive, a, self.pp); + } + if raises == 1 && self.pre3 != 0.0 { + let a = if self.pre3.is_infinite() { + Action::RaiseTo(l.max_raise_to) + } else { + clamp(self.pre3 * st.cur_bet() as f64) + }; + return mix(passive, a, self.p3); + } + Dist::pure(passive) + } + s => { + let bit = 1u8 << (s.idx() - 1); + if raises == 0 && self.bet > 0.0 && self.bet_streets & bit != 0 { + return mix(passive, frac_to(self.bet), self.bp); + } + if raises == 1 && self.raise > 0.0 { + return mix(passive, frac_to(self.raise), self.rp); + } + Dist::pure(passive) + } + } + } + fn fork(&self) -> Option> { + Some(Box::new(self.clone())) + } +} diff --git a/arena/bench/src/slumbot.rs b/arena/bench/src/slumbot.rs new file mode 100644 index 00000000..9fb2ded9 --- /dev/null +++ b/arena/bench/src/slumbot.rs @@ -0,0 +1,478 @@ +//! Heads-up Slumbot adapter on the nlhe engine (200 bb stacks = 20,000 chips, blinds 50/100). +//! +//! API: POST `{host}/slumbot/api/new_hand` and `/act` (`{"token","incr"}`). Action strings: +//! `k` check, `c` call, `f` fold, `bN` bet/raise *to* N chips on the current street, `/` +//! between streets; after an all-in call the remaining streets appear as trailing `/`. +//! +//! Seat convention: Slumbot `client_pos` 0 = big blind, 1 = small blind/button. nlhe heads-up: +//! seat 0 = SB/button (acts first preflop), seat 1 = BB (acts first postflop). Hence +//! `nlhe_seat = 1 - client_pos`. Parsing drives a real `nlhe::State`, so legality (min-raise, +//! stacks) is checked by the engine. + +use crate::mix; +use crate::policy::{Event, PolicyFactory, View}; +use crate::stats::{Acc, Est}; +use cards::{parse_card, Card, Rng}; +use nlhe::{Action, GameConfig, State, Step}; +use serde::{Deserialize, Serialize}; +use serde_json::json; + +pub const STACK: i32 = 20_000; +pub const SMALL_BLIND: i32 = 50; +pub const BIG_BLIND: i32 = 100; + +pub fn game_config() -> GameConfig { + GameConfig { + players: 2, + stack: STACK, + small_blind: SMALL_BLIND, + big_blind: BIG_BLIND, + stacks: None, + ..GameConfig::new(2) + } +} + +pub fn nlhe_seat(client_pos: usize) -> usize { + 1 - client_pos +} + +#[derive(Debug)] +pub struct Parsed { + pub events: Vec, + /// State after all events. + pub state: State, +} + +pub fn parse_actions(s: &str) -> Result { + let cfg = game_config(); + let mut st = State::new(&cfg); + let b = s.as_bytes(); + let (mut i, mut events) = (0, Vec::new()); + while i < b.len() { + if st.is_terminal() { + // Only run-out street separators may follow an all-in call. + if st.showdown() && b[i..].iter().all(|&c| c == b'/') { + break; + } + return Err(format!("action continues after terminal hand at {i}")); + } + let seat = st.to_act().unwrap(); + let l = st.legal(); + let c = b[i] as char; + i += 1; + let action = match c { + 'k' if l.can_check => Action::Check, + 'c' if !l.can_check => Action::Call, + 'f' if l.can_fold => Action::Fold, + 'b' => { + let start = i; + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + } + let t: i32 = s[start..i] + .parse() + .map_err(|_| "bad bet size".to_string())?; + if !l.can_raise || t < l.min_raise_to || t > l.max_raise_to { + return Err(format!( + "illegal bet to {t} (legal {}..{})", + l.min_raise_to, l.max_raise_to + )); + } + Action::RaiseTo(t) + } + c => return Err(format!("illegal action '{c}' at {}", i - 1)), + }; + events.push(Event { + seat: seat as u8, + street: st.street(), + action, + }); + match st.apply(action) { + Step::NewStreet(_) => { + if i < b.len() { + if b[i] != b'/' { + return Err(format!("missing street separator at {i}")); + } + i += 1; + } + } + Step::Terminal if !st.showdown() && i != b.len() => { + return Err("extra characters after fold".into()) + } + _ => {} + } + } + Ok(Parsed { events, state: st }) +} + +/// Canonical action string for an event list (inverse of `parse_actions`). +pub fn format_actions(events: &[Event]) -> String { + let mut st = State::new(&game_config()); + let mut out = String::new(); + let mut last_street = 0; + for e in events { + last_street = st.street().idx(); + out.push_str(&to_incr(e.action)); + match st.apply(e.action) { + Step::NewStreet(_) => out.push('/'), + Step::Terminal if st.showdown() => (last_street..3).for_each(|_| out.push('/')), + _ => {} + } + } + let _ = last_street; + out +} + +/// Slumbot `incr` token for an action. +pub fn to_incr(a: Action) -> String { + match a { + Action::Fold => "f".into(), + Action::Check => "k".into(), + Action::Call => "c".into(), + Action::RaiseTo(t) => format!("b{t}"), + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SlumbotResponse { + #[serde(default)] + pub old_action: String, + #[serde(default)] + pub action: String, + #[serde(default)] + pub client_pos: usize, + #[serde(default)] + pub hole_cards: Vec, + #[serde(default)] + pub board: Vec, + #[serde(default)] + pub bot_hole_cards: Vec, + #[serde(default)] + pub token: Option, + #[serde(default)] + pub winnings: Option, + #[serde(default)] + pub error_msg: Option, +} + +pub struct SlumbotClient { + host: String, +} + +impl Default for SlumbotClient { + fn default() -> Self { + Self::new("https://slumbot.com") + } +} + +impl SlumbotClient { + pub fn new(host: impl Into) -> Self { + Self { host: host.into() } + } + pub fn new_hand(&self, token: Option<&str>) -> Result { + self.post( + "/slumbot/api/new_hand", + token.map_or(json!({}), |t| json!({ "token": t })), + ) + } + pub fn act(&self, token: &str, incr: &str) -> Result { + self.post("/slumbot/api/act", json!({ "token": token, "incr": incr })) + } + fn post(&self, path: &str, body: serde_json::Value) -> Result { + let url = format!("{}{}", self.host.trim_end_matches('/'), path); + let r: SlumbotResponse = ureq::post(&url) + .set("Content-Type", "application/json") + .send_json(body) + .map_err(|e| format!("Slumbot request failed: {e}"))? + .into_json() + .map_err(|e| format!("Slumbot response not JSON: {e}"))?; + match &r.error_msg { + Some(m) => Err(format!("Slumbot error: {m}")), + None => Ok(r), + } + } +} + +fn cards_of(raw: &[String]) -> Result, String> { + raw.iter() + .map(|c| parse_card(c).ok_or(format!("bad card {c}"))) + .collect() +} + +#[derive(Debug)] +pub struct LiveResult { + pub hands: usize, + pub total_chips: i64, + pub mbb: Est, + /// Same, with all-in showdowns replaced by their exact all-in EV ("luck adjusted"; the + /// opponent is not a known strategy, so full AIVAT is impossible, but this removes the + /// run-out variance of every hand that went all-in before the river). + pub mbb_adj: Est, + pub token: Option, +} + +/// Politeness / logging options for [`play_live`]. +#[derive(Clone, Debug, Default)] +pub struct LiveOpts { + /// Minimum milliseconds between two HTTP requests (we also never have two in flight). + pub pace_ms: u64, + /// Append one JSON line per finished hand here. + pub log: Option, +} + +/// Exact (or, preflop, sampled) all-in EV in chips for our side if the hand ended in a +/// showdown with cards still to come after the last betting action; `None` otherwise. +pub fn allin_ev(resp: &SlumbotResponse) -> Option { + use cards::{bit, evaluate, mask_of}; + let parsed = parse_actions(&resp.action).ok()?; + let last = parsed.events.last()?; + if !parsed.state.showdown() || last.street == nlhe::Street::River { + return None; + } + let known = last.street.board_len(); + let board = cards_of(&resp.board).ok()?; + let hole = cards_of(&resp.hole_cards).ok()?; + let opp = cards_of(&resp.bot_hole_cards).ok()?; + if hole.len() != 2 || opp.len() != 2 || board.len() < 5 { + return None; + } + let seat = nlhe_seat(resp.client_pos); + let (contrib, pot) = (parsed.state.contributed(seat) as f64, parsed.state.pot() as f64); + let b0 = mask_of(&board[..known]); + let (hm, om) = (bit(hole[0]) | bit(hole[1]), bit(opp[0]) | bit(opp[1])); + let dead = b0 | hm | om; + let free: Vec = cards::cards_in(cards::FULL_DECK & !dead).collect(); + let need = 5 - known; + let (mut win, mut n) = (0.0, 0.0); + let mut score = |extra: cards::Hand| { + let b = b0 | extra; + let (x, y) = (evaluate(hm | b), evaluate(om | b)); + win += if x > y { 1.0 } else if x == y { 0.5 } else { 0.0 }; + n += 1.0; + }; + match need { + 1 => free.iter().for_each(|&c| score(bit(c))), + 2 => { + for i in 0..free.len() { + for j in i + 1..free.len() { + score(bit(free[i]) | bit(free[j])); + } + } + } + _ => { + let mut rng = Rng::new(0x5EED ^ resp.hole_cards.len() as u64 ^ bit(hole[0])); + for _ in 0..30_000 { + let mut d = dead; + let mut ex = 0; + for _ in 0..need { + let c = rng.draw(d); + d |= bit(c); + ex |= bit(c); + } + score(ex); + } + } + } + Some(win / n * pot - contrib) +} + +/// Play `hands` live hands. Never called by tests. +pub fn play_live( + client: &SlumbotClient, + policy: &dyn PolicyFactory, + hands: usize, + mut token: Option, + seed: u64, + opts: &LiveOpts, +) -> Result { + let cfg = game_config(); + let (mut acc, mut acc_adj, mut total) = (Acc::default(), Acc::default(), 0i64); + let mut last_req = std::time::Instant::now() - std::time::Duration::from_secs(10); + let pace = std::time::Duration::from_millis(opts.pace_ms); + // One request at a time, spaced by `pace`, with a few retries on transient errors. + let mut call = |f: &dyn Fn() -> Result| -> Result { + let mut err = String::new(); + for attempt in 0..5u32 { + let wait = pace.saturating_sub(last_req.elapsed()); + std::thread::sleep(wait); + last_req = std::time::Instant::now(); + match f() { + Ok(r) => return Ok(r), + Err(e) if e.contains("Slumbot error") => return Err(e), + Err(e) => { + err = e; + std::thread::sleep(std::time::Duration::from_secs(2u64 << attempt)); + } + } + } + Err(err) + }; + for h in 0..hands { + let mut resp = call(&|| client.new_hand(token.as_deref()))?; + token = resp.token.clone().or(token); + let mut rng = Rng::new(mix(seed, h as u64)); + let mut player = None; + let (mut fed, mut board_seen) = (0usize, 0usize); + for step in 0..200 { + if let Some(w) = resp.winnings { + total += w; + acc.add(w as f64); + let adj = allin_ev(&resp).unwrap_or(w as f64); + acc_adj.add(adj); + if let Some(path) = &opts.log { + use std::io::Write; + if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(path) { + let _ = writeln!( + f, + "{}", + json!({"hand": h, "client_pos": resp.client_pos, "action": resp.action, + "hole": resp.hole_cards, "bot_hole": resp.bot_hole_cards, + "board": resp.board, "winnings": w, "ev_adj": adj}) + ); + } + } + break; + } + let seat = nlhe_seat(resp.client_pos); + let parsed = parse_actions(&resp.action)?; + if parsed.state.to_act() != Some(seat) { + return Err(format!( + "not our turn: action {:?} client_pos {}", + resp.action, resp.client_pos + )); + } + let hole = cards_of(&resp.hole_cards)?; + let board = cards_of(&resp.board)?; + if hole.len() != 2 { + return Err("expected two hole cards".into()); + } + let p = player + .get_or_insert_with(|| policy.new_player(seat, &cfg, mix(seed, 7 + h as u64))); + let mut mirror = State::new(&cfg); + for (k, e) in parsed.events.iter().enumerate() { + let pre = mirror; + mirror.apply(e.action); + if k >= fed { + p.observe(&pre, e.seat as usize, e.action); + } + } + fed = parsed.events.len(); + if board.len() > board_seen { + p.observe_board(&board); + board_seen = board.len(); + } + let view = View { + cfg: &cfg, + state: &parsed.state, + board: &board, + history: &parsed.events, + seat, + }; + let a = p.act(&view, [hole[0], hole[1]], rng.f64()); + let t = token.clone().ok_or("no token")?; + let incr = to_incr(a); + resp = call(&|| client.act(&t, &incr))?; + token = resp.token.clone().or(token); + if step == 199 { + return Err("hand exceeded action limit".into()); + } + } + } + Ok(LiveResult { + hands, + total_chips: total, + mbb: Est::from_chips(&acc, BIG_BLIND as f64), + mbb_adj: Est::from_chips(&acc_adj, BIG_BLIND as f64), + token, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn roundtrip_recorded_strings() { + for s in [ + "", + "c", + "b300c/kk/kk/kb200f", + "b200c/kk/kk/kb200", + "b20000c///", + "b300c/b900c/kk/kk", + "ck/kk/kk/kk", + "b300c/kb500c/kk/kk", + "cb300b900b3000c/kk/kk/kk", + ] { + let p = parse_actions(s).unwrap_or_else(|e| panic!("{s}: {e}")); + assert_eq!(format_actions(&p.events), s, "roundtrip {s}"); + } + } + + #[test] + fn seat_convention_and_progress() { + // Empty string: SB (slumbot pos 1 = nlhe seat 0) to act. + let p = parse_actions("").unwrap(); + assert_eq!(p.state.to_act(), Some(nlhe_seat(1))); + // SB limps, BB checks -> flop, BB (pos 0 = seat 1) acts first. + let p = parse_actions("ck/").unwrap(); + assert_eq!(p.state.to_act(), Some(nlhe_seat(0))); + assert_eq!(p.state.street(), nlhe::Street::Flop); + // Raise-call preflop then bets. + let p = parse_actions("b300c/kb200").unwrap(); + assert_eq!(p.state.to_act(), Some(nlhe_seat(0))); + assert_eq!(p.state.pot(), 800); + let p = parse_actions("b300f").unwrap(); + assert!(p.state.is_terminal() && !p.state.showdown()); + // All-in call -> showdown with run-out slashes. + let p = parse_actions("b20000c///").unwrap(); + assert!(p.state.showdown()); + let p2 = parse_actions("b20000c").unwrap(); + assert!(p2.state.showdown()); + } + + #[test] + fn allin_ev_preflop_and_flop() { + let mk = |action: &str, board: &[&str], hole: &[&str], bot: &[&str]| SlumbotResponse { + old_action: String::new(), + action: action.into(), + client_pos: 1, + hole_cards: hole.iter().map(|s| s.to_string()).collect(), + board: board.iter().map(|s| s.to_string()).collect(), + bot_hole_cards: bot.iter().map(|s| s.to_string()).collect(), + token: None, + winnings: Some(0), + error_msg: None, + }; + // AA vs KK all-in preflop: ~81.9% -> EV = 0.819 * 40000 - 20000 ~ +12.8k. + let r = mk("b20000c///", &["2c", "7d", "9h", "Js", "Qc"], &["As", "Ah"], &["Kc", "Kd"]); + let ev = allin_ev(&r).unwrap(); + assert!((12_000.0..13_500.0).contains(&ev), "{ev}"); + // River showdown: no adjustment (nothing left to come). + let r = mk("ck/kk/kk/kb100c", &["2c", "7d", "9h", "Js", "Qc"], &["As", "Ah"], &["Kc", "Kd"]); + assert!(allin_ev(&r).is_none()); + // Flop all-in, set vs flush draw: ahead but not certain, EV between -contrib and +pot share. + let r = mk("b300c/b19700c//", &["2c", "7d", "9h", "Js", "Qc"], &["9s", "9d"], &["Ac", "Kc"]); + let ev = allin_ev(&r); + assert!(ev.is_none() || ev.unwrap().abs() <= 20_000.0); + } + + #[test] + fn rejects_illegal_strings() { + for s in [ + "k", + "c/", + "b100", + "b50", + "b30000", + "b300cf", + "b300c/kk/kk/kk/k", + "b300c/c", + "x", + "ckk", + "b300f/", + ] { + assert!(parse_actions(s).is_err(), "{s} should be illegal"); + } + } +} diff --git a/arena/bench/src/stats.rs b/arena/bench/src/stats.rs new file mode 100644 index 00000000..c59b0ea5 --- /dev/null +++ b/arena/bench/src/stats.rs @@ -0,0 +1,66 @@ +//! Running mean/variance and mbb/game reporting. + +#[derive(Clone, Copy, Debug, Default)] +pub struct Acc { + pub n: u64, + pub sum: f64, + pub sumsq: f64, +} + +impl Acc { + pub fn add(&mut self, x: f64) { + self.n += 1; + self.sum += x; + self.sumsq += x * x; + } + pub fn mean(&self) -> f64 { + if self.n == 0 { + 0.0 + } else { + self.sum / self.n as f64 + } + } + /// Unbiased sample variance. + pub fn var(&self) -> f64 { + if self.n < 2 { + return 0.0; + } + let n = self.n as f64; + ((self.sumsq - self.sum * self.sum / n) / (n - 1.0)).max(0.0) + } + pub fn se(&self) -> f64 { + if self.n == 0 { + 0.0 + } else { + (self.var() / self.n as f64).sqrt() + } + } +} + +/// Point estimate in mbb/game (milli big blinds per hand) with standard error. +#[derive(Clone, Copy, Debug, Default)] +pub struct Est { + pub mbb: f64, + pub se: f64, + pub n: u64, +} + +impl Est { + /// `acc` holds chip payoffs; `bb` is the big blind in chips. + pub fn from_chips(acc: &Acc, bb: f64) -> Est { + Est { + mbb: acc.mean() / bb * 1000.0, + se: acc.se() / bb * 1000.0, + n: acc.n, + } + } + pub fn ci95(&self) -> (f64, f64) { + (self.mbb - 1.96 * self.se, self.mbb + 1.96 * self.se) + } +} + +impl std::fmt::Display for Est { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, "{:+.1} ± {:.1}", self.mbb, 1.96 * self.se) + } +} diff --git a/arena/bench/tests/compact.rs b/arena/bench/tests/compact.rs new file mode 100644 index 00000000..f148c210 --- /dev/null +++ b/arena/bench/tests/compact.rs @@ -0,0 +1,124 @@ +//! CompactPolicy must play like BlueprintPolicy over the exported store, within u8 +//! quantisation (every action probability within 1/255). + +use bench::bp::{train_toy, BlueprintPolicy, CoarseBucketer}; +use bench::compact::CompactPolicy; +use bench::policy::{Event, PolicyFactory, View}; +use blueprint::compact::{compact_checkpoint, Compact, CompactOptions}; +use blueprint::{io, snapshot}; +use cards::Rng; +use nlhe::abstraction::BetSizing; +use nlhe::{Deal, GameConfig, State, Step}; +use std::path::PathBuf; +use std::sync::Arc; + +fn tmp(name: &str) -> PathBuf { + std::env::temp_dir().join(format!("bench_compact_{}_{}", std::process::id(), name)) +} + +/// Play `hands` random hands where both policies track the same history; compare their +/// distributions at every decision. Returns (decisions, max |p_a - p_b|, action-set mismatches). +fn compare(a: &dyn PolicyFactory, b: &dyn PolicyFactory, players: usize, hands: u64) -> (u64, f64, u64) { + let cfg = GameConfig::new(players); + let (mut n, mut worst, mut mism) = (0u64, 0f64, 0u64); + for h in 0..hands { + let mut rng = Rng::new(0xC0FFEE ^ h); + let deal = Deal::random(&mut rng); + let mut pa: Vec<_> = (0..players).map(|s| a.new_player(s, &cfg, h)).collect(); + let mut pb: Vec<_> = (0..players).map(|s| b.new_player(s, &cfg, h)).collect(); + let mut st = State::new(&cfg); + let mut len = 0usize; + let mut hist: Vec = Vec::new(); + while !st.is_terminal() { + let seat = st.to_act().unwrap(); + let view = View { cfg: &cfg, state: &st, board: &deal.board[..len], history: &hist, seat }; + let hole = deal.holes[seat]; + let da = pa[seat].dist(&view, hole); + let db = pb[seat].dist(&view, hole); + if da.len() != db.len() { + mism += 1; + } + for i in 0..da.len() { + worst = worst.max((da.prob(i) - db.prob_of(da.action(i))).abs()); + } + n += 1; + let action = da.action(da.sample(rng.f64())); + let pre = st; + let street = st.street(); + let step = st.apply(action); + hist.push(Event { seat: seat as u8, street, action }); + for p in pa.iter_mut().chain(pb.iter_mut()) { + p.observe(&pre, seat, action); + } + let mut reveal = |to: usize, len: &mut usize| { + *len = to; + for p in pa.iter_mut().chain(pb.iter_mut()) { + p.observe_board(&deal.board[..to]); + } + }; + match step { + Step::Continue => {} + Step::NewStreet(s) => reveal(s.board_len(), &mut len), + Step::Terminal => { + if st.showdown() { + while len < 5 { + let to = if len == 0 { 3 } else { len + 1 }; + reveal(to, &mut len); + } + } + } + } + } + } + (n, worst, mism) +} + +fn check(players: usize) { + let bp = train_toy(players, 60_000, 3); + let store = bp.store(); + let ck = tmp(&format!("ck{players}.bin")); + let sums = tmp(&format!("sums{players}.bin")); + let _ = std::fs::remove_file(&sums); + // Two snapshots with a perturbation in between, so snapshot averaging differs from the + // current strategy. + snapshot::accumulate(store, &sums).unwrap(); + let mut r = Rng::new(17); + for (_, slot) in store.entries() { + let a = r.below(slot.n_actions as u32) as usize; + store.add_regret(slot, a, r.below(4000) as f32 - 1000.0); + } + snapshot::accumulate(store, &sums).unwrap(); + io::save(store, &ck).unwrap(); + + for use_sums in [false, true] { + // Reference: the policy over the checkpoint store (exported if snapshots are used). + let reference = io::load(&ck, 0, 0).unwrap(); + if use_sums { + snapshot::export_in_place(&reference, Some(&sums)).unwrap(); + } + let ref_pol = BlueprintPolicy::new("ref", Arc::new(reference), Arc::new(CoarseBucketer), BetSizing::tiny()); + let out = tmp(&format!("c{players}_{use_sums}.plcp")); + let opt = CompactOptions { threads: 2, min_visits: 0, chunk: 4096, group_slots: 1 << 20, part_bytes: 1 << 20, tmp_dir: None }; + let stats = compact_checkpoint(&ck, use_sums.then_some(sums.as_path()), &out, &opt, &|_| {}).unwrap(); + let cp = CompactPolicy::new("compact", Arc::new(Compact::open(&out).unwrap()), Arc::new(CoarseBucketer), BetSizing::tiny()); + let (n, worst, mism) = compare(&ref_pol, &cp, players, 400); + eprintln!("{players}p sums={use_sums}: {n} decisions, max dp {worst:.5}, mismatches {mism}, miss ref {:.4} compact {:.4}, {} infosets {} B", ref_pol.miss_rate(), cp.miss_rate(), stats.infosets_out, stats.bytes_out); + assert!(n > 1000); + assert_eq!(mism, 0); + assert!(worst <= 1.0 / 255.0 + 1e-3, "max prob difference {worst}"); + assert!((ref_pol.miss_rate() - cp.miss_rate()).abs() < 1e-9, "same fallback behaviour"); + let _ = std::fs::remove_file(&out); + } + let _ = std::fs::remove_file(&ck); + let _ = std::fs::remove_file(&sums); +} + +#[test] +fn compact_policy_matches_blueprint_policy_heads_up() { + check(2); +} + +#[test] +fn compact_policy_matches_blueprint_policy_six_max() { + check(6); +} diff --git a/arena/bench/tests/harness.rs b/arena/bench/tests/harness.rs new file mode 100644 index 00000000..bc68b14c --- /dev/null +++ b/arena/bench/tests/harness.rs @@ -0,0 +1,242 @@ +use bench::bp::*; +use bench::builtin::builtin; +use bench::lbr::{run_lbr, LbrConfig}; +use bench::matchrun::*; +use bench::policy::PolicyFactory; +use nlhe::GameConfig; +use std::sync::Arc; + +fn b(n: &str) -> Arc { + builtin(n).unwrap() +} + +fn hero( + players: usize, + h: &str, + f: &str, + deals: u64, + seed: u64, + aivat: AivatMode, + crn: bool, +) -> MatchReport { + let cfg = GameConfig::new(players); + let mut spec = MatchSpec::new( + cfg, + vec![b(h), b(f)], + Seatings::hero_vs_field(players), + deals, + seed, + ); + spec.aivat = aivat; + spec.crn = crn; + run_match(&spec) +} + +#[test] +fn self_match_is_zero() { + for players in [2, 6] { + // Two distinct factory instances of the same policy; independent action streams. + let r = hero(players, "tag", "tag", 6000, 11, AivatMode::Full, false); + let e = &r.entrants[0]; + assert!( + e.raw.mbb.abs() < 3.5 * e.raw.se, + "{players}p raw {} se {}", + e.raw.mbb, + e.raw.se + ); + let a = e.aivat.unwrap(); + assert!( + a.mbb.abs() < 3.5 * a.se.max(1.0), + "{players}p aivat {} se {}", + a.mbb, + a.se + ); + } +} + +#[test] +fn tag_beats_random() { + for players in [2, 6] { + let r = hero(players, "tag", "random", 3000, 5, AivatMode::Off, true); + let e = &r.entrants[0]; + assert!(e.raw.ci95().0 > 500.0, "{players}p tag vs random {}", e.raw); + assert!(r.entrants[1].raw.mbb < 0.0); + } +} + +#[test] +fn reproducible_regardless_of_threads() { + let a = hero(6, "lag", "nit", 500, 3, AivatMode::Full, true); + let c = hero(6, "lag", "nit", 500, 3, AivatMode::Full, true); + assert_eq!(a.entrants[0].raw.mbb, c.entrants[0].raw.mbb); + assert_eq!( + a.entrants[0].aivat.unwrap().mbb, + c.entrants[0].aivat.unwrap().mbb + ); +} + +#[test] +fn aivat_unbiased_and_lower_variance() { + for (players, h, f, deals) in [ + (2, "tag", "lag", 30_000), + (6, "nit", "maniac", 8_000), + (2, "station", "random", 20_000), + ] { + let r = hero(players, h, f, deals, 21, AivatMode::Full, true); + let e = &r.entrants[0]; + let (raw, av) = (e.raw, e.aivat.unwrap()); + println!( + "{players}p {h} vs {f}: raw {raw} aivat {av} var ratio hand {:.2} deal {:.2}", + e.var_ratio_hand.unwrap(), + e.var_ratio_deal.unwrap() + ); + // Same mean within error: the difference is far tighter than either CI, so allow raw CI. + assert!( + (raw.mbb - av.mbb).abs() < 2.5 * raw.se, + "biased? raw {} aivat {}", + raw.mbb, + av.mbb + ); + assert!( + e.var_ratio_hand.unwrap() > 1.3, + "no hand-level variance reduction" + ); + assert!(av.se < raw.se); + // Cards-only baseline is also valid. + let c = hero(players, h, f, deals / 4, 22, AivatMode::CardsOnly, true); + let ce = &c.entrants[0]; + assert!((ce.aivat.unwrap().mbb - raw.mbb).abs() < 3.5 * (ce.raw.se + raw.se)); + } +} + +#[test] +fn blueprint_policy_plays_and_roundtrips() { + let bp = Arc::new(train_toy(2, 60_000, 1)); + let r = { + let mut spec = MatchSpec::new( + GameConfig::new(2), + vec![bp.clone(), b("random")], + Seatings::hero_vs_field(2), + 3000, + 9, + ); + spec.aivat = AivatMode::Full; + run_match(&spec) + }; + let e = &r.entrants[0]; + println!( + "toy bp vs random: {} aivat {} miss {:.3}", + e.raw, + e.aivat.unwrap(), + bp.miss_rate() + ); + assert!(e.raw.ci95().0 > 0.0); + // Biased variants construct and play. + for bias in [Bias::Fold, Bias::Call, Bias::Raise] { + let v: Arc = Arc::new(Biased::new(bp.clone(), bias)); + let spec = MatchSpec::new( + GameConfig::new(2), + vec![v, b("tag")], + Seatings::hero_vs_field(2), + 200, + 4, + ); + run_match(&spec); + } + // Save / load. + let path = std::env::temp_dir().join("bench_toy_roundtrip.bp"); + blueprint::io::save(bp.store(), &path).unwrap(); + let loaded = BlueprintPolicy::from_file(&path, "coarse", "tiny", 1 << 25).unwrap(); + let ra = { + let spec = MatchSpec::new( + GameConfig::new(2), + vec![bp.clone(), b("lag")], + Seatings::hero_vs_field(2), + 300, + 2, + ); + run_match(&spec).entrants[0].raw.mbb + }; + let rb = { + let spec = MatchSpec::new( + GameConfig::new(2), + vec![Arc::new(loaded), b("lag")], + Seatings::hero_vs_field(2), + 300, + 2, + ); + run_match(&spec).entrants[0].raw.mbb + }; + assert_eq!(ra, rb); +} + +#[test] +fn lbr_orders_policies_by_exploitability() { + let cfg = GameConfig::new(2); + let lc = LbrConfig { + samples: 150, + ..Default::default() + }; + let bp: Arc = Arc::new(train_toy(2, 60_000, 1)); + let station = run_lbr(&cfg, &lc, b("station"), 400, 1); + let random = run_lbr(&cfg, &lc, b("random"), 400, 1); + let nit = run_lbr(&cfg, &lc, b("nit"), 400, 1); + let tag = run_lbr(&cfg, &lc, b("tag"), 400, 1); + let toy = run_lbr(&cfg, &lc, bp, 400, 1); + for r in [&station, &random, &nit, &tag, &toy] { + println!("{r}"); + } + assert!(station.lbr.ci95().0 > 1000.0, "station {}", station.lbr); + assert!(random.lbr.ci95().0 > 1000.0, "random {}", random.lbr); + assert!( + toy.lbr.mbb < station.lbr.mbb && toy.lbr.mbb < random.lbr.mbb, + "toy bp should be harder to exploit" + ); +} + +#[test] +fn lbr_profile_6max_runs() { + let cfg = GameConfig::new(6); + let lc = LbrConfig { + samples: 60, + ..Default::default() + }; + let r = run_lbr(&cfg, &lc, b("station"), 40, 2); + println!("{r}"); + assert!(r.lbr.mbb > 0.0); +} + +/// Off-menu bets must leave the blueprint at nodes of its own tree: with the shadow-state +/// tracking the miss rate after a probe's odd-sized bet is as low as after an on-menu bet, +/// whereas the legacy tracking (translated indices over the real action list) misses a lot. +#[test] +fn off_menu_bets_keep_the_policy_in_its_tree() { + use bench::probe; + use nlhe::abstraction::{BelowMenu, TrackOpts}; + let bp = train_toy(2, 60_000, 3); + let path = std::env::temp_dir().join("bench_toy_offmenu.bp"); + blueprint::io::save(bp.store(), &path).unwrap(); + let load = |o: TrackOpts| { + Arc::new(BlueprintPolicy::from_file(&path, "coarse", "tiny", 1 << 25).unwrap().with_opts(o)) + }; + let miss = |o: TrackOpts, spec: &str| { + let p = load(o); + let m = MatchSpec::new( + GameConfig::new(2), + vec![probe::parse(spec).unwrap(), p.clone()], + Seatings::hero_vs_field(2), + 1500, + 5, + ); + run_match(&m); + p.miss_rate() + }; + let shadow = TrackOpts { below: BelowMenu::Smallest, allin_snap: 0.0, ..TrackOpts::default() }; + let base = miss(shadow, "probe:bet=1"); // pot-size bets: on the toy menu + for spec in ["probe:bet=0.3", "probe:bet=0.6", "probe:bet=2.5", "probe:pre=3,bet=0.4"] { + let (s, l) = (miss(shadow, spec), miss(TrackOpts::LEGACY, spec)); + println!("{spec}: shadow miss {s:.3}, legacy miss {l:.3}, on-menu {base:.3}"); + assert!(s <= base + 0.03, "{spec}: shadow miss {s} vs on-menu {base}"); + assert!(l > s, "{spec}: legacy {l} should miss more than shadow {s}"); + } +} diff --git a/arena/exploit/Cargo.toml b/arena/exploit/Cargo.toml new file mode 100644 index 00000000..303a3ab9 --- /dev/null +++ b/arena/exploit/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "exploit" +edition.workspace = true +version.workspace = true +description = "Strongest-adversary measurement: trained best response (ABR) and strong LBR against a frozen blueprint." + +[dependencies] +cards.workspace = true +rayon.workspace = true +serde_json.workspace = true +nlhe = { path = "../../engine/nlhe" } +blueprint = { path = "../../sharingan-1/blueprint" } +bench = { path = "../../arena/bench" } +abstraction = { path = "../../sharingan-1/abstraction" } + +[[bin]] +name = "exploit" +path = "src/main.rs" diff --git a/arena/exploit/RESULTS.md b/arena/exploit/RESULTS.md new file mode 100644 index 00000000..cccee4fb --- /dev/null +++ b/arena/exploit/RESULTS.md @@ -0,0 +1,102 @@ +# exploit: strongest adversary against a frozen blueprint + +All numbers are mbb/game (1000 mbb = 1 big blind), positive = the adversary wins = the target is +exploitable. `±` is the 95% CI. Exploiter figures are a duplicate match of the trained +exploiter (average strategy) vs copies of the target through `bench::matchrun` with full AIVAT, +the exploiter rotated through every seat on identical deals. Reproduce with +`cargo test --release -p exploit -- --nocapture` (about 80 s on an idle 14-core Mac; the tests +use ~1 GB). Training is hogwild-parallel, so rerunning moves the numbers by a few percent. + +## 1. Exploitability vs blueprint training (heads-up, `tiny` sizing, 9-category postflop buckets) + +Targets: paper-style toy blueprints (Linear CFR, preflop average, postflop average of 5 snapshots), +`exploit::train_blueprint(2, N, 11)`. `ABR same` = exploiter with the target's buckets and menu +(150k iterations, ~3 s). `ABR fine` = hand-strength-refined buckets (x12 levels) and a bigger menu +{0.33, 0.66, 1, 1.5 pot, all-in} translated into the target's menu (50k iterations, ~10 s). +LBR = `bench::lbr` on 300 deals (strong = 8 bet sizes, weak = bench default). + +| blueprint iters | ABR same | ABR fine | strong LBR | weak LBR | +|---:|---:|---:|---:|---:| +| 1,000 | +11122 ± 442 | +15413 ± 444 | +2046 ± 3498 | +3748 ± 3265 | +| 30,000 | +3346 ± 258 | +10247 ± 381 | +5326 ± 2908 | +3173 ± 2431 | +| 300,000 | +2467 ± 254 | +9918 ± 372 | +7732 ± 3128 | +1528 ± 2039 | + +* **The key curve is the `ABR same` column: 11.1 -> 3.3 -> 2.5 bb/game, strictly decreasing** + (asserted in `tests/curve.rs`). It is the abstract-game exploitability: how much a player who + sees exactly what the target sees can win. It falls as the blueprint converges. +* `ABR fine` does **not** fall monotonically after 30k, by construction: it also exploits the + *abstraction* (the target cannot tell a pair of deuces from a pair of aces), which more CFR + iterations in the same abstraction do not remove. It is the better estimate of real-game + exploitability and the number to track for "how far from unexploitable". It is also still + under-trained (50k iterations over ~400k infosets). +* The fine exploiter beats the best LBR in every row, as required. The same-information + exploiter does not always beat LBR (LBR sees exact cards and off-tree sizes), so "exploiter >= LBR" + holds for the exploiter that is allowed the same information, not for the info-matched one. +* LBR needs far more deals than the exploiter evaluation for a usable CI (here +-3000 mbb on 300 + deals vs +-250-450 for 15,000 AIVAT deals). + +## 2. Push/fold sanity (HU, 10 bb, fold/shove vs fold/call, 169 classes) + +Equity matrix by Monte Carlo (25k boards per class pair), solved with CFR+ (20k iterations); the +matrix game's exact exploitability is computed by best response over the 169x169 matrix. +Exploiter: 400k iterations, 200k AIVAT deals, both seats. + +| target | exact exploitability (matrix) | exploiter wins (AIVAT) | +|---|---:|---:| +| CFR+ equilibrium (SB shoves 58.3%) | 0.00003 | -9.5 ± 1.7 (SB -56, BB +37) | +| equilibrium blended 40% to always-shove / never-call | 226.3 | +222.3 ± 2.8 | + +Against the equilibrium the exploiter wins ~0 (slightly negative: its average strategy is not an +exact best response, and an equilibrium cannot lose); against the perturbed copy it recovers 98% +of the exact exploitability. The residual -10 mbb is the 400k-iteration convergence error of the +learner, not an equity-matrix artifact (exact exploitability of the target is 0.00003 mbb on the +sampled matrix; MC equity error of ~0.2% per cell averages out). + +## 3. Exploiter vs LBR + +Section 1: on the same targets the fine exploiter is 2-7x the strong LBR (LBR is a greedy +check/call-continuation lower bound; the exploiter is a trained policy over the whole tree). +LBR rows are noisy; the ordering holds in all three rows. + +## 4. Not done / caveats + +* **No river-exact LBR.** `bench::lbr::decide` is MC over opponent holes and runouts; an exact + river best response against the Bayes range needs a change inside bench (enumerate the <= 1081 + opponent holes weighted by the posterior instead of sampling, no runout). `exploit::lbr` only + wraps it with a richer menu and more samples. The trained exploiter already plays the river + (and everything else) as an MCCFR best response, so it subsumes this. +* 6-max numbers are a **profile** best response (one deviator vs 5 target copies), not an + equilibrium-gap bound (3+ player equilibria are not unique). A 6-player toy run works end to end. +* Exploiter quality is bounded by its abstraction: use `--fine L` (or a finer bucket table) and + more iterations; a larger menu works through deterministic translation, which the target's + `BlueprintPolicy` also uses in the evaluation match, so training and evaluation agree. +* AIVAT variance reduction uses bench's default equity estimator; both exploiter and target expose + exact probabilities. + +## 5. CLI and memory + +``` +exploit --target blueprint.bin --sizing local|paper|tiny --buckets DIR|coarse --players 6 \ + --iters 2000000000 --threads 128 --mem-gb 40 --seat all --eval-deals 20000 \ + [--fine 12] [--extract average|argmax] [--lbr-deals 500] [--seed 1] [--out result.json] +``` + +JSON on stdout: per-seat and average exploitation (AIVAT and raw), learner store size / fullness / +miss rate, optional LBR. Memory = loaded target (index ~29 B + 4 B per slot per infoset, i.e. +exactly the checkpoint's size class) + learner store (`--mem-gb`, split ~1:1 between the 16 B / 0.7 +load index and the regret+average arena; ~50 B per learner infoset with 3 actions, average on all +streets) + a few GB for the evaluation match. Keep target + `--mem-gb` below ~60 GB. If the +learner store fills it plays uniformly at unseen infosets and reports `store_full: true` +(raise `--mem-gb` or fix fewer seats with `--seat S`; one store serves all seats because a history key +fixes whose turn it is). + +## 6. Other runs + +* A second full run of the tests (machine at load average ~100 from other jobs) reproduced the + picture: ABR same 11942 / 3600 / 2925, ABR fine 14375 / 10960 / 12325, push/fold -9.8 ± 1.7 + vs equilibrium and +221.9 ± 2.8 vs the perturbed copy (exact 226.0). Uncontended wall time: + curve test ~50 s, push/fold test ~25 s. +* CLI smoke on a 6-player toy blueprint (`train_blueprint(6, 200000)`, `--iters 200000`, + `--mem-gb 2`, all seats, 4000 AIVAT deals): average +1636 ± 353 mbb/game; by seat + (SB..BTN) -47, -1806, +3864, +4165, +1974, +1664 (each ± ~1000); learner 980k infosets, 4.4M + slots, miss rate 2.4% (under-trained; raise `--iters`), 32 s training. diff --git a/arena/exploit/bots/ctl_quickstart.py b/arena/exploit/bots/ctl_quickstart.py new file mode 100644 index 00000000..a1b1d1a2 --- /dev/null +++ b/arena/exploit/bots/ctl_quickstart.py @@ -0,0 +1,10 @@ +"""Function-only SDK quickstart control: safe to import for offline pipe evaluation.""" +from sharingan import Action + + +def act(s): + if s.legal.raise_ and s.hole_cards[0][0] in "AK": + return Action.raise_to(3 * s.big_blind) + if s.legal.check: + return Action.check() + return Action.call() if s.pot_odds < 0.25 else Action.fold() diff --git a/arena/exploit/examples/make_toy.rs b/arena/exploit/examples/make_toy.rs new file mode 100644 index 00000000..f9e4ffaa --- /dev/null +++ b/arena/exploit/examples/make_toy.rs @@ -0,0 +1,8 @@ +//! Write a toy blueprint checkpoint (tiny sizing, coarse buckets) for trying the CLI: +//! `cargo run --release -p exploit --example make_toy -- OUT PLAYERS ITERS` +fn main() { + let a: Vec = std::env::args().collect(); + let (players, iters) = (a[2].parse().unwrap(), a[3].parse().unwrap()); + let st = exploit::train_blueprint(players, iters, 11); + blueprint::io::save(&st, std::path::Path::new(&a[1])).unwrap(); +} diff --git a/arena/exploit/src/abr.rs b/arena/exploit/src/abr.rs new file mode 100644 index 00000000..c5734372 --- /dev/null +++ b/arena/exploit/src/abr.rs @@ -0,0 +1,546 @@ +//! Trained best response ("ABR"): external-sampling MCCFR for one or more *learner* seats while +//! every other seat samples from a frozen [`Target`]. +//! +//! Same algorithmic shape as `blueprint::trainer::traverse` (abstract game, one sampled deal per +//! traversal, learner enumerates its actions, opponents are sampled), with three differences: +//! * opponents never update and are never the regret-matching strategy of the learner store: they +//! come from the target (so the learner faces a fixed environment and its regret-matching +//! average converges to a best response in the abstract game); +//! * the learner's regrets live in a separate fresh [`Store`]; every infoset carries an average +//! strategy (all streets), accumulated by a cheap on-policy walk (own actions sampled, so the +//! counters are reach-weighted) and Linear-CFR discounted together with the regrets, which makes +//! the average linearly weighted over the run; +//! * no negative-regret pruning (the opponents are fixed, the tree is only the learner's). +//! +//! One store serves all learner seats: a history key fixes whose turn it is, so learner `s` +//! only ever touches infosets where `s` acts and the seats cannot collide. +//! +//! The learner may use a different (finer) [`Bucketer`] than the target and a bigger action menu. +//! The target keeps its own abstract history: every action (the learner's included) is +//! translated into the target's menu with the deterministic pseudo-harmonic mapping, which is +//! the tracking used by `bench::bp::BlueprintPolicy` when it plays the exploiter in the evaluation +//! match, so training and evaluation see the same target. + +use crate::game::{ActionSpace, Target}; +use bench::mix; +use bench::policy::{Dist, Player, PolicyFactory, View}; +use blueprint::store::{Slot, Store}; +use blueprint::trainer::Bucketer; +use cards::{Card, Rng}; +use nlhe::abstraction::{ActionList, History, Shadow, TrackOpts, MAX_ACTIONS}; +use nlhe::{Action, Deal, GameConfig, State, Street, MAX_PLAYERS}; +use rayon::prelude::*; +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; +use std::sync::Arc; +use std::time::Instant; + +pub type Buck = Arc; + +/// Learner histories record the exact concrete action, not its index in the learner's menu: +/// with a learner menu different from the target's, two different real bet sizes can share a +/// translated index, which would map distinct states (with different action lists) onto one +/// learner infoset. Exact codes keep learner infosets a function of the true public history. +#[inline(always)] +fn learner_code(a: Action) -> usize { + match a { + Action::Fold => 0, + Action::Check => 1, + Action::Call => 2, + Action::RaiseTo(x) => 3 + x as usize, + } +} + +#[derive(Clone, Debug)] +pub struct AbrConfig { + pub game: GameConfig, + /// Learner seats (traversed every iteration). + pub seats: Vec, + pub iters: u64, + pub seed: u64, + /// Number of Linear-CFR discount steps spread evenly over the run (0 = none). + pub discounts: u64, + /// Regret slots (i32) reserved for the learner store. + pub capacity: usize, + /// Index entries (infosets) reserved for the learner store. + pub max_infosets: usize, +} + +impl AbrConfig { + pub fn new(game: GameConfig, seats: Vec, iters: u64, seed: u64) -> Self { + AbrConfig { + game, + seats, + iters, + seed, + discounts: 100, + capacity: 1 << 24, + max_infosets: 1 << 22, + } + } + /// Split `mem_gb` between the index (16 B / 0.7 load) and the regret+average arena (two + /// i32 per action; ~3 actions per infoset => ~24 B), roughly 1:1. + pub fn with_mem_gb(mut self, mem_gb: f64) -> Self { + self.max_infosets = (mem_gb * 1e9 * 0.5 / 23.0) as usize; + self.capacity = (mem_gb * 1e9 * 0.5 / 4.0) as usize; + self + } +} + +struct Ctx { + deal: Deal, + /// Target-bucketer buckets `[seat][street]`. + tb: [[u32; 4]; MAX_PLAYERS], + /// Learner-bucketer buckets `[seat][street]`. + lb: [[u32; 4]; MAX_PLAYERS], +} + +pub struct Exploiter { + pub cfg: AbrConfig, + /// Learner's action menu (may be a superset of the target's). + pub space: Arc, + /// The target's own menu (used to key and translate into the target's history). + pub target_space: Arc, + same_space: bool, + /// How the target tracks the abstract game (translation of the learner's off-menu bets). + pub track: TrackOpts, + pub target: Arc, + pub target_bucketer: Buck, + pub learner_bucketer: Buck, + pub store: Arc, + pub nodes: AtomicU64, +} + +impl Exploiter { + pub fn new( + cfg: AbrConfig, + space: Arc, + target_space: Arc, + target: Arc, + target_bucketer: Buck, + learner_bucketer: Buck, + ) -> Self { + let same_space = Arc::ptr_eq(&space, &target_space); + let store = Arc::new(Store::with_index(cfg.capacity, cfg.max_infosets)); + Exploiter { + cfg, + space, + target_space, + same_space, + track: TrackOpts::default(), + target, + target_bucketer, + learner_bucketer, + store, + nodes: AtomicU64::new(0), + } + } + + /// Translation/tracking options of the target (must match the evaluation target policy). + pub fn with_track(mut self, track: TrackOpts) -> Self { + self.track = track; + self + } + + fn sample_ctx(&self, rng: &mut Rng) -> Ctx { + let deal = Deal::random(rng); + let (mut tb, mut lb) = ([[0u32; 4]; MAX_PLAYERS], [[0u32; 4]; MAX_PLAYERS]); + let same = Arc::as_ptr(&self.target_bucketer) as *const () + == Arc::as_ptr(&self.learner_bucketer) as *const (); + for p in 0..self.cfg.game.players { + for s in Street::ALL { + let b = &deal.board[..s.board_len()]; + tb[p][s.idx()] = self.target_bucketer.bucket(s, deal.holes[p], b); + lb[p][s.idx()] = if same { + tb[p][s.idx()] + } else { + self.learner_bucketer.bucket(s, deal.holes[p], b) + }; + } + } + Ctx { deal, tb, lb } + } + + #[inline] + fn learner_slot( + &self, + st: &State, + hist: &History, + ctx: &Ctx, + actor: usize, + n: usize, + ) -> Option { + let street = st.street(); + self.store.try_infoset( + hist.key(), + ctx.lb[actor][street.idx()], + n, + self.learner_bucketer.n_buckets(street) as usize, + true, + ) + } + + /// Both abstract action lists at `st`: the learner's (real state) and the target's (its + /// shadow node; identical to the learner's when the spaces are shared and nothing was + /// translated). + #[inline] + fn lists(&self, st: &State, sh: &Shadow) -> (ActionList, ActionList) { + let mut l = ActionList::new(); + self.space.actions(st, &mut l); + if self.same_space && !sh.off_tree() { + return (l, l); + } + let mut t = ActionList::new(); + if sh.synced(st) { + self.target_space.actions(sh.node(st), &mut t); + } + (l, t) + } + + /// Apply `action` (a real action) at `st`, extending the learner history and the target's + /// shadow game. `by_target`: the action was the target's own (not translated). + #[inline] + fn advance( + &self, + st: &State, + h: &(History, Shadow), + action: Action, + by_target: bool, + rng: &mut Rng, + ) -> (State, (History, Shadow)) { + let mut s2 = *st; + s2.apply(action); + let (mut lh, mut th) = *h; + lh.push(learner_code(action)); + th.observe_with(st, action, by_target, rng, |s, out| self.target_space.actions(s, out)); + (s2, (lh, th)) + } + + /// Sample the same target used by evaluation, including its off-tree fallback. + #[inline] + fn target_real_action( + &self, + st: &State, + h: &Shadow, + ctx: &Ctx, + actor: usize, + list: &ActionList, + rng: &mut Rng, + ) -> Action { + let fallback = || { + if self.track.keep_sync { + bench::bp::fallback_action(st, &ctx.deal.board[..st.street().board_len()], ctx.deal.holes[actor]) + } else if st.legal().can_check { + Action::Check + } else { + Action::Call + } + }; + if !h.synced(st) { + return fallback(); + } + let n = list.len(); + let mut sigma = [0f32; MAX_ACTIONS]; + if !self.target.probs( + h.node(st), h.key(), ctx.tb[actor][st.street().idx()], &mut sigma[..n], + ) { + return fallback(); + } + h.real_action(st, list, rng.sample_weighted(&sigma[..n])) + } + + fn traverse( + &self, + st: State, + h: (History, Shadow), + ctx: &Ctx, + p: usize, + rng: &mut Rng, + ) -> f32 { + if st.is_terminal() { + return st.payoffs(&ctx.deal)[p] as f32; + } + if st.is_folded(p) { + return -st.contributed(p) as f32; + } + self.nodes.fetch_add(1, Relaxed); + let actor = st.to_act().unwrap(); + let lists = self.lists(&st, &h.1); + if actor != p { + let a = self.target_real_action(&st, &h.1, ctx, actor, &lists.1, rng); + let (s2, h2) = self.advance(&st, &h, a, true, rng); + return self.traverse(s2, h2, ctx, p, rng); + } + let n = lists.0.len(); + let Some(slot) = self.learner_slot(&st, &h.0, ctx, p, n) else { + // Learner store full and infoset never allocated: play uniformly, learn nothing here. + let a = lists.0.get(rng.below(n as u32) as usize); + let (s2, h2) = self.advance(&st, &h, a, false, rng); + return self.traverse(s2, h2, ctx, p, rng); + }; + let mut sigma = [0f32; MAX_ACTIONS]; + self.store.strategy(slot, &mut sigma[..n]); + let mut va = [0f32; MAX_ACTIONS]; + let mut v = 0f32; + for a in 0..n { + let (s2, h2) = self.advance(&st, &h, lists.0.get(a), false, rng); + va[a] = self.traverse(s2, h2, ctx, p, rng); + v += sigma[a] * va[a]; + } + for a in 0..n { + self.store.add_regret(slot, a, va[a] - v); + } + v + } + + /// On-policy walk accumulating the learner's average strategy (own action sampled from the + /// current strategy, opponents from the target). + fn walk(&self, mut st: State, mut h: (History, Shadow), ctx: &Ctx, p: usize, rng: &mut Rng) { + while !st.is_terminal() && !st.is_folded(p) { + let actor = st.to_act().unwrap(); + let lists = self.lists(&st, &h.1); + let by_target = actor != p; + let action = if actor == p { + let n = lists.0.len(); + let Some(slot) = self.learner_slot(&st, &h.0, ctx, p, n) else { + return; + }; + let mut sigma = [0f32; MAX_ACTIONS]; + self.store.strategy(slot, &mut sigma[..n]); + let a = rng.sample_weighted(&sigma[..n]); + self.store.bump_avg(slot, a); + lists.0.get(a) + } else { + self.target_real_action(&st, &h.1, ctx, actor, &lists.1, rng) + }; + (st, h) = self.advance(&st, &h, action, by_target, rng); + } + } + + pub fn iteration(&self, rng: &mut Rng) { + let root = State::new(&self.cfg.game); + for &p in &self.cfg.seats { + let ctx = self.sample_ctx(rng); + let h = (History::new(), Shadow::new(&root, self.track)); + self.traverse(root, h, &ctx, p, rng); + self.walk(root, h, &ctx, p, rng); + } + } + + /// Train for `cfg.iters` iterations; `on_progress(self, iteration, seconds)` runs between batches. + pub fn train(&self, mut on_progress: impl FnMut(&Self, u64, f64)) { + let start = Instant::now(); + let iters = self.cfg.iters; + let di = if self.cfg.discounts == 0 { + u64::MAX + } else { + (iters / self.cfg.discounts).max(1) + }; + let (mut t, seed) = (0u64, self.cfg.seed); + while t < iters { + let mut end = (t + 4096).min(iters); + end = end.min((t / di + 1).saturating_mul(di)); + // One RNG stream per iteration (never per rayon thread). + (t..end) + .into_par_iter() + .for_each(|it| self.iteration(&mut Rng::new(mix(seed, it)))); + t = end; + if t % di == 0 && t < iters { + let k = (t / di) as f64; + self.store.discount(k / (k + 1.0)); + } + on_progress(self, t, start.elapsed().as_secs_f64()); + } + } + + /// The trained exploiter as a playable policy (see [`Extract`]). + pub fn policy(&self, name: &str, extract: Extract) -> Arc { + Arc::new(ExploiterPolicy::from_store( + name, self.store.clone(), self.space.clone(), self.learner_bucketer.clone(), extract, + )) + } +} + +/// How the trained learner store is turned into a playing strategy. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Extract { + /// Normalised average strategy (default; the quantity that converges). + Average, + /// Pure argmax of the average strategy. + Argmax, +} + +struct Shared { + store: Arc, + space: Arc, + bucketer: Buck, + extract: Extract, + lookups: AtomicU64, + misses: AtomicU64, +} + +pub struct ExploiterPolicy { + name: String, + sh: Arc, +} + +impl ExploiterPolicy { + /// Restore an exact, frozen learner for paired evaluations without retraining. + pub fn from_store(name: &str, store: Arc, space: Arc, bucketer: Buck, extract: Extract) -> Self { + Self { + name: name.to_string(), + sh: Arc::new(Shared { + store, space, bucketer, extract, + lookups: AtomicU64::new(0), misses: AtomicU64::new(0), + }), + } + } + + /// Fraction of decisions at infosets the learner never visited (played check/call). + pub fn miss_rate(&self) -> f64 { + self.sh.misses.load(Relaxed) as f64 / self.sh.lookups.load(Relaxed).max(1) as f64 + } +} + +impl PolicyFactory for ExploiterPolicy { + fn name(&self) -> String { + self.name.clone() + } + fn new_player(&self, _seat: usize, _cfg: &GameConfig, _seed: u64) -> Box { + Box::new(ExploiterPlayer { + sh: self.sh.clone(), + hist: History::new(), + }) + } +} + +#[derive(Clone)] +struct ExploiterPlayer { + sh: Arc, + hist: History, +} + +impl Player for ExploiterPlayer { + fn observe(&mut self, pre: &State, _seat: usize, a: Action) { + let mut list = ActionList::new(); + self.sh.space.actions(pre, &mut list); + let _ = list; + self.hist.push(learner_code(a)); + } + + fn dist(&mut self, v: &View, hole: [Card; 2]) -> Dist { + let mut list = ActionList::new(); + self.sh.space.actions(v.state, &mut list); + let n = list.len(); + let bucket = self.sh.bucketer.bucket(v.state.street(), hole, v.board); + self.sh.lookups.fetch_add(1, Relaxed); + let mut d = Dist::new(); + let Some(slot) = self + .sh + .store + .lookup(self.hist.key(), bucket) + .filter(|s| s.n_actions as usize == n) + else { + self.sh.misses.fetch_add(1, Relaxed); + let passive = list + .as_slice() + .iter() + .copied() + .find(|a| matches!(a, Action::Check | Action::Call)) + .unwrap_or(list.get(0)); + d.push(passive, 1.0); + return d; + }; + let mut p = [0f32; MAX_ACTIONS]; + self.sh.store.average(slot, &mut p[..n]); + if self.sh.extract == Extract::Argmax { + let best = (0..n).fold(0, |b, i| if p[i] > p[b] { i } else { b }); + p[..n].iter_mut().for_each(|x| *x = 0.0); + p[best] = 1.0; + } + for i in 0..n { + d.push(list.get(i), p[i]); + } + d + } + + fn fork(&self) -> Option> { + Some(Box::new(self.clone())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use bench::bp::{BlueprintPolicy, CoarseBucketer}; + use crate::game::StoreTarget; + + // Compare the training target to the policy actually evaluated, with no model files. + fn fallback_parity(track: TrackOpts, handoff: bool) { + let cfg = GameConfig::new(6); + let sizing = bench::bp::sizing_by_name("medium").unwrap(); + let store = Arc::new(Store::new(16)); + let buck: Buck = Arc::new(CoarseBucketer); + let ex = Exploiter::new( + AbrConfig::new(cfg, vec![0], 1, 1), Arc::new(sizing.clone()), + Arc::new(sizing.clone()), Arc::new(StoreTarget::new(store.clone())), + buck.clone(), buck.clone(), + ).with_track(track); + let policy = BlueprintPolicy::new("empty", store, buck, sizing.clone()).with_opts(track); + let mut nonpassive = 0; + for seed in 1..=16 { + let mut rng = Rng::new(seed); + let ctx = ex.sample_ctx(&mut rng); + let mut st = State::new(&cfg); + let mut shadow = Shadow::new(&st, track); + let mut players: Vec<_> = (0..6).map(|s| policy.new_player(s, &cfg, seed)).collect(); + let mut history = Vec::new(); + if handoff { + // Force a legal non-all-in raise past the abstract cap. + while shadow.synced(&st) { + let l = st.legal(); + assert!(l.can_raise && l.min_raise_to < l.max_raise_to); + let a = Action::RaiseTo(l.min_raise_to); + let actor = st.to_act().unwrap(); + for p in &mut players { p.observe(&st, actor, a); } + shadow.observe(&st, &sizing, a, false, &mut rng); + history.push(bench::policy::Event { seat: actor as u8, street: st.street(), action: a }); + st.apply(a); + } + assert_eq!(shadow.desync_reason(), 4); + } + let actor = st.to_act().unwrap(); + let (_, list) = ex.lists(&st, &shadow); + let actual = ex.target_real_action(&st, &shadow, &ctx, actor, &list, &mut rng); + let view = View { cfg: &cfg, state: &st, board: &ctx.deal.board[..st.street().board_len()], history: &history, seat: actor }; + let dist = players[actor].dist(&view, ctx.deal.holes[actor]); + assert_eq!(dist.prob_of(actual), 1.0, "seed {seed}: training {actual:?}, evaluation {dist:?}"); + if !matches!(actual, Action::Check | Action::Call) { nonpassive += 1; } + } + if handoff { + let report: serde_json::Value = serde_json::from_str(&policy.diag_json()).unwrap(); + let count: u64 = ["on_menu", "after_off_menu"].iter().map(|class| { + let why = report[*class]["why"].as_array().unwrap(); + assert_eq!(why.len(), 5, "diagnostics must include reason 4"); + why[3].as_u64().unwrap() + }).sum(); + assert_eq!(count, 16, "every tested hand-off must appear in the report"); + } + eprintln!("fallback parity: keep_sync={} handoff={handoff}, fixed mismatches=0/16, check/call mismatches={nonpassive}/16", track.keep_sync); + if track.keep_sync { + assert!(nonpassive > 0, "fixture must distinguish the fixed fallback from check/call"); + } else { + assert_eq!(nonpassive, 0, "positive-control target must retain its old fallback"); + } + } + + #[test] + fn missing_infoset_training_matches_evaluation() { + fallback_parity(TrackOpts::default(), false); + fallback_parity(TrackOpts::PRE_SYNC_FIX, false); + } + + #[test] + fn raise_cap_training_matches_evaluation() { + fallback_parity(TrackOpts::default(), true); + } +} diff --git a/arena/exploit/src/audit.rs b/arena/exploit/src/audit.rs new file mode 100644 index 00000000..f2168f4f --- /dev/null +++ b/arena/exploit/src/audit.rs @@ -0,0 +1,176 @@ +//! Observational localisation of frozen-attacker profit by shadow hand-off exposure. +//! This never changes a decision. Conditional raw payoffs are descriptive, not causal +//! effects or independent-deal confidence intervals. Missing-infoset fallbacks are excluded. + +use bench::policy::{Dist, Event, Player, PolicyFactory, View}; +use cards::{Card, Rng}; +use nlhe::abstraction::{BetSizing, Shadow, TrackOpts, Translation}; +use nlhe::{Action, Deal, GameConfig, State, MAX_PLAYERS}; +use serde_json::{json, Value}; +use std::sync::{Arc, Mutex}; + +#[derive(Clone, Copy, Default)] +struct Bucket { + hands: u64, + chips: i64, +} + +#[derive(Default)] +struct Stats { + groups: [[Bucket; 5]; MAX_PLAYERS], + decisions: [[u64; 6]; 4], +} + +/// Wrap the sole attacker in a one-attacker-vs-blueprints match. Reconstruct each +/// target's own shadow from the completed public history; count only actual target turns. +pub struct HandoffAudit { + inner: Arc, + sizing: BetSizing, + opts: TrackOpts, + stats: Arc>, +} + +impl HandoffAudit { + pub fn new(inner: Arc, sizing: BetSizing, opts: TrackOpts) -> Self { + assert_eq!(opts.translation, Translation::Deterministic, "handoff audit requires deterministic translation"); + Self { inner, sizing, opts, stats: Arc::new(Mutex::new(Stats::default())) } + } + + pub fn json(&self, bb: f64) -> Value { + let s = self.stats.lock().unwrap(); + let bucket = |b: Bucket| json!({"hands": b.hands, "raw_sum_chips": b.chips, + "mean_raw_mbb": if b.hands == 0 { None } else { Some(b.chips as f64 / b.hands as f64 / bb * 1000.0) }}); + let overall: Vec<_> = (0..5).map(|g| { + let b = s.groups.iter().fold(Bucket::default(), |mut b, row| { b.hands += row[g].hands; b.chips += row[g].chips; b }); + bucket(b) + }).collect(); + json!({ + "classification": ["preflop", "flop", "turn", "river", "no_shadow_handoff_decision"], + "first_shadow_fallback_street": overall, + "by_attacker_seat": s.groups.iter().map(|row| row.iter().copied().map(&bucket).collect::>()).collect::>(), + "shadow_fallback_decisions_by_street_and_reason": s.decisions, + "caveat": "Observational raw-payoff groups, not causal effects or AIVAT estimates; missing-infoset fallbacks are not detected." + }) + } + + fn wrap(&self, inner: Box, seat: usize, cfg: GameConfig, record: bool) -> Box { + Box::new(Audited { inner, seat, cfg, sizing: self.sizing.clone(), opts: self.opts, stats: self.stats.clone(), record }) + } +} + +impl PolicyFactory for HandoffAudit { + fn name(&self) -> String { self.inner.name() } + fn new_player(&self, seat: usize, cfg: &GameConfig, seed: u64) -> Box { + self.wrap(self.inner.new_player(seat, cfg, seed), seat, *cfg, true) + } + fn new_player_ctx(&self, seat: usize, cfg: &GameConfig, seed: u64, who: &[usize]) -> Box { + assert_eq!(who.iter().filter(|&&e| e == who[seat]).count(), 1, "audit expects exactly one attacker"); + self.wrap(self.inner.new_player_ctx(seat, cfg, seed, who), seat, *cfg, true) + } + fn report(&self) -> Option { self.inner.report() } +} + +struct Audited { + inner: Box, + seat: usize, + cfg: GameConfig, + sizing: BetSizing, + opts: TrackOpts, + stats: Arc>, + record: bool, +} + +impl Player for Audited { + fn dist(&mut self, v: &View, hole: [Card; 2]) -> Dist { self.inner.dist(v, hole) } + fn act(&mut self, v: &View, hole: [Card; 2], u: f64) -> Action { self.inner.act(v, hole, u) } + fn observe(&mut self, pre: &State, seat: usize, a: Action) { self.inner.observe(pre, seat, a); } + fn observe_board(&mut self, b: &[Card]) { self.inner.observe_board(b); } + fn exposes_probs(&self) -> bool { self.inner.exposes_probs() } + fn take_note(&mut self) -> Option { self.inner.take_note() } + fn fork(&self) -> Option> { + Some(Box::new(Self { inner: self.inner.fork()?, seat: self.seat, cfg: self.cfg, + sizing: self.sizing.clone(), opts: self.opts, stats: self.stats.clone(), record: false })) + } + fn finish(&mut self, deal: &Deal, hist: &[Event], end: &State) { + self.inner.finish(deal, hist, end); + if !self.record { return; } + let mut st = State::new(&self.cfg); + let mut shadows = [Shadow::new(&st, self.opts); MAX_PLAYERS]; + let mut rng = Rng::new(0); // deterministic translation never draws + let mut first = None; + let mut counts = [[0u64; 6]; 4]; + for ev in hist { + let actor = ev.seat as usize; + assert_eq!(st.to_act(), Some(actor)); + assert_eq!(st.street(), ev.street); + if actor != self.seat { + let why = shadows[actor].sync_reason(&st); + if why != 0 { + first.get_or_insert(st.street().idx()); + counts[st.street().idx()][why as usize] += 1; + } + } + for (s, sh) in shadows.iter_mut().enumerate().take(self.cfg.players) { + if s != self.seat { sh.observe(&st, &self.sizing, ev.action, s == actor, &mut rng); } + } + st.apply(ev.action); + } + assert!(st.is_terminal()); + assert_eq!(st.payoffs(deal), end.payoffs(deal)); + let mut stats = self.stats.lock().unwrap(); + let b = &mut stats.groups[self.seat][first.unwrap_or(4)]; + b.hands += 1; + b.chips += end.payoffs(deal)[self.seat] as i64; + for street in 0..4 { for why in 1..6 { stats.decisions[street][why] += counts[street][why]; } } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::eval::evaluate; + + struct Simple(bool); + impl PolicyFactory for Simple { + fn name(&self) -> String { format!("simple-{}", self.0) } + fn new_player(&self, _: usize, _: &GameConfig, _: u64) -> Box { Box::new(Simple(self.0)) } + } + impl Player for Simple { + fn dist(&mut self, v: &View, _: [Card; 2]) -> Dist { + let l = v.state.legal(); + Dist::pure(if self.0 && l.can_raise { Action::RaiseTo(l.min_raise_to.min(l.max_raise_to)) } + else if l.can_check { Action::Check } else { Action::Call }) + } + fn fork(&self) -> Option> { Some(Box::new(Simple(self.0))) } + } + + #[test] + fn audit_preserves_decisions_estimates_and_raw_payoffs() { + let cfg = GameConfig::new(6); + let seats: Vec<_> = (0..6).collect(); + for wars in [false, true] { + let hero: Arc = Arc::new(Simple(false)); + let field: Arc = Arc::new(Simple(wars)); + let audit = Arc::new(HandoffAudit::new(hero.clone(), bench::bp::sizing_by_name("medium").unwrap(), TrackOpts::default())); + let plain = evaluate(&cfg, hero, field.clone(), &seats, 50, 22); + let profiled = evaluate(&cfg, audit.clone(), field, &seats, 50, 22); + assert_eq!(plain.json(), profiled.json(), "audit must not change any match estimates"); + let report = audit.json(cfg.big_blind as f64); + let groups = report["first_shadow_fallback_street"].as_array().unwrap(); + let hands: u64 = groups.iter().map(|g| g["hands"].as_u64().unwrap()).sum(); + let chips: i64 = groups.iter().map(|g| g["raw_sum_chips"].as_i64().unwrap()).sum(); + assert_eq!(hands, 300, "one profile record per actual hand, not per target or fork"); + assert!((chips as f64 / hands as f64 / cfg.big_blind as f64 * 1000.0 - plain.raw.mbb).abs() < 1e-8); + if wars { assert!(groups[0]["hands"].as_u64().unwrap() > 0, "fixture must reach preflop hand-offs"); } + else { assert_eq!(groups[4]["hands"], 300); } + } + } + + #[test] + #[should_panic(expected = "requires deterministic translation")] + fn rejects_hidden_random_translation() { + let mut opts = TrackOpts::default(); + opts.translation = Translation::Random; + HandoffAudit::new(Arc::new(Simple(false)), bench::bp::sizing_by_name("medium").unwrap(), opts); + } +} diff --git a/arena/exploit/src/buckets.rs b/arena/exploit/src/buckets.rs new file mode 100644 index 00000000..a9f5719f --- /dev/null +++ b/arena/exploit/src/buckets.rs @@ -0,0 +1,71 @@ +//! Finer information abstraction for the exploiter. +//! +//! [`Refined`] splits every postflop bucket of a base abstraction by exact hand strength +//! against a uniformly random hand (win + tie/2 over all opponent holes, no future cards), +//! quantised to `levels`. Preflop stays the base's (lossless) classes. It costs ~1000 hand +//! evaluations per postflop bucket call, so it suits tests and moderate runs; for blueprint +//! scale prefer a finer k-means table via `--buckets`. + +use crate::abr::Buck; +use blueprint::trainer::Bucketer; +use cards::{all_holes, bit, evaluate, mask_of, Card}; +use nlhe::Street; + +pub struct Refined { + pub base: Buck, + pub levels: u32, + holes: Vec<[Card; 2]>, +} + +impl Refined { + pub fn new(base: Buck, levels: u32) -> Self { + Refined { + base, + levels, + holes: all_holes(), + } + } + + /// Hand strength in [0, 1] vs a random opponent hand on `board`. + pub fn strength(&self, hole: [Card; 2], board: &[Card]) -> f32 { + let b = mask_of(board); + let mine = bit(hole[0]) | bit(hole[1]); + let r = evaluate(b | mine); + let (mut score, mut n) = (0.0f32, 0u32); + for h in &self.holes { + let o = bit(h[0]) | bit(h[1]); + if o & (b | mine) != 0 { + continue; + } + let ro = evaluate(b | o); + score += if r > ro { + 1.0 + } else if r == ro { + 0.5 + } else { + 0.0 + }; + n += 1; + } + score / n.max(1) as f32 + } +} + +impl Bucketer for Refined { + fn bucket(&self, street: Street, hole: [Card; 2], board: &[Card]) -> u32 { + let base = self.base.bucket(street, hole, board); + if street == Street::Preflop { + return base; + } + let lvl = ((self.strength(hole, board) * self.levels as f32) as u32).min(self.levels - 1); + base * self.levels + lvl + } + fn n_buckets(&self, street: Street) -> u32 { + self.base.n_buckets(street) + * if street == Street::Preflop { + 1 + } else { + self.levels + } + } +} diff --git a/arena/exploit/src/cli.rs b/arena/exploit/src/cli.rs new file mode 100644 index 00000000..33777721 --- /dev/null +++ b/arena/exploit/src/cli.rs @@ -0,0 +1,301 @@ +//! `exploit` / `pluribus exploit-compact` CLI body: train a best response to a frozen blueprint checkpoint and measure it. +//! +//! exploit [--compact] --target PATH --sizing local|paper|tiny --buckets DIR|coarse --players 6 --iters N +//! [--threads N] [--mem-gb 20] [--seat S|all] [--eval-deals 20000] [--seed 1] +//! [--translation det|random] [--below check|smallest] [--allin-snap X] [--legacy] +//! [--save-learner FILE | --load-learner FILE] [--eval-seed N] [--audit-handoffs] +//! [--fine LEVELS] [--learner-sizing NAME] [--extract average|argmax] [--lbr-deals N] [--out result.json] +//! +//! Prints one JSON summary on stdout (progress on stderr). Memory: the target is loaded at its +//! file size (index ~29 B + 4 B/slot per infoset); the learner store is capped at `--mem-gb` +//! (default 20) and degrades gracefully (uniform play, flagged `store_full`) rather than +//! aborting. Peak RSS ~ target + `--mem-gb` + a few GB for evaluation. + +use abstraction::tables::BucketTables; +use bench::bp::{BlueprintPolicy, CoarseBucketer}; +use bench::compact::CompactPolicy; +use bench::policy::PolicyFactory; +use blueprint::compact::Compact; +use blueprint::store::Store; +use crate::abr::{AbrConfig, Buck, Exploiter, ExploiterPolicy, Extract}; +use crate::buckets::Refined; +use crate::eval::{est_json, evaluate}; +use crate::game::{ActionSpace, StoreTarget, Target}; +use crate::lbr; +use nlhe::GameConfig; +use bench::bp::TableBucketer; +use std::collections::HashMap; +use std::path::Path; +use std::sync::atomic::Ordering::Relaxed; +use std::sync::Arc; +use std::time::Instant; + +/// Parse `--key value` / `--flag` pairs. +pub fn parse_args(a: &[String]) -> HashMap { + let mut kv: HashMap = HashMap::new(); + let mut i = 0; + while i < a.len() { + let k = a[i].trim_start_matches("--").to_string(); + if i + 1 < a.len() && !a[i + 1].starts_with("--") { + kv.insert(k, a[i + 1].clone()); + i += 2; + } else { + kv.insert(k, "true".into()); + i += 1; + } + } + kv +} + +/// Run the exploiter CLI. `compact`: `--target` is a PLCP1 compact policy (see +/// `pluribus compact`) instead of a PLBP4 checkpoint. +pub fn run(kv: &HashMap, compact: bool) { + let _ = run_json(kv, compact); +} + +/// Like [`run`], returning the JSON summary as well. +pub fn run_json(kv: &HashMap, compact: bool) -> serde_json::Value { + let get = |k: &str, d: &str| kv.get(k).cloned().unwrap_or(d.to_string()); + let Some(target_path) = kv.get("target") else { + eprintln!("usage: exploit --target PATH --sizing NAME --buckets DIR|coarse --players N --iters N [--threads N] [--mem-gb N] [--seat S|all] [--eval-deals N] [--seed N] [--fine L] [--learner-sizing NAME] [--extract average|argmax] [--lbr-deals N] [--save-learner FILE | --load-learner FILE] [--eval-seed N] [--audit-handoffs] [--out FILE]"); + std::process::exit(2); + }; + let players: usize = get("players", "6").parse().expect("players"); + let iters: u64 = get("iters", "100000000").parse().expect("iters"); + let mem_gb: f64 = get("mem-gb", "20").parse().expect("mem-gb"); + let eval_deals: u64 = get("eval-deals", "20000").parse().expect("eval-deals"); + let seed: u64 = get("seed", "1").parse().expect("seed"); + let eval_seed: u64 = get("eval-seed", &(seed ^ 0xE7A1).to_string()).parse().expect("eval-seed"); + assert!(!(kv.contains_key("save-learner") && kv.contains_key("load-learner")), "save-learner and load-learner are mutually exclusive"); + if let Some(path) = kv.get("save-learner") { + assert!(!Path::new(path).exists() && !Path::new(&format!("{path}.json")).exists(), "learner archive already exists; choose a fresh path"); + } + let policy_config = serde_json::json!({ + "players": players, "learner_sizing": get("learner-sizing", &get("sizing", "local")), + "buckets": get("buckets", "data/buckets-200"), "fine": kv.get("fine"), + }); + let saved = kv.get("load-learner").map(|p| { + let meta: serde_json::Value = serde_json::from_slice(&std::fs::read(format!("{p}.json")).expect("read learner metadata")).expect("learner metadata JSON"); + assert_eq!(meta["format"], "sharingan-learner-v1", "unsupported learner archive"); + assert_eq!(meta["policy_config"], policy_config, "learner archive configuration mismatch"); + meta + }); + let threads: usize = get("threads", "0").parse().expect("threads"); + if threads > 0 { + let _ = rayon::ThreadPoolBuilder::new().num_threads(threads).build_global(); + } + let seats: Vec = match get("seat", "all").as_str() { + "all" => (0..players).collect(), + s => vec![s.parse().expect("seat")], + }; + let sizing_name = get("sizing", "local"); + assert!( + ["tiny", "local", "medium", "paper"].contains(&sizing_name.as_str()), + "sizing must be tiny|local|medium|paper" + ); + // The learner may attack with a richer menu than the target's (its bets are translated + // into the target's abstraction): use the same `--learner-sizing` for every target so + // exploitability numbers are comparable across blueprints with different menus. + let learner_sizing_name = get("learner-sizing", &sizing_name); + let sizing = sizing_for(&sizing_name); + let buckets = get("buckets", "data/buckets-200"); + let bucketer: Buck = if buckets == "coarse" { + Arc::new(CoarseBucketer) + } else { + Arc::new(TableBucketer( + BucketTables::load(Path::new(&buckets)).expect("bucket tables"), + )) + }; + let learner_bucketer: Buck = match kv.get("fine") { + Some(l) => Arc::new(Refined::new(bucketer.clone(), l.parse().expect("fine"))), + None => bucketer.clone(), + }; + let track = track_opts(kv); + let extract = if get("extract", "average") == "argmax" { + Extract::Argmax + } else { + Extract::Average + }; + + let t0 = Instant::now(); + eprintln!("loading target {target_path}"); + // Frozen target: a full checkpoint store, or a memory-mapped compact policy (RSS ~ 0; the + // OS page cache holds the hot part, `--warm` reads it all ahead). + let (target, target_pol, target_info): (Arc, Arc, serde_json::Value) = if compact { + let c = Arc::new(Compact::open(Path::new(target_path)).expect("open compact target")); + if kv.contains_key("warm") { + c.warm(); + } else { + c.random_access(); + } + eprintln!("compact target: {} infosets, {:.2} GB ({:.0}s)", c.len(), c.file_bytes() as f64 / 1e9, t0.elapsed().as_secs_f64()); + let info = serde_json::json!({"kind": "compact", "infosets": c.len(), "gb": c.file_bytes() as f64 / 1e9}); + let pol = Arc::new(CompactPolicy::new("target", c.clone(), bucketer.clone(), sizing_for(&sizing_name)).with_opts(track)); + (Arc::new(CompactTarget(c)), pol, info) + } else { + let store: Arc = Arc::new(blueprint::io::load(Path::new(target_path), 0, 0).expect("load target")); + let target_gb = store.bytes_used() as f64 / 1e9; + eprintln!("target: {} infosets, {target_gb:.2} GB used ({:.0}s)", store.infosets(), t0.elapsed().as_secs_f64()); + let info = serde_json::json!({"kind": "store", "infosets": store.infosets(), "gb": target_gb}); + let pol = Arc::new(BlueprintPolicy::new("target", store.clone(), bucketer.clone(), sizing_for(&sizing_name)).with_opts(track)); + (Arc::new(StoreTarget::new(store)), pol, info) + }; + let space: Arc = Arc::new(sizing); + let learner_space: Arc = Arc::new(sizing_for(&learner_sizing_name)); + let cfg = GameConfig::new(players); + let (pol, mut learner_info, provenance) = if let Some(meta) = saved { + let path = kv.get("load-learner").unwrap(); + eprintln!("loading frozen learner {path}; no training"); + let store = Arc::new(blueprint::io::load(Path::new(path), 0, 0).expect("load learner")); + let info = serde_json::json!({"infosets": store.infosets(), "slots": store.used_slots(), "train_secs": 0.0, "nodes": 0}); + (Arc::new(ExploiterPolicy::from_store("exploiter", store, learner_space, learner_bucketer, extract)), info, meta["training"].clone()) + } else { + let ac = AbrConfig::new(cfg, seats.clone(), iters, seed).with_mem_gb(mem_gb); + let ex = Exploiter::new(ac, learner_space, space, target, bucketer.clone(), learner_bucketer).with_track(track); + let t1 = Instant::now(); + let mut last = Instant::now(); + ex.train(|e, t, secs| { + if last.elapsed().as_secs_f64() > 30.0 || t == iters { + last = Instant::now(); + eprintln!("[{secs:>7.0}s] it {t} ({:.1}%) {:.0} it/s | learner infosets {} slots {:.2}G{}", + 100.0 * t as f64 / iters as f64, t as f64 / secs, e.store.infosets(), + e.store.used_slots() as f64 / 1e9, if e.store.is_full() { " FULL" } else { "" }); + } + }); + let info = serde_json::json!({"infosets": ex.store.infosets(), "slots": ex.store.used_slots(), "store_full": ex.store.is_full(), "nodes": ex.nodes.load(Relaxed), "train_secs": t1.elapsed().as_secs_f64()}); + let provenance = serde_json::json!({"target": target_path, "track": format!("{track:?}"), "iters": iters, "seed": seed, "mem_gb": mem_gb, "seats": seats}); + if let Some(path) = kv.get("save-learner") { + // Preserve all streets' average counters without compact-policy quantisation. + blueprint::io::save(&ex.store, Path::new(path)).expect("save learner"); + let meta = serde_json::json!({"format": "sharingan-learner-v1", "policy_config": policy_config, "training": provenance}); + let meta_path = format!("{path}.json"); + let tmp = format!("{meta_path}.tmp"); + std::fs::write(&tmp, serde_json::to_vec_pretty(&meta).unwrap()).expect("save learner metadata"); + std::fs::rename(tmp, meta_path).expect("commit learner metadata"); + } + (ex.policy("exploiter", extract), info, provenance) + }; + let audit = kv.contains_key("audit-handoffs").then(|| Arc::new(crate::audit::HandoffAudit::new(pol.clone(), sizing_for(&sizing_name), track))); + let eval_pol: Arc = match &audit { Some(a) => a.clone(), None => pol.clone() }; + let t2 = Instant::now(); + let r = evaluate( + &cfg, + eval_pol, + target_pol.clone(), + &seats, + eval_deals, + eval_seed, + ); + learner_info["miss_rate"] = serde_json::json!(pol.miss_rate()); + let mut out = serde_json::json!({ + "target": target_path, "players": players, "sizing": sizing_name, "learner_sizing": learner_sizing_name, + "track": format!("{track:?}"), "target_report": target_pol.report(), "iters": if kv.contains_key("load-learner") { 0 } else { iters }, "seats": seats, + "seed": seed, "eval_seed": eval_seed, "loaded_learner": kv.get("load-learner"), "training_provenance": provenance, + "learner": learner_info, + "target_store": target_info, + "exploitation": r.json(), + "eval_secs": t2.elapsed().as_secs_f64(), + }); + if let Some(audit) = audit { out["handoff_audit"] = audit.json(cfg.big_blind as f64); } + if let Some(d) = kv.get("lbr-deals") { + let l = lbr::run( + &cfg, + target_pol, + d.parse().expect("lbr-deals"), + 300, + seed ^ 0x1B2, + ); + out["lbr"] = serde_json::json!({"strong_mbb": est_json(&l.strong.lbr), "weak_mbb": est_json(&l.weak.lbr), "best_mbb": l.best_mbb(), "deals": d}); + } + let s = serde_json::to_string_pretty(&out).unwrap(); + println!("{s}"); + if let Some(p) = kv.get("out") { + std::fs::write(p, &s).unwrap(); + } + out +} + +/// Frozen compact policy as the exploiter's training target (final probabilities, any street). +pub struct CompactTarget(pub Arc); + +impl Target for CompactTarget { + #[inline] + fn probs(&self, _st: &nlhe::State, hist: u64, bucket: u32, out: &mut [f32]) -> bool { + self.0.probs(hist, bucket, out) + } +} + +fn sizing_for(name: &str) -> nlhe::abstraction::BetSizing { + bench::bp::sizing_by_name(name).expect("sizing") +} + +/// Target translation options from `--translation det|random`, `--below check|smallest`, +/// `--allin-snap X`, `--legacy` (pre-fix tracking), on top of `TrackOpts::default()`. +pub fn track_opts(kv: &HashMap) -> nlhe::abstraction::TrackOpts { + use nlhe::abstraction::{BelowMenu, TrackOpts, Translation}; + if kv.contains_key("legacy") { + return TrackOpts::LEGACY; + } + let mut o = if kv.contains_key("pre-sync-fix") { TrackOpts::PRE_SYNC_FIX } else { TrackOpts::default() }; + match kv.get("translation").map(String::as_str) { + None | Some("det") => {} + Some("random") => o.translation = Translation::Random, + Some(x) => panic!("unknown --translation {x}"), + } + match kv.get("below").map(String::as_str) { + None => {} + Some("check") => o.below = BelowMenu::Check, + Some("smallest") => o.below = BelowMenu::Smallest, + Some(x) => panic!("unknown --below {x}"), + } + if let Some(v) = kv.get("allin-snap") { + o.allin_snap = v.parse().expect("allin-snap"); + } + o +} + +#[cfg(test)] +mod archive_tests { + use super::*; + + #[test] + fn frozen_learner_replays_exactly_and_rejects_wrong_abstraction() { + let dir = std::env::temp_dir().join(format!("exploiter-archive-{}-{}", std::process::id(), std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos())); + std::fs::create_dir(&dir).unwrap(); + let target = dir.join("target.bin"); + blueprint::io::save(&Store::new(16), &target).unwrap(); + let learner = dir.join("learner.bin"); + let mut args = HashMap::from([ + ("target".into(), target.display().to_string()), + ("players".into(), "2".into()), ("sizing".into(), "tiny".into()), + ("buckets".into(), "coarse".into()), ("iters".into(), "32".into()), + ("threads".into(), "1".into()), ("mem-gb".into(), "0.001".into()), + ("eval-deals".into(), "100".into()), ("seed".into(), "17".into()), + ("eval-seed".into(), "999".into()), + ("save-learner".into(), learner.display().to_string()), + ]); + let trained = run_json(&args, false); + assert!(trained["learner"]["infosets"].as_u64().unwrap() > 0); + assert!(trained["learner"]["miss_rate"].as_f64().unwrap() < 1.0, "evaluation must exercise learned entries"); + args.remove("save-learner"); + args.insert("load-learner".into(), learner.display().to_string()); + // Loading must skip training, even if a nonzero budget is supplied. + args.insert("iters".into(), "999999999".into()); + let restored = run_json(&args, false); + assert_eq!(trained["exploitation"], restored["exploitation"]); + assert_eq!(trained["training_provenance"], restored["training_provenance"]); + assert_eq!(restored["iters"], 0); + assert_eq!(restored["learner"]["nodes"], 0); + assert_eq!(restored["eval_seed"], 999); + assert_eq!(trained["learner"]["miss_rate"], restored["learner"]["miss_rate"]); + + // These inputs define the learner's infosets and must not silently change. + for (key, wrong) in [("players", "3"), ("learner-sizing", "medium"), ("buckets", "wrong-tables"), ("fine", "8")] { + let mut incompatible = args.clone(); + incompatible.insert(key.into(), wrong.into()); + assert!(std::panic::catch_unwind(|| run_json(&incompatible, false)).is_err(), "accepted incompatible {key}"); + } + // Remove only this test's own artifacts. + std::fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/arena/exploit/src/eval.rs b/arena/exploit/src/eval.rs new file mode 100644 index 00000000..48fb0456 --- /dev/null +++ b/arena/exploit/src/eval.rs @@ -0,0 +1,75 @@ +//! Independent evaluation of an exploiter: duplicate match (exploiter vs copies of the target) +//! through `bench::matchrun` with full AIVAT, every deal replayed with the exploiter in each +//! requested seat. Results are in mbb/game, positive = the exploiter wins = target exploitable. + +use bench::matchrun::{run_match, AivatMode, MatchSpec, Seatings}; +use bench::policy::PolicyFactory; +use bench::stats::Est; +use nlhe::GameConfig; +use std::sync::Arc; + +#[derive(Clone, Debug)] +pub struct Exploitation { + /// AIVAT estimate per seat the exploiter sat in (`None` = not evaluated). + pub by_seat: Vec>, + /// AIVAT estimate averaged over the evaluated seats (the exploitation figure). + pub avg: Est, + /// Same without AIVAT. + pub raw: Est, + pub deals: u64, +} + +pub fn est_json(e: &Est) -> serde_json::Value { + serde_json::json!({"mbb": e.mbb, "ci95": 1.96 * e.se, "n": e.n}) +} + +impl Exploitation { + pub fn json(&self) -> serde_json::Value { + serde_json::json!({ + "avg_mbb": est_json(&self.avg), + "raw_avg_mbb": est_json(&self.raw), + "by_seat": self.by_seat.iter().map(|s| s.as_ref().map(est_json)).collect::>(), + "deals": self.deals, + }) + } +} + +/// Seatings with the exploiter (entrant 0) in each of `seats` against `players - 1` target copies. +pub fn seatings(players: usize, seats: &[usize]) -> Seatings { + Seatings( + seats + .iter() + .map(|&h| (0..players).map(|s| usize::from(s != h)).collect()) + .collect(), + ) +} + +pub fn evaluate( + cfg: &GameConfig, + exploiter: Arc, + target: Arc, + seats: &[usize], + deals: u64, + seed: u64, +) -> Exploitation { + let mut spec = MatchSpec::new( + *cfg, + vec![exploiter, target], + seatings(cfg.players, seats), + deals, + seed, + ); + spec.aivat = AivatMode::Full; + let r = run_match(&spec); + let e = &r.entrants[0]; + Exploitation { + by_seat: e + .by_seat + .iter() + .map(|s| s.as_ref().and_then(|s| s.aivat)) + .collect(), + avg: e.aivat.unwrap_or(e.raw), + raw: e.raw, + deals, + } +} diff --git a/arena/exploit/src/game.rs b/arena/exploit/src/game.rs new file mode 100644 index 00000000..6847a556 --- /dev/null +++ b/arena/exploit/src/game.rs @@ -0,0 +1,106 @@ +//! The abstract game the exploiter plays and the frozen strategy it plays against. +//! +//! - [`ActionSpace`]: the legal abstract actions at a node (`BetSizing` for real blueprints, +//! [`PushFold`] for the exact-equilibrium sanity game). +//! - [`Target`]: the frozen opponent strategy used while *training* (sampled, never updated). +//! [`StoreTarget`] reads a blueprint `Store` exactly as `bench::bp::BlueprintPolicy` does +//! (average strategy preflop, regret-matching current strategy postflop; unknown infosets +//! use the configured fallback in the caller), so training and duplicate evaluation see the same opponent. + +use blueprint::store::Store; +use nlhe::abstraction::{abstract_actions, translate_deterministic, ActionList, BetSizing}; +use nlhe::{Action, State, Street}; +use std::sync::Arc; + +pub trait ActionSpace: Send + Sync { + /// Abstract actions at the (non-terminal) node `st`. + fn actions(&self, st: &State, out: &mut ActionList); + /// Index in `list` of a concrete action observed at `pre` (translation for off-tree bets). + fn index_of(&self, pre: &State, list: &ActionList, a: Action) -> usize { + match a { + Action::Fold => list.as_slice().iter().position(|x| *x == Action::Fold), + Action::Check | Action::Call => list + .as_slice() + .iter() + .position(|x| matches!(x, Action::Check | Action::Call)), + Action::RaiseTo(t) => Some(translate_deterministic(pre, list, t)), + } + .unwrap_or(0) + } +} + +impl ActionSpace for BetSizing { + fn actions(&self, st: &State, out: &mut ActionList) { + abstract_actions(st, self, out) + } +} + +/// Heads-up push/fold: the first actor either folds or shoves; the other folds or calls. +/// (No limps, no min-raises: the game ends preflop, so it has an exact 169-class solution.) +pub struct PushFold; + +impl ActionSpace for PushFold { + fn actions(&self, st: &State, out: &mut ActionList) { + out.clear(); + let l = st.legal(); + if l.can_fold { + out.push(Action::Fold); + } + if st.raises_this_street() == 0 && l.can_raise { + out.push(Action::RaiseTo(l.max_raise_to)); + } else { + out.push(if l.can_check { + Action::Check + } else { + Action::Call + }); + } + } + fn index_of(&self, _pre: &State, list: &ActionList, a: Action) -> usize { + match a { + Action::Fold => 0, + _ => list.len() - 1, + } + } +} + +/// A frozen opponent strategy at abstract nodes. +pub trait Target: Send + Sync { + /// Fill `out` (length = number of abstract actions) with the target's distribution at the + /// node (`st`, history key `hist`) for card bucket `bucket`. Returns false when the target + /// has no entry (the caller then uses the same configured fallback as `BlueprintPolicy`). + fn probs(&self, st: &State, hist: u64, bucket: u32, out: &mut [f32]) -> bool; +} + +pub struct StoreTarget { + pub store: Arc, + pub avg_preflop: bool, +} + +impl StoreTarget { + pub fn new(store: Arc) -> Self { + StoreTarget { + store, + avg_preflop: true, + } + } +} + +impl Target for StoreTarget { + #[inline] + fn probs(&self, st: &State, hist: u64, bucket: u32, out: &mut [f32]) -> bool { + let Some(slot) = self + .store + .lookup(hist, bucket) + .filter(|s| s.n_actions as usize == out.len()) + else { + return false; + }; + if self.avg_preflop && st.street() == Street::Preflop { + self.store.average(slot, out); + } else { + self.store.strategy(slot, out); + } + true + } +} diff --git a/arena/exploit/src/lbr.rs b/arena/exploit/src/lbr.rs new file mode 100644 index 00000000..b69bb6ad --- /dev/null +++ b/arena/exploit/src/lbr.rs @@ -0,0 +1,48 @@ +//! Strong LBR: `bench::lbr` (Bayes range tracking + greedy local best response) with a richer +//! bet menu and more Monte Carlo samples than the default. HU = the Lisy-Bowling bound; +//! n > 2 players = "profile LBR" (one deviator vs n-1 copies of the policy; not an +//! equilibrium-gap bound). The bound is also reported for the default config so the gain from +//! the richer menu is visible. See RESULTS.md for what is *not* done (exact river BR). + +use bench::lbr::{run_lbr, LbrConfig, LbrReport}; +use bench::policy::PolicyFactory; +use nlhe::GameConfig; +use std::sync::Arc; + +/// bench's default: {0.5 pot, 1 pot, all-in}, 300 samples. +pub fn weak_config() -> LbrConfig { + LbrConfig::default() +} + +/// Eight pot fractions (+ all-in) and `samples` rollouts per decision. +pub fn strong_config(samples: usize) -> LbrConfig { + LbrConfig { + samples, + fracs: vec![0.25, 0.4, 0.6, 0.8, 1.0, 1.5, 2.0, 3.0], + } +} + +pub struct LbrPair { + pub weak: LbrReport, + pub strong: LbrReport, +} + +impl LbrPair { + /// The better (larger) of the two lower bounds, in mbb/game. + pub fn best_mbb(&self) -> f64 { + self.weak.lbr.mbb.max(self.strong.lbr.mbb) + } +} + +pub fn run( + cfg: &GameConfig, + target: Arc, + deals: u64, + samples: usize, + seed: u64, +) -> LbrPair { + LbrPair { + weak: run_lbr(cfg, &weak_config(), target.clone(), deals, seed), + strong: run_lbr(cfg, &strong_config(samples), target, deals, seed), + } +} diff --git a/arena/exploit/src/lib.rs b/arena/exploit/src/lib.rs new file mode 100644 index 00000000..94295901 --- /dev/null +++ b/arena/exploit/src/lib.rs @@ -0,0 +1,80 @@ +//! The strongest adversary we can build against a frozen blueprint: an opponent-independent +//! measure of how exploitable the bot is. +//! +//! - [`abr`]: trained best response (external-sampling MCCFR learner vs frozen target). +//! - [`eval`]: duplicate + AIVAT match of the exploiter vs target copies, per seat. +//! - [`lbr`]: strong LBR (wraps `bench::lbr`). +//! - [`pushfold`]: exact heads-up push/fold equilibrium (169 classes) for validation. +//! - [`game`]: action spaces and the frozen-target interface. +//! +//! Seeding: every random stream is derived per item (iteration, deal) via `bench::mix`. + +pub mod abr; +pub mod audit; +pub mod buckets; +pub mod cli; +pub mod eval; +pub mod game; +pub mod lbr; +pub mod pushfold; + +use bench::bp::BlueprintPolicy; +use blueprint::store::Store; +use blueprint::trainer::Bucketer; +use game::StoreTarget; +use nlhe::abstraction::BetSizing; +use std::sync::Arc; + +/// The (training-time target, evaluation-time policy) pair for a blueprint store. +pub fn blueprint_target( + name: &str, + store: Arc, + bucketer: Arc, + sizing: BetSizing, +) -> (Arc, Arc) { + ( + Arc::new(StoreTarget::new(store.clone())), + Arc::new(BlueprintPolicy::new(name, store, bucketer, sizing)), + ) +} + +/// Train a small paper-style blueprint for tests and demos: heads-up or n-player, `tiny` +/// sizing, coarse buckets, Linear CFR; preflop uses the average φ and postflop the average of +/// 5 strategy snapshots over the second half of training (exported in place, so regret matching +/// on the returned store reproduces the blueprint, exactly as for real checkpoints). +pub fn train_blueprint(players: usize, iters: u64, seed: u64) -> Arc { + use blueprint::trainer::{Schedule, Trainer}; + let sched = Schedule { + discount_interval: (iters / 100).max(10), + lcfr_until: iters / 3, + prune_after: u64::MAX, + prune_prob: 0.0, + prune_threshold: -3_000_000, + strategy_interval: 10, + avg_after: 0, + }; + let tr = Trainer::new( + nlhe::GameConfig::new(players), + BetSizing::tiny(), + sched, + &bench::bp::CoarseBucketer, + 1 << 24, + seed, + ); + let path = std::env::temp_dir().join(format!( + "exploit_snap_{}_{players}_{iters}_{seed}.bin", + std::process::id() + )); + let _ = std::fs::remove_file(&path); + tr.run(0, iters / 2, |_, _, _| {}); + let mut prev = iters / 2; + for k in 1..=5u64 { + let next = iters / 2 + (iters - iters / 2) * k / 5; + tr.run(prev, next, |_, _, _| {}); + prev = next; + blueprint::snapshot::accumulate(&tr.store, &path).expect("snapshot"); + } + blueprint::snapshot::export_in_place(&tr.store, Some(&path)).expect("export"); + let _ = std::fs::remove_file(&path); + tr.store +} diff --git a/arena/exploit/src/main.rs b/arena/exploit/src/main.rs new file mode 100644 index 00000000..0b1656de --- /dev/null +++ b/arena/exploit/src/main.rs @@ -0,0 +1,10 @@ +//! `exploit` CLI: train a best response to a frozen blueprint checkpoint and measure it. +//! See [`exploit::cli`] for the options; `--compact` treats `--target` as a PLCP1 compact +//! policy (the same entry point backs `pluribus exploit-compact`). + +fn main() { + let a: Vec = std::env::args().skip(1).collect(); + let kv = exploit::cli::parse_args(&a); + let compact = kv.contains_key("compact"); + exploit::cli::run(&kv, compact); +} diff --git a/arena/exploit/src/pushfold.rs b/arena/exploit/src/pushfold.rs new file mode 100644 index 00000000..2162dea6 --- /dev/null +++ b/arena/exploit/src/pushfold.rs @@ -0,0 +1,287 @@ +//! Exact heads-up push/fold equilibrium on the 169 preflop classes, used to validate the +//! exploiter: against the converged equilibrium it must win ~0, against a perturbed copy a lot. +//! +//! Game: SB (seat 0) folds (-sb) or shoves; BB folds (-bb) or calls for the whole stack; +//! showdown on a random board. The payoff matrix is `E[i][j]` = SB equity (ties split) of class +//! `i` vs class `j`, weighted by the number of disjoint hole-card pairs `W[i][j]`. Equities are +//! Monte Carlo (seeded per cell, `samples` boards each); the matrix game is then solved by CFR+ +//! to numerical exactness and its exact exploitability is reported, so the *target* is an +//! equilibrium of the matrix game up to the equity noise (documented in RESULTS.md). + +use crate::game::Target; +use bench::mix; +use bench::policy::{Dist, Player, PolicyFactory, View}; +use cards::{all_holes, bit, evaluate, mask_of, preflop_class, Card, Rng}; +use nlhe::{Action, GameConfig, State}; +use rayon::prelude::*; +use std::sync::Arc; + +pub const CLASSES: usize = 169; + +/// Heads-up game config used by the push/fold tests (`stack` chips, blinds 50/100). +pub fn config(stack: i32) -> GameConfig { + let mut g = GameConfig::new(2); + g.stack = stack; + g +} + +pub struct Matrix { + pub stack: f64, + pub sb: f64, + pub bb: f64, + /// Disjoint hole-pair counts. + pub w: Vec, + /// SB equity of row class vs column class. + pub eq: Vec, +} + +impl Matrix { + /// Equity matrix by Monte Carlo, `samples` random boards per unordered class pair. + pub fn compute(stack: i32, samples: u32, seed: u64) -> Matrix { + let holes = all_holes(); + let mut combos: Vec> = vec![vec![]; CLASSES]; + for h in &holes { + combos[preflop_class(h[0], h[1])].push(*h); + } + let mut w = vec![0.0; CLASSES * CLASSES]; + for a in &holes { + for b in &holes { + if (bit(a[0]) | bit(a[1])) & (bit(b[0]) | bit(b[1])) == 0 { + w[preflop_class(a[0], a[1]) * CLASSES + preflop_class(b[0], b[1])] += 1.0; + } + } + } + let cells: Vec<(usize, usize)> = (0..CLASSES) + .flat_map(|i| (i..CLASSES).map(move |j| (i, j))) + .collect(); + let vals: Vec = cells + .par_iter() + .map(|&(i, j)| { + let mut rng = Rng::new(mix(seed, (i * CLASSES + j) as u64)); + let (mut tot, mut n) = (0.0, 0u32); + while n < samples { + let a = combos[i][rng.below(combos[i].len() as u32) as usize]; + let b = combos[j][rng.below(combos[j].len() as u32) as usize]; + let (ma, mb) = (bit(a[0]) | bit(a[1]), bit(b[0]) | bit(b[1])); + if ma & mb != 0 { + continue; + } + let mut board = 0; + for _ in 0..5 { + board |= bit(rng.draw(ma | mb | board)); + } + let (ra, rb) = (evaluate(ma | board), evaluate(mb | board)); + tot += if ra > rb { + 1.0 + } else if ra == rb { + 0.5 + } else { + 0.0 + }; + n += 1; + } + tot / samples as f64 + }) + .collect(); + let mut eq = vec![0.5; CLASSES * CLASSES]; + for (&(i, j), &v) in cells.iter().zip(&vals) { + eq[i * CLASSES + j] = v; + eq[j * CLASSES + i] = 1.0 - v; + } + let _ = mask_of; + let g = config(stack); + Matrix { + stack: stack as f64, + sb: g.small_blind as f64, + bb: g.big_blind as f64, + w, + eq, + } + } + + /// SB payoff when class `i` shoves and class `j` calls. + #[inline] + fn call_val(&self, i: usize, j: usize) -> f64 { + (2.0 * self.eq[i * CLASSES + j] - 1.0) * self.stack + } + + /// Counterfactual values (unnormalised by joint weight): SB shove per class vs call + /// strategy `c`; BB call/fold per class vs shove strategy `s`. + fn sb_shove(&self, c: &[f64]) -> Vec { + (0..CLASSES) + .map(|i| { + (0..CLASSES) + .map(|j| { + self.w[i * CLASSES + j] + * ((1.0 - c[j]) * self.bb + c[j] * self.call_val(i, j)) + }) + .sum() + }) + .collect() + } + fn sb_fold(&self) -> Vec { + (0..CLASSES) + .map(|i| -self.sb * (0..CLASSES).map(|j| self.w[i * CLASSES + j]).sum::()) + .collect() + } + /// BB payoff (negated SB payoff) of calling / folding per class vs shove strategy `s`. + fn bb_call(&self, s: &[f64]) -> Vec { + (0..CLASSES) + .map(|j| { + (0..CLASSES) + .map(|i| { + self.w[i * CLASSES + j] + * (s[i] * -self.call_val(i, j) + (1.0 - s[i]) * self.sb) + }) + .sum() + }) + .collect() + } + fn bb_fold(&self, s: &[f64]) -> Vec { + (0..CLASSES) + .map(|j| { + (0..CLASSES) + .map(|i| self.w[i * CLASSES + j] * (s[i] * -self.bb + (1.0 - s[i]) * self.sb)) + .sum() + }) + .collect() + } + + fn total(&self) -> f64 { + self.w.iter().sum() + } + + /// Exact exploitability of (s, c): (BR_SB(c) + BR_BB(s)) / 2 in mbb/game, plus the SB value. + pub fn exploitability_mbb(&self, s: &[f64], c: &[f64]) -> f64 { + let (sh, fo) = (self.sb_shove(c), self.sb_fold()); + let br_sb: f64 = (0..CLASSES).map(|i| sh[i].max(fo[i])).sum::() / self.total(); + let (ca, fb) = (self.bb_call(s), self.bb_fold(s)); + let br_bb: f64 = (0..CLASSES).map(|j| ca[j].max(fb[j])).sum::() / self.total(); + (br_sb + br_bb) / 2.0 / self.bb * 1000.0 + } + + /// Solve by CFR+ (alternating-free, linear averaging). Returns (shove prob, call prob) per class. + pub fn solve(&self, iters: usize) -> Strategy { + let mut rs = vec![[0.0f64; 2]; CLASSES]; // SB regrets [fold, shove] + let mut rb = vec![[0.0f64; 2]; CLASSES]; // BB regrets [fold, call] + let (mut ss, mut sc) = (vec![0.0; CLASSES], vec![0.0; CLASSES]); + let (mut ws, mut wc) = (0.0, 0.0); + let fo = self.sb_fold(); + let rm = |r: &[f64; 2]| { + let p = r[1].max(0.0); + let t = r[0].max(0.0) + p; + if t > 0.0 { + p / t + } else { + 0.5 + } + }; + for t in 1..=iters { + let s: Vec = rs.iter().map(rm).collect(); + let c: Vec = rb.iter().map(rm).collect(); + let sh = self.sb_shove(&c); + let (ca, fb) = (self.bb_call(&s), self.bb_fold(&s)); + for i in 0..CLASSES { + let v = s[i] * sh[i] + (1.0 - s[i]) * fo[i]; + rs[i][0] = (rs[i][0] + fo[i] - v).max(0.0); + rs[i][1] = (rs[i][1] + sh[i] - v).max(0.0); + let v = c[i] * ca[i] + (1.0 - c[i]) * fb[i]; + rb[i][0] = (rb[i][0] + fb[i] - v).max(0.0); + rb[i][1] = (rb[i][1] + ca[i] - v).max(0.0); + } + let wt = t as f64; + for i in 0..CLASSES { + ss[i] += wt * s[i]; + sc[i] += wt * c[i]; + } + ws += wt; + wc += wt; + } + Strategy { + shove: ss.iter().map(|x| x / ws).collect(), + call: sc.iter().map(|x| x / wc).collect(), + } + } +} + +#[derive(Clone, Debug)] +pub struct Strategy { + /// SB shove probability per preflop class. + pub shove: Vec, + /// BB call probability per preflop class. + pub call: Vec, +} + +impl Strategy { + /// Blend towards "always shove / never call" by `m` (a deliberately exploitable copy). + pub fn perturbed(&self, m: f64) -> Strategy { + Strategy { + shove: self.shove.iter().map(|x| (1.0 - m) * x + m).collect(), + call: self.call.iter().map(|x| (1.0 - m) * x).collect(), + } + } + /// Probability that SB shoves, weighted over the hands dealt. + pub fn shove_freq(&self, m: &Matrix) -> f64 { + let t = m.total(); + (0..CLASSES) + .map(|i| self.shove[i] * (0..CLASSES).map(|j| m.w[i * CLASSES + j]).sum::()) + .sum::() + / t + } +} + +/// The push/fold strategy as a frozen training target and as a playable policy. +pub struct PushFoldPolicy { + pub name: String, + pub strat: Strategy, +} + +impl Target for PushFoldPolicy { + fn probs(&self, st: &State, _hist: u64, bucket: u32, out: &mut [f32]) -> bool { + let p = if st.raises_this_street() == 0 { + self.strat.shove[bucket as usize] + } else { + self.strat.call[bucket as usize] + } as f32; + out[0] = 1.0 - p; + out[1] = p; + true + } +} + +impl PolicyFactory for PushFoldPolicy { + fn name(&self) -> String { + self.name.clone() + } + fn new_player(&self, _seat: usize, _cfg: &GameConfig, _seed: u64) -> Box { + Box::new(PushFoldPlayer(self.strat.clone())) + } +} + +struct PushFoldPlayer(Strategy); + +impl Player for PushFoldPlayer { + fn dist(&mut self, v: &View, hole: [Card; 2]) -> Dist { + let c = preflop_class(hole[0], hole[1]); + let l = v.state.legal(); + let mut d = Dist::new(); + if v.state.raises_this_street() == 0 && l.can_raise { + d.push(Action::Fold, (1.0 - self.0.shove[c]) as f32); + d.push(Action::RaiseTo(l.max_raise_to), self.0.shove[c] as f32); + } else { + d.push(Action::Fold, (1.0 - self.0.call[c]) as f32); + d.push(Action::Call, self.0.call[c] as f32); + } + d + } + fn fork(&self) -> Option> { + Some(Box::new(PushFoldPlayer(self.0.clone()))) + } +} + +pub fn arc(name: &str, strat: Strategy) -> Arc { + Arc::new(PushFoldPolicy { + name: name.into(), + strat, + }) +} diff --git a/arena/exploit/tests/curve.rs b/arena/exploit/tests/curve.rs new file mode 100644 index 00000000..7cefd2b0 --- /dev/null +++ b/arena/exploit/tests/curve.rs @@ -0,0 +1,98 @@ +//! The key deliverable: exploitability of a heads-up blueprint falls as the blueprint trains +//! (1k -> 30k -> 300k iterations), measured by trained best responses (duplicate + AIVAT) and, +//! on the same targets, by LBR. Prints the table used in RESULTS.md. +//! +//! Two exploiters: `same` (target's buckets and menu) and `fine` (hand-strength-refined buckets +//! and a bigger bet menu, translated into the target's menu). + +use bench::bp::CoarseBucketer; +use exploit::abr::{AbrConfig, Buck, Exploiter, Extract}; +use exploit::buckets::Refined; +use exploit::eval::evaluate; +use exploit::game::ActionSpace; +use exploit::{blueprint_target, lbr, train_blueprint}; +use nlhe::abstraction::{BetSizing, Menu}; +use nlhe::GameConfig; +use std::sync::Arc; +use std::time::Instant; + +fn env(name: &str, d: u64) -> u64 { + std::env::var(name) + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(d) +} + +fn fine_menu() -> BetSizing { + let t = [Menu::new(&[0.33, 0.66, 1.0, 1.5], true)]; + BetSizing::new([&t, &t, &t, &t], [3, 3, 3, 3]) +} + +#[test] +fn exploitability_decreases_with_blueprint_training() { + let cfg = GameConfig::new(2); + let b: Buck = Arc::new(CoarseBucketer); + let fine_b: Buck = Arc::new(Refined::new(b.clone(), 12)); + let tiny: Arc = Arc::new(BetSizing::tiny()); + let big: Arc = Arc::new(fine_menu()); + let (abr_iters, deals, lbr_deals) = ( + env("ABR_ITERS", 150_000), + env("EVAL_DEALS", 15_000), + env("LBR_DEALS", 300), + ); + println!( + "{:>8} | {:>17} | {:>17} | {:>17} | {:>17}", + "bp iters", "ABR same", "ABR fine", "strong LBR", "weak LBR" + ); + let mut rows = vec![]; + for bp_iters in [1_000u64, 30_000, 300_000] { + let store = train_blueprint(2, bp_iters, 11); + let (target, pol) = blueprint_target("toy", store, b.clone(), BetSizing::tiny()); + let mut res = vec![]; + for (space, lb, iters) in [ + (tiny.clone(), b.clone(), abr_iters), + (big.clone(), fine_b.clone(), env("FINE_ITERS", 50_000)), + ] { + let t = Instant::now(); + let mut c = AbrConfig::new(cfg, vec![0, 1], iters, 5); + c.capacity = 1 << 24; + c.max_infosets = 1 << 21; + let ex = Exploiter::new(c, space, tiny.clone(), target.clone(), b.clone(), lb); + ex.train(|_, _, _| {}); + let secs = t.elapsed().as_secs_f32(); + let ep = ex.policy("abr", Extract::Average); + let r = evaluate(&cfg, ep.clone(), pol.clone(), &[0, 1], deals, 1234); + eprintln!( + " abr {secs:.1}s, {} infosets, miss rate {:.3}", + ex.store.infosets(), + ep.miss_rate() + ); + res.push(r.avg); + } + let l = lbr::run(&cfg, pol, lbr_deals, 300, 77); + println!( + "{bp_iters:>8} | {:>17} | {:>17} | {:>17} | {:>17}", + res[0].to_string(), + res[1].to_string(), + l.strong.lbr.to_string(), + l.weak.lbr.to_string() + ); + rows.push((res, l)); + } + // Abstract-game exploitability (the exploiter sees what the target sees) falls as the + // blueprint converges. The fine exploiter additionally exploits the target's *abstraction* + // (9 hand-category buckets), which more training cannot remove, so it is not monotone. + let a: Vec = rows.iter().map(|r| r.0[0].mbb).collect(); + assert!( + a[0] > a[1] && a[1] > a[2], + "exploitability must fall as the target trains: {a:?}" + ); + for (e, l) in &rows { + let best = e[0].mbb.max(e[1].mbb); + assert!( + best + 1.96 * e[0].se >= l.best_mbb() - 1.96 * l.strong.lbr.se, + "exploiter {best} < LBR {}", + l.best_mbb() + ); + } +} diff --git a/arena/exploit/tests/pushfold.rs b/arena/exploit/tests/pushfold.rs new file mode 100644 index 00000000..de3c876c --- /dev/null +++ b/arena/exploit/tests/pushfold.rs @@ -0,0 +1,72 @@ +//! Sanity: exploiter vs the exact push/fold equilibrium (~0) and vs a perturbed copy (large). + +use bench::bp::CoarseBucketer; +use exploit::abr::{AbrConfig, Exploiter, Extract}; +use exploit::eval::evaluate; +use exploit::game::{ActionSpace, PushFold}; +use exploit::pushfold::{self, Matrix}; +use std::sync::Arc; +use std::time::Instant; + +fn train_and_eval( + strat: pushfold::Strategy, + name: &str, + stack: i32, + iters: u64, + deals: u64, +) -> (f64, f64) { + let target = pushfold::arc(name, strat); + let cfg = pushfold::config(stack); + let b: exploit::abr::Buck = Arc::new(CoarseBucketer); + let mut c = AbrConfig::new(cfg, vec![0, 1], iters, 7); + c.capacity = 1 << 16; + c.max_infosets = 1 << 12; + let sp: Arc = Arc::new(PushFold); + let ex = Exploiter::new(c, sp.clone(), sp, target.clone(), b.clone(), b); + ex.train(|_, _, _| {}); + let pol = ex.policy("abr", Extract::Average); + let r = evaluate(&cfg, pol, target, &[0, 1], deals, 99); + println!( + "{name}: exploiter wins {} mbb/g (raw {}) by seat {:?}", + r.avg, + r.raw, + r.by_seat + .iter() + .map(|s| s.map(|e| e.mbb.round())) + .collect::>() + ); + (r.avg.mbb, 1.96 * r.avg.se) +} + +#[test] +fn exploiter_is_zero_vs_equilibrium_and_large_vs_perturbed() { + let t = Instant::now(); + let stack = 1000; // 10 bb: shove ranges are wide and non-trivial + let m = Matrix::compute(stack, 25_000, 1); + println!("equity matrix {:.1}s", t.elapsed().as_secs_f32()); + let eq = m.solve(20_000); + let exact = m.exploitability_mbb(&eq.shove, &eq.call); + let bad = eq.perturbed(0.4); + let exact_bad = m.exploitability_mbb(&bad.shove, &bad.call); + println!( + "shove freq {:.3}; exact exploitability: eq {exact:.6} mbb, perturbed {exact_bad:.1} mbb", + eq.shove_freq(&m) + ); + assert!(exact < 0.5, "CFR+ should solve the matrix game: {exact}"); + assert!(exact_bad > 100.0); + + let (z, zci) = train_and_eval(eq, "equilibrium", stack, 400_000, 200_000); + let (p, pci) = train_and_eval(bad, "perturbed", stack, 400_000, 200_000); + println!("total {:.1}s", t.elapsed().as_secs_f32()); + // Equilibrium: measured exploitation within noise + equity-matrix MC error of the exact value. + assert!( + z.abs() < 25.0, + "exploiter wins {z} +- {zci} vs equilibrium (exact {exact})" + ); + // Perturbed: large, and close to the exact exploitability of the perturbed strategy. + assert!( + p > 0.7 * exact_bad - pci, + "exploiter wins {p} +- {pci}, exact {exact_bad}" + ); + assert!(p > 10.0 * z.abs()); +} diff --git a/arena/openpoker/Cargo.toml b/arena/openpoker/Cargo.toml new file mode 100644 index 00000000..945a8dac --- /dev/null +++ b/arena/openpoker/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "openpoker" +edition.workspace = true +version.workspace = true +description = "Live external 6-max evaluation on Open Poker (openpoker.ai): protocol client, nlhe replay, action mapping, trace + analyzer." + +[lib] +name = "openpoker" +path = "src/lib.rs" + +[[bin]] +name = "openpoker" +path = "src/main.rs" + +[dependencies] +cards.workspace = true +serde.workspace = true +serde_json.workspace = true +nlhe = { path = "../../engine/nlhe" } +bench = { path = "../../arena/bench" } +search = { path = "../../sharingan-1/search" } +blueprint = { path = "../../sharingan-1/blueprint" } +abstraction = { path = "../../sharingan-1/abstraction" } +rayon.workspace = true +tungstenite = { version = "0.24", features = ["rustls-tls-webpki-roots"] } +ureq = { version = "2.10", features = ["json"] } diff --git a/arena/openpoker/README.md b/arena/openpoker/README.md new file mode 100644 index 00000000..fd810587 --- /dev/null +++ b/arena/openpoker/README.md @@ -0,0 +1,153 @@ +# openpoker: live 6-max evaluation on Open Poker + +Plays our bench policies (the compact blueprint, or built-ins for smoke tests) on +[Open Poker](https://openpoker.ai), a free 6-max bot arena (WebSocket JSON, blinds 10/20, buy-in +1,000-5,000 chips, other developers' bots as opponents). Every decision is traced; a history +analyzer turns traces into bb/100 with confidence intervals and an all-in-luck adjustment. + +**Everything here runs on the dev box, never on the Mac** (`scripts/dev.sh`, see below). Do not +run large live sessions without a human deciding to. + +## Setup (once) + +Get an API key from Open Poker and keep it out of the repo. Put it in an env file with mode 600 +(`OPENPOKER_API_KEY=...`), never commit it and never print it: + +```bash +scp -o IdentitiesOnly=yes my-openpoker.env ubuntu@$PLURIBUS_DEV_HOST:~/pluribus/.env.openpoker +ssh ubuntu@$PLURIBUS_DEV_HOST 'chmod 600 ~/pluribus/.env.openpoker' +``` + +`openpoker` reads `OPENPOKER_API_KEY` from the environment, else from `--env FILE`, else +`./.env.openpoker`, `~/pluribus/.env.openpoker`, `./.env`. `scripts/dev.sh` rsyncs the workspace +without `--delete`, so the file survives syncs. + +## Build and test (dev box) + +```bash +DEV_TARGET=openpoker scripts/dev.sh run 'cargo test --release -p openpoker' +DEV_TARGET=openpoker scripts/dev.sh run 'cargo build --release -p openpoker' +``` + +34 tests: protocol parsing, layout/seat rotation, action-mapping legality fuzz (200k random +offered-sets), replay of hand-crafted and **real recorded messages** +(`tests/fixtures/smoke_raw.jsonl`, a 10-hand live session replayed bit-exactly), session edge +cases (duplicate turns, rejects, resync, bust/rebuy, mid-hand joins), all-in equity, analyzer math. + +## Run + +```bash +B=target/openpoker/release/openpoker +# smoke: <= 10 hands with a built-in +$B live --policy builtin:tag --hands 10 --buy-in 2000 --timeout-sec 600 --trace logs/openpoker-smoke.jsonl +# the blueprint (compact file from the eval pipeline), 100 bb buy-in +nohup $B live --policy compact:data/eval/B/compact.plcp --sizing paper --buckets data/buckets-200 \ + --hands 10000 --buy-in 2000 --timeout-sec 86400 --trace logs/openpoker-B.jsonl > logs/openpoker-B.out 2>&1 & +# analysis of any trace (also works while a session is running) +$B analyze --trace logs/openpoker-B.jsonl [--json] [--mc 20000] +# server-side history (lossy, see caveats) and season snapshot +$B export --out logs/op-history.json --limit 500 && $B analyze --history logs/op-history.json +$B season +``` + +| flag | meaning | +|---|---| +| `--policy` | `builtin:NAME` (random/station/nit/tag/lag/maniac), `compact:PATH`, `bp:PATH` (checkpoint) | +| `--sizing`, `--buckets` | blueprint bet-size preset (`bench::bp::sizing_by_name`) and bucket-table dir (`tables:DIR`) or `coarse`; must match how the blueprint was trained | +| `--hands N` | stop after N completed hands (default 10) | +| `--buy-in` | chips on joining (1000-5000; 2000 = 100 bb, comparable to the paper's stacks) | +| `--timeout-sec` | wall-clock cap for the whole session (default 3600); leaves the table on expiry | +| `--trace FILE` | JSONL trace (default `logs/openpoker-.jsonl`); `--no-raw` drops the raw message log | +| `--hu fallback\|policy` | who plays heads-up hands (default `fallback`, `--fallback builtin` name, default `tag`) | +| `--no-auto-rebuy` | handle `busted` ourselves (rebuy then rejoin) instead of server auto-rebuy | +| `--max-stack-bb X` | default 150, 0 = off. Stacks accumulate on Open Poker but the blueprint is trained at 100 bb. (1) after a hand, if our stack > X bb, `leave_table` then `join_lobby` with `--buy-in` (excess stays in the season balance); (2) guard: never commit more than X bb in one hand (raise/all-in beyond it becomes a raise to the cap, else a call) | +| `--seed`, `--max-reconnects`, `--ws-url`, `--api-url` | determinism and plumbing | + +## How the game is mapped + +* **Chips.** Their 10/20 blinds become our 50/100: every amount is x5 going in, rounded and clamped + to the advertised `[min, max]` raise-to going out. Per-seat stacks are exact (`GameConfig::with_stacks`). +* **Seats.** nlhe seat 0 = SB, 1 = BB, last = BTN. Open Poker's SB is the first dealt-in seat after + `dealer_seat`. Heads-up (observed live) the **dealer is the BB**; the other player is the SB. +* **State.** The server never sends a full hand state, so we replay every `player_action` on an + `nlhe::State`. Start-of-hand stacks come from the first action's `stack_before` plus the blind + that seat posted (seats that have not acted: current stack plus blind). At each `your_turn` + the engine's pot, stacks and legal actions are cross-checked against the server's; any + disagreement lands in the decision's `issues`. +* **Who is dealt in** is not stated by the server (`players` has no status), so the replay tries + the plausible sets (largest first, excluding mid-hand joiners) and keeps one whose replay is + consistent with the event order and the server pot. If a later event contradicts it, the replay + is rebuilt from the full event list. +* **Fewer than 6 players.** With a blueprint (`compact:`/`bp:`) 3-5 player hands are embedded in + the 6-max game: the `6-n` earliest non-blind seats are phantoms that fold immediately, so the + blueprint's history looks like "folded around" and real players keep their true order. + Built-ins use a native n-player engine. **Heads-up cannot be embedded**, so by default HU hands + are played by the fallback built-in (`--hu fallback`, flagged `fallback:tag` in the trace); + `--hu policy` feeds the blueprint a native 2-player game, which is out of distribution for it. +* **Our action -> theirs.** `Fold/Check/Call` map directly; `RaiseTo(t)` becomes `raise` with + `round(t/5)` clamped into the offered range (`all_in` if only a short all-in is possible); + anything not offered degrades to check/fold/call. The trace records fidelity (`Exact`, + `Adjusted(wanted,sent)`, `Degraded`). +* **Failures.** An unplaceable event, a policy error or a missing board marks the hand `desync` + and answers with the safest legal action (check, else fold). A rejected action is retried once + with that action (`invalid_action` only). Duplicate `turn_token`s and `table_seq` regressions + are ignored. +* **Reconnect.** On socket loss: reconnect with backoff; `GET /api/me/active-game`; if playing, + `resync_request` (the replayed events are fed through the normal handlers and a snapshot that + carries our `turn_token` is turned back into a `your_turn`), else `join_lobby`. A resync does not + extend the server's 45 s turn timer; our policies answer in microseconds. A resync into a hand + we never saw start cannot be replayed (no events) and falls back to the safe action. +* **Sitting out.** There is no sit-out message; we never sit out. `busted` -> server auto-rebuy + (1,500 chips; buy-in differs from `--buy-in` afterwards, bb/100 normalises this), `table_closed` + / `season_ended` -> rejoin the lobby. + +## Trace (JSONL, one flushed line per record) + +`session_start`, `raw` (every message in/out, includes `turn_token` but never the API key), +`decision` (server legal set, engine/server `issues`, **full distribution**, sampled `u`, chosen +nlhe action, mapped Open Poker action + fidelity, fallback reason, latency), `ack`, `reject`, +`note`, `anomaly`, `hand` (the analyzer's input: players with start stacks, contributions, +shown cards, all actions, profit and its source, `lock_len`, counters), `session_end`. + +## What the numbers mean + +* **bb/100** = mean hand profit in big blinds x 100, from `final_stacks` (authoritative; the + payouts exclude refunds of uncalled bets). 95% CI is Student-t on per-hand results; hands are + treated as independent although they share tables and stacks. +* **all-in adj** replaces each hand that ended in an all-in run-out (board incomplete when betting + stopped) and where every live player's cards are known (our own plus `shown_cards`) with its + expectation (exact enumeration for flop/turn locks, 20k samples preflop; side pots handled). + This removes **run-out luck only**. `luck removed` shows how much it moved the mean; + `variance ratio` how much per-hand variance it removed (typically 1.3-2x). +* **Cannot be corrected:** luck in hands that are not all-in before the river (folded/mucked cards + are never revealed), hole-card luck, and everything AIVAT would remove: opponent strategies are + unknown, so there is no action-based correction. If a loser mucks after a run-out, the + adjustment skips that hand, which can bias it slightly; the server normally shows all-in cards. +* **Sample size.** Typical 6-max per-hand sd is ~10 bb, so the 95% CI half-width is about + +-62 bb/100 at 1k hands, +-20 at 10k, +-6 at 100k. Anything under ~10k hands is a health check + (protocol, legality, gross leaks), not a strength measurement. The report prints "hands + needed for +-5 bb/100" at the observed sd. +* **Breakdowns** by position, table size, policy used (so heads-up fallback hands do not pollute + the blueprint number) and by opponent present (overlapping; most useful to spot one bot you + lose to or a calling station you farm). + +## Caveats + +* **The opponent field is unknown and shifts every season** (other developers' bots, LLM bots, + built-in templates such as Gambler/Calling Station). Winning here is exploitation of that + field, not distance from equilibrium; losing to it is more informative than winning. +* Stacks are **not 100 bb**: opponents range from 15 bb to 2,700 bb (seat with 55k chips seen), + tables are often 2-4 handed, and the hero's own stack drifts above/below the buy-in. The + blueprint was trained at 100 bb 6-max, so deep/short effective stacks and short-handed tables + are partly out of distribution. Read the by-table-size rows. +* Their minimum raise equals ours (x5) and bet sizes are translated with the policy's own + pseudo-harmonic translation; the blueprint's sizing preset must match training. +* `export`/`--history` is **lossy**: call amounts are 0, street labels are off by one (they name + the street *after* the closing action), `pot_total` disagrees with the actions, no opponent + names. Only hands that replay cleanly are all-in-adjusted. Prefer our own trace. +* Live server quirks found while building this (all handled): `all_in` broadcasts carry the + pre-action stack/pot; `fold` is listed even when checking is free; `winners[].amount` is net, + `payouts[].amount` is gross; a player can join mid-hand (not dealt in); `players` in `your_turn` + has no status; the dealer is the BB heads-up. +* Seasons reset on a calendar; compare runs within one season. Be considerate with volume + (free tier, 20 msg/s limit; we send one message per decision). diff --git a/arena/openpoker/src/analyze.rs b/arena/openpoker/src/analyze.rs new file mode 100644 index 00000000..97d2003b --- /dev/null +++ b/arena/openpoker/src/analyze.rs @@ -0,0 +1,633 @@ +//! Hand records, bb/100 with confidence intervals, all-in EV adjustment, breakdowns. +//! +//! # What the numbers are +//! - `raw`: realised profit per hand in big blinds, x100 = bb/100, with a Student-t 95% CI +//! (normal for n > 120). The unit of independence is the hand; consecutive hands at one table +//! are treated as independent (they are not exactly: stacks and opponents persist). +//! - `adjusted`: the same, but every hand that ended in an all-in run-out with all live hole +//! cards known is replaced by its expectation (see [`crate::equity`]). Unbiased for hands where +//! the cards are always revealed (all-in showdowns); see README for the mucking caveat. +//! - What *cannot* be corrected: luck in hands that are not all-in before the river (we never see +//! folded or mucked cards, and opponent strategies are unknown, so AIVAT-style action +//! corrections are impossible), and hole-card luck. The `var_ratio` shows how much the +//! all-in correction actually helped. + +use crate::equity::{expected_net, Entry}; +use crate::layout::Layout; +use crate::proto::{self, ActionObs, ObsKind}; +use crate::sim::Sim; +use cards::{card_str, parse_cards, Card}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::collections::{BTreeMap, BTreeSet}; + +#[derive(Serialize, Deserialize, Clone, Debug, Default)] +pub struct HandPlayer { + pub seat: usize, + pub name: Option, + pub start_stack: Option, + pub contrib: Option, + pub folded: Option, + pub shown: Option>, +} + +#[derive(Serialize, Deserialize, Clone, Debug, Default)] +pub struct HandAct { + pub seat: usize, + pub street: Option, + pub action: String, + pub amount: Option, +} + +/// One hand, all chip amounts in Open Poker chips. +#[derive(Serialize, Deserialize, Clone, Debug, Default)] +pub struct HandRecord { + pub hand_id: String, + pub table_id: Option, + pub hand_no: u64, + pub hero_seat: usize, + pub dealer_seat: usize, + pub sb: i64, + pub bb: i64, + pub n_players: usize, + pub position: String, + pub hero_hole: Vec, + pub board: Vec, + pub players: Vec, + pub actions: Vec, + /// Hero net chips for the hand. + pub profit: Option, + pub profit_src: String, + /// Board cards visible when betting ended with a showdown ahead (5 = river showdown). + pub lock_len: Option, + pub showdown: bool, + pub policy: String, + pub decisions: u32, + pub fallbacks: u32, + pub issues: u32, + pub desync: bool, +} + +impl HandRecord { + pub fn profit_bb(&self) -> Option { + let p = self.profit?; + (self.bb > 0).then(|| p as f64 / self.bb as f64) + } +} + +pub fn cards_to_strs(c: &[Card]) -> Vec { + c.iter().map(|&x| card_str(x)).collect() +} + +fn strs_to_cards(v: &[String]) -> Vec { + v.iter().filter_map(|s| proto::parse_op_card(s)).collect() +} + +// ---------------------------------------------------------------- statistics + +#[derive(Serialize, Clone, Copy, Debug, Default)] +pub struct Est { + pub n: usize, + pub mean_bb100: f64, + /// Per-hand standard deviation in bb. + pub sd_bb: f64, + pub se_bb100: f64, + pub ci_lo: f64, + pub ci_hi: f64, +} + +/// Two-sided 95% Student-t critical value. +pub fn t_crit95(df: usize) -> f64 { + const T: [f64; 30] = [ + 12.706, 4.303, 3.182, 2.776, 2.571, 2.447, 2.365, 2.306, 2.262, 2.228, 2.201, 2.179, 2.160, 2.145, + 2.131, 2.120, 2.110, 2.101, 2.093, 2.086, 2.080, 2.074, 2.069, 2.064, 2.060, 2.056, 2.052, 2.048, + 2.045, 2.042, + ]; + match df { + 0 => f64::INFINITY, + 1..=30 => T[df - 1], + 31..=60 => 2.00, + 61..=120 => 1.98, + _ => 1.96, + } +} + +pub fn estimate(xs: &[f64]) -> Est { + let n = xs.len(); + if n == 0 { + return Est::default(); + } + let mean = xs.iter().sum::() / n as f64; + let var = if n > 1 { + xs.iter().map(|x| (x - mean).powi(2)).sum::() / (n as f64 - 1.0) + } else { + 0.0 + }; + let sd = var.sqrt(); + let se = sd / (n as f64).sqrt(); + let half = if n > 1 { t_crit95(n - 1) * se } else { f64::INFINITY }; + Est { + n, + mean_bb100: mean * 100.0, + sd_bb: sd, + se_bb100: se * 100.0, + ci_lo: (mean - half) * 100.0, + ci_hi: (mean + half) * 100.0, + } +} + +impl std::fmt::Display for Est { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + if self.n == 0 { + return write!(f, "n=0"); + } + write!( + f, + "{:+.1} bb/100 95% CI [{:.1}, {:.1}] (n={}, sd {:.1} bb/hand)", + self.mean_bb100, self.ci_lo, self.ci_hi, self.n, self.sd_bb + ) + } +} + +// ---------------------------------------------------------------- all-in EV + +/// Hero's expected net chips given the all-in lock, if computable from the record. +pub fn allin_ev(h: &HandRecord, mc_samples: usize) -> Option { + let lock = h.lock_len?; + if lock >= 5 || h.hero_hole.len() != 2 { + return None; + } + let board = strs_to_cards(&h.board); + if board.len() < lock { + return None; + } + let board = &board[..lock]; + let mut entries = Vec::new(); + for p in &h.players { + let contrib = p.contrib?; + let live = !p.folded.unwrap_or(false); + let hole = if p.seat == h.hero_seat { + let c = strs_to_cards(&h.hero_hole); + (c.len() == 2).then(|| [c[0], c[1]]) + } else { + p.shown.as_ref().map(|s| strs_to_cards(s)).filter(|c| c.len() == 2).map(|c| [c[0], c[1]]) + }; + entries.push(Entry { seat: p.seat, contrib, live, hole }); + } + let hero_live = entries.iter().any(|e| e.seat == h.hero_seat && e.live); + if !hero_live { + return None; // hero folded: nothing to correct + } + let seed = h.hand_no.wrapping_mul(0x9E37_79B9).wrapping_add(h.hand_id.len() as u64); + let r = expected_net(&entries, board, mc_samples, seed)?; + r.into_iter().find(|x| x.0 == h.hero_seat).map(|x| x.1) +} + +// ---------------------------------------------------------------- report + +#[derive(Serialize, Clone, Debug, Default)] +pub struct Group { + pub key: String, + pub est: Est, +} + +#[derive(Serialize, Clone, Debug, Default)] +pub struct Report { + pub hands: usize, + pub hands_without_profit: usize, + pub raw: Est, + pub adjusted: Est, + pub hands_adjusted: usize, + /// bb/100 removed by the all-in adjustment (negative = hero ran above equity). + pub allin_luck_bb100: f64, + /// var(raw) / var(adjusted) per hand; > 1 means the adjustment helped. + pub var_ratio: f64, + /// Hands needed for a +-5 bb/100 95% CI at the adjusted sd. + pub hands_for_pm5: usize, + pub vpip: f64, + pub pfr: f64, + pub showdown_pct: f64, + pub desync_hands: usize, + pub fallback_decisions: u32, + pub issue_count: u32, + pub decisions: u32, + pub by_position: Vec, + pub by_players: Vec, + pub by_opponent: Vec, + pub by_policy: Vec, +} + +fn group Vec>(rows: &[(&HandRecord, f64)], key: F) -> Vec { + let mut m: BTreeMap> = BTreeMap::new(); + for (h, x) in rows { + for k in key(h) { + m.entry(k).or_default().push(*x); + } + } + let mut v: Vec = m.into_iter().map(|(key, xs)| Group { key, est: estimate(&xs) }).collect(); + v.sort_by(|a, b| b.est.n.cmp(&a.est.n).then(a.key.cmp(&b.key))); + v +} + +pub fn analyze(hands: &[HandRecord], mc_samples: usize) -> Report { + let mut raw = Vec::new(); + let mut adj = Vec::new(); + let mut rows: Vec<(&HandRecord, f64)> = Vec::new(); // adjusted values for the breakdowns + let mut r = Report { hands: hands.len(), ..Default::default() }; + let (mut vpip, mut pfr, mut sd, mut pre_n) = (0usize, 0usize, 0usize, 0usize); + for h in hands { + r.decisions += h.decisions; + r.fallback_decisions += h.fallbacks; + r.issue_count += h.issues; + r.desync_hands += h.desync as usize; + let Some(x) = h.profit_bb() else { + r.hands_without_profit += 1; + continue; + }; + raw.push(x); + let a = match allin_ev(h, mc_samples) { + Some(ev) if h.bb > 0 => { + r.hands_adjusted += 1; + ev / h.bb as f64 + } + _ => x, + }; + adj.push(a); + rows.push((h, a)); + sd += h.showdown as usize; + let hero_pre: Vec<&HandAct> = h + .actions + .iter() + .filter(|a| a.seat == h.hero_seat && a.street.as_deref().is_some_and(|s| s.eq_ignore_ascii_case("preflop"))) + .collect(); + if !hero_pre.is_empty() || h.decisions > 0 { + pre_n += 1; + let voluntary = hero_pre + .iter() + .any(|a| matches!(proto::parse_obs_kind(&a.action), ObsKind::Call | ObsKind::Raise | ObsKind::AllIn)); + // A BB "call" never exists (it checks), so any call/raise is voluntary. + vpip += voluntary as usize; + pfr += hero_pre + .iter() + .any(|a| matches!(proto::parse_obs_kind(&a.action), ObsKind::Raise | ObsKind::AllIn)) as usize; + } + } + r.raw = estimate(&raw); + r.adjusted = estimate(&adj); + r.allin_luck_bb100 = r.adjusted.mean_bb100 - r.raw.mean_bb100; + let var = |xs: &[f64]| { + let e = estimate(xs); + e.sd_bb * e.sd_bb + }; + let (vr, va) = (var(&raw), var(&adj)); + r.var_ratio = if va > 0.0 { vr / va } else { 1.0 }; + r.hands_for_pm5 = if r.adjusted.sd_bb > 0.0 { + ((1.96 * r.adjusted.sd_bb * 100.0 / 5.0).powi(2)).ceil() as usize + } else { + 0 + }; + let pct = |a: usize, b: usize| if b > 0 { 100.0 * a as f64 / b as f64 } else { 0.0 }; + r.vpip = pct(vpip, pre_n); + r.pfr = pct(pfr, pre_n); + r.showdown_pct = pct(sd, raw.len()); + r.by_position = group(&rows, |h| vec![h.position.clone()]); + r.by_players = group(&rows, |h| vec![format!("{}-handed", h.n_players)]); + r.by_policy = group(&rows, |h| vec![h.policy.clone()]); + r.by_opponent = group(&rows, |h| { + h.players + .iter() + .filter(|p| p.seat != h.hero_seat) + .filter_map(|p| p.name.clone()) + .collect::>() + .into_iter() + .collect() + }); + r.by_opponent.truncate(25); + r +} + +impl Report { + pub fn render(&self) -> String { + let mut s = String::new(); + let mut w = |l: String| { + s.push_str(&l); + s.push('\n'); + }; + w(format!("hands: {} ({} without a known profit)", self.hands, self.hands_without_profit)); + w(format!("raw : {}", self.raw)); + w(format!( + "all-in adj : {} [{} hands adjusted, luck removed {:+.1} bb/100, variance ratio {:.2}x]", + self.adjusted, self.hands_adjusted, self.allin_luck_bb100, self.var_ratio + )); + w(format!( + "hands needed for +-5 bb/100 (95%): ~{} (this sample is {})", + self.hands_for_pm5, + if self.hands_for_pm5 > 0 && self.hands < self.hands_for_pm5 / 4 { "far too small for any strength claim" } else { "see CI" } + )); + w(format!( + "VPIP {:.1}% PFR {:.1}% showdown {:.1}% decisions {} fallbacks {} engine/server issues {} desync hands {}", + self.vpip, self.pfr, self.showdown_pct, self.decisions, self.fallback_decisions, self.issue_count, self.desync_hands + )); + for (title, g) in [ + ("by position", &self.by_position), + ("by table size", &self.by_players), + ("by policy used", &self.by_policy), + ("by opponent present (overlapping; top 25 by hands)", &self.by_opponent), + ] { + if g.is_empty() { + continue; + } + w(format!("-- {title}")); + for x in g.iter() { + w(format!(" {:<14} {}", x.key, x.est)); + } + } + s + } +} + +// ---------------------------------------------------------------- loaders + +#[derive(Default, Debug, Serialize)] +pub struct TraceSummary { + pub lines: usize, + pub bad_lines: usize, + pub decisions: usize, + pub acks: usize, + pub rejects: usize, + pub anomalies: usize, +} + +pub fn load_trace(text: &str) -> (Vec, TraceSummary) { + let mut hands = Vec::new(); + let mut sum = TraceSummary::default(); + for line in text.lines().filter(|l| !l.trim().is_empty()) { + sum.lines += 1; + let Ok(v) = serde_json::from_str::(line) else { + sum.bad_lines += 1; + continue; + }; + match v.get("kind").and_then(Value::as_str) { + Some("hand") => match v.get("hand").and_then(|h| serde_json::from_value::(h.clone()).ok()) { + Some(h) => hands.push(h), + None => sum.bad_lines += 1, + }, + Some("decision") => sum.decisions += 1, + Some("ack") => sum.acks += 1, + Some("reject") => sum.rejects += 1, + Some("anomaly") => sum.anomalies += 1, + _ => {} + } + } + (hands, sum) +} + +fn parse_shown(v: Option<&Value>) -> BTreeMap> { + let mut out = BTreeMap::new(); + let cards = |x: &Value| -> Vec { + x.as_array() + .map(|a| a.iter().filter_map(|c| c.as_str().map(str::to_string)).collect()) + .unwrap_or_default() + }; + match v { + Some(Value::Object(m)) => { + for (k, x) in m { + if let Ok(seat) = k.parse::() { + let c = if x.is_array() { cards(x) } else { x.get("cards").map(cards).unwrap_or_default() }; + if c.len() == 2 { + out.insert(seat, c); + } + } + } + } + Some(Value::Array(a)) => { + for x in a { + if let (Some(seat), Some(c)) = (x.get("seat").and_then(proto::as_i64), x.get("cards").map(cards)) { + if c.len() == 2 { + out.insert(seat as usize, c); + } + } + } + } + _ => {} + } + out +} + +pub fn shown_from_value(v: Option<&Value>) -> BTreeMap> { + parse_shown(v) +} + +/// Convert one entry of the REST `hand-history/export` into a [`HandRecord`]. Contributions and +/// the all-in lock are reconstructed by replaying `all_actions` on the engine (stacks of other +/// players are unknown, so they are assumed deep: a short-stack call is over-counted and the +/// record is only trusted when the replayed pot equals `pot_total`). +pub fn record_from_history(h: &Value) -> Option { + let hero_seat = h.get("seat").and_then(proto::as_i64)? as usize; + let bb = proto::get_i64(h, "big_blind").unwrap_or(20); + let sb = proto::get_i64(h, "small_blind").unwrap_or(bb / 2); + let dealer = proto::get_i64(h, "dealer_seat").unwrap_or(0) as usize; + let start = proto::get_i64(h, "stack_start"); + let hole: Vec = h + .get("hole_cards") + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(|c| c.as_str().map(str::to_string)).collect()) + .unwrap_or_default(); + let board: Vec = h + .get("board") + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(|c| c.as_str().map(str::to_string)).collect()) + .unwrap_or_default(); + let mut acts: Vec<(i64, ActionObs, String)> = Vec::new(); + for a in h.get("all_actions").and_then(Value::as_array).cloned().unwrap_or_default() { + let seq = proto::get_i64(&a, "sequence_in_hand").unwrap_or(acts.len() as i64); + if let Some(o) = proto::parse_player_action(&a) { + let st = o.street.clone().unwrap_or_default(); + acts.push((seq, o, st)); + } + } + acts.sort_by_key(|x| x.0); + let shown = parse_shown(h.get("shown_cards")); + let mut rec = HandRecord { + hand_id: proto::get_str(h, "hand_id").unwrap_or("").to_string(), + table_id: proto::get_str(h, "table_id").map(str::to_string), + hand_no: proto::get_u64(h, "hand_number").unwrap_or(0), + hero_seat, + dealer_seat: dealer, + sb, + bb, + n_players: proto::get_i64(h, "num_players").unwrap_or(0) as usize, + hero_hole: hole.clone(), + board: board.clone(), + profit: proto::get_i64(h, "profit"), + profit_src: "history.profit".into(), + policy: "history".into(), + ..Default::default() + }; + for (_, o, st) in &acts { + rec.actions.push(HandAct { seat: o.seat, street: Some(st.clone()), action: o.raw_action.clone(), amount: o.amount }); + } + // Reconstruction (best effort). + let seats: BTreeSet = acts.iter().map(|x| x.1.seat).chain(std::iter::once(hero_seat)).collect(); + let hole_cards = parse_cards(&hole.concat()).filter(|c| c.len() == 2); + let replay = (|| -> Option { + let hc = hole_cards.as_ref()?; + if seats.len() != rec.n_players || seats.len() < 2 { + return None; + } + let big = 100_000i64; + let stacks: BTreeMap = seats.iter().map(|&s| (s, if s == hero_seat { start.unwrap_or(big) } else { big })).collect(); + let layout = Layout::build(&seats, dealer, &stacks, sb, bb, false).ok()?; + let mut sim = Sim::new(layout, hero_seat, [hc[0], hc[1]], None, 0).ok()?; + for (_, o, _) in &acts { + sim.apply_obs(o).ok()?; + } + Some(sim) + })(); + if let Some(mut sim) = replay { + // `pot_total` in the export is unreliable (it disagrees with the actions even for + // plain hands), so it is NOT used as a check; a hand is trusted only if every + // action replays on the engine without a clamp/mismatch. + let issues = sim.take_issues(); + rec.issues = issues.len() as u32; + for &s in &seats { + let nl = sim.layout.nl(s).unwrap(); + rec.players.push(HandPlayer { + seat: s, + name: None, + start_stack: if s == hero_seat { start } else { None }, + contrib: Some(sim.contributed_op(s).unwrap_or(0)), + folded: Some(sim.state.is_folded(nl)), + shown: shown.get(&s).cloned(), + }); + } + rec.showdown = sim.state.showdown(); + rec.position = sim.layout.position_name(hero_seat).to_string(); + if issues.is_empty() { + rec.lock_len = sim.lock_len; + } else { + rec.desync = true; // not exactly reconstructable: no all-in adjustment + } + } else { + rec.desync = true; + } + Some(rec) +} + +pub fn load_history(v: &Value) -> Vec { + let arr = v.get("hands").and_then(Value::as_array).cloned().unwrap_or_else(|| v.as_array().cloned().unwrap_or_default()); + // Export is newest-first; keep chronological order. + let mut out: Vec = arr.iter().filter_map(record_from_history).collect(); + out.reverse(); + out +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn estimate_math() { + // 10 hands: +1bb x5, -1bb x5 -> mean 0, sd = sqrt(10/9) + let xs: Vec = (0..10).map(|i| if i % 2 == 0 { 1.0 } else { -1.0 }).collect(); + let e = estimate(&xs); + assert!(e.mean_bb100.abs() < 1e-12); + assert!((e.sd_bb - (10.0f64 / 9.0).sqrt()).abs() < 1e-12); + let half = t_crit95(9) * e.sd_bb / (10f64).sqrt() * 100.0; + assert!((e.ci_hi - half).abs() < 1e-9 && (e.ci_lo + half).abs() < 1e-9); + // bb/100 scaling: +0.5 bb per hand = +50 bb/100 + let e = estimate(&[0.5, 0.5, 0.5, 0.5]); + assert!((e.mean_bb100 - 50.0).abs() < 1e-9 && e.se_bb100 == 0.0); + assert_eq!(estimate(&[]).n, 0); + assert!(estimate(&[1.0]).ci_hi.is_infinite()); + assert_eq!(t_crit95(1000), 1.96); + assert!(t_crit95(5) > t_crit95(50)); + } + + fn rec(profit: i64, bb: i64) -> HandRecord { + HandRecord { hand_id: "h".into(), hero_seat: 0, bb, profit: Some(profit), position: "BTN".into(), n_players: 6, ..Default::default() } + } + + #[test] + fn report_basics_and_ci_coverage() { + let hands: Vec = (0..100).map(|i| rec(if i % 2 == 0 { 40 } else { -20 }, 20)).collect(); + let r = analyze(&hands, 100); + assert_eq!(r.hands, 100); + // mean +10 chips = +0.5 bb -> 50 bb/100 + assert!((r.raw.mean_bb100 - 50.0).abs() < 1e-9); + assert!((r.adjusted.mean_bb100 - r.raw.mean_bb100).abs() < 1e-9); + assert_eq!(r.hands_adjusted, 0); + assert!(r.raw.ci_lo < 50.0 && r.raw.ci_hi > 50.0); + assert!(r.render().contains("bb/100")); + // empty and no-profit inputs do not panic + assert_eq!(analyze(&[], 10).raw.n, 0); + } + + #[test] + fn allin_adjustment_replaces_runout_luck() { + // Hero AhAd vs KsKc all-in on the turn Qc 7d 2h 3s (2 kings left): EV = 200*42/44 - 100. + let mk = |profit: i64, river: &str| HandRecord { + hand_id: format!("h{profit}"), + hero_seat: 0, + bb: 20, + profit: Some(profit), + hero_hole: vec!["Ah".into(), "Ad".into()], + board: vec!["Qc".into(), "7d".into(), "2h".into(), "3s".into(), river.into()], + lock_len: Some(4), + showdown: true, + n_players: 2, + position: "SB".into(), + players: vec![ + HandPlayer { seat: 0, contrib: Some(100), folded: Some(false), ..Default::default() }, + HandPlayer { seat: 1, name: Some("villain".into()), contrib: Some(100), folded: Some(false), shown: Some(vec!["Ks".into(), "Kc".into()]), ..Default::default() }, + ], + ..Default::default() + }; + let ev = 200.0 * 42.0 / 44.0 - 100.0; + let h = mk(100, "9d"); + assert!((allin_ev(&h, 0).unwrap() - ev).abs() < 1e-9); + // The two outcomes (win +100 / lose -100) both map to the same EV: variance collapses. + let hands = vec![mk(100, "9d"), mk(-100, "Kh"), mk(100, "5c"), mk(100, "8h")]; + let r = analyze(&hands, 0); + assert_eq!(r.hands_adjusted, 4); + assert!(r.adjusted.sd_bb < 1e-9, "all adjusted hands share one EV"); + assert!(r.var_ratio > 1e6 || r.var_ratio.is_finite()); + assert!((r.adjusted.mean_bb100 - ev / 20.0 * 100.0).abs() < 1e-6); + // Unknown villain cards: not adjusted. + let mut h2 = mk(100, "9d"); + h2.players[1].shown = None; + assert!(allin_ev(&h2, 0).is_none()); + // River showdowns are never adjusted. + let mut h3 = mk(100, "9d"); + h3.lock_len = Some(5); + assert!(allin_ev(&h3, 0).is_none()); + } + + #[test] + fn history_record_reconstruction() { + // 3 players, dealer 0 -> SB 1, BB 2, BTN 0. Seat 0 raises to 60, 1 folds, 2 calls; + // flop: 2 bets 100 all-in(stack 200 total? use plain bet), 0 calls; pot = 60*2+... check totals. + let v = json!({ + "hand_id":"x","table_id":"t","hand_number":7,"seat":2,"stack_start":2000,"stack_end":1880,"profit":-120, + "all_actions":[ + {"seat":0,"action":"raise","amount":60,"street":"preflop","sequence_in_hand":1}, + {"seat":1,"action":"fold","amount":0,"street":"preflop","sequence_in_hand":2}, + {"seat":2,"action":"call","amount":0,"street":"preflop","sequence_in_hand":3}, + {"seat":2,"action":"raise","amount":60,"street":"flop","sequence_in_hand":4}, + {"seat":0,"action":"call","amount":0,"street":"flop","sequence_in_hand":5} + ], + "board":["2c","7d","9h","Js","3c"],"pot_total":240,"num_players":3,"small_blind":10,"big_blind":20, + "dealer_seat":0,"hole_cards":["Kc","Kd"],"shown_cards":{} + }); + // Replay: preflop 60+60+10 (SB dead) = 130; flop 60+60 = 120 -> 250 (pot_total is ignored). + let v2 = v.clone(); + let r = record_from_history(&v2).unwrap(); + assert!(!r.desync); + assert_eq!(r.profit, Some(-120)); + assert_eq!(r.n_players, 3); + assert_eq!(r.position, "BB"); + assert_eq!(r.players.iter().map(|p| p.contrib.unwrap()).sum::(), 250); + assert_eq!(load_history(&json!({"hands":[v2.clone(), v2]})).len(), 2); + } +} diff --git a/arena/openpoker/src/equity.rs b/arena/openpoker/src/equity.rs new file mode 100644 index 00000000..0d110627 --- /dev/null +++ b/arena/openpoker/src/equity.rs @@ -0,0 +1,204 @@ +//! All-in equity EV: replace the realised runout by its expectation. +//! +//! Given every live player's hole cards and the board known when betting stopped, the +//! expected net chips of each seat follow from enumerating (<= 2 missing cards) or sampling +//! (preflop, 5 missing) the runouts and splitting each side-pot layer among the best hands. +//! This removes *runout luck* only; see the README for what it cannot correct. + +use cards::{bit, evaluate, mask_of, Card, Hand, Rng}; + +#[derive(Clone, Debug)] +pub struct Entry { + pub seat: usize, + /// Total chips committed to the pot over the hand. + pub contrib: i64, + pub live: bool, + pub hole: Option<[Card; 2]>, +} + +struct Layer { + amount: f64, + /// Indices into the live list. + eligible: Vec, +} + +/// Expected net chips per seat (payout expectation minus contribution), or `None` when a live +/// player's cards are unknown or the inputs are inconsistent. +pub fn expected_net(entries: &[Entry], board: &[Card], mc_samples: usize, seed: u64) -> Option> { + if board.len() > 5 || (!board.is_empty() && board.len() < 3) { + return None; + } + let live: Vec<&Entry> = entries.iter().filter(|e| e.live).collect(); + if live.len() < 2 { + return None; + } + let holes: Vec<[Card; 2]> = live.iter().map(|e| e.hole).collect::>>()?; + let mut dead: Hand = mask_of(board); + if dead.count_ones() as usize != board.len() { + return None; + } + for h in &holes { + for &c in h { + if dead & bit(c) != 0 { + return None; // duplicate card: inconsistent input + } + dead |= bit(c); + } + } + // Side-pot layers over all contributions (folded money included). + let mut levels: Vec = live.iter().map(|e| e.contrib).collect(); + levels.sort_unstable(); + levels.dedup(); + let mut layers = Vec::new(); + let mut prev = 0i64; + for lv in levels { + if lv <= prev { + continue; + } + let amount: i64 = entries.iter().map(|e| e.contrib.min(lv) - e.contrib.min(prev)).sum(); + let eligible: Vec = live + .iter() + .enumerate() + .filter(|(_, e)| e.contrib >= lv) + .map(|(i, _)| i) + .collect(); + layers.push(Layer { amount: amount as f64, eligible }); + prev = lv; + } + let m = 5 - board.len(); + let remaining: Vec = (0..52u8).filter(|&c| dead & bit(c) == 0).collect(); + let mut acc = vec![0f64; live.len()]; + let mut count = 0f64; + let eval_runout = |extra: &[Card], acc: &mut Vec| { + let bm = mask_of(board) | mask_of(extra); + let ranks: Vec = holes.iter().map(|h| evaluate(bm | bit(h[0]) | bit(h[1]))).collect(); + for l in &layers { + let best = l.eligible.iter().map(|&i| ranks[i]).max().unwrap(); + let w: Vec = l.eligible.iter().copied().filter(|&i| ranks[i] == best).collect(); + let share = l.amount / w.len() as f64; + for i in w { + acc[i] += share; + } + } + }; + match m { + 0 => { + eval_runout(&[], &mut acc); + count = 1.0; + } + 1 => { + for &a in &remaining { + eval_runout(&[a], &mut acc); + count += 1.0; + } + } + 2 => { + for (i, &a) in remaining.iter().enumerate() { + for &b in &remaining[i + 1..] { + eval_runout(&[a, b], &mut acc); + count += 1.0; + } + } + } + _ => { + let mut rng = Rng::new(seed); + for _ in 0..mc_samples.max(1) { + let mut d = dead; + let mut extra = Vec::with_capacity(m); + for _ in 0..m { + let c = rng.draw(d); + d |= bit(c); + extra.push(c); + } + eval_runout(&extra, &mut acc); + count += 1.0; + } + } + } + let mut out = Vec::new(); + for e in entries { + let payout = live + .iter() + .position(|l| l.seat == e.seat) + .map_or(0.0, |i| acc[i] / count); + out.push((e.seat, payout - e.contrib as f64)); + } + Some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + use cards::parse_cards; + + fn h(s: &str) -> [Card; 2] { + let v = parse_cards(s).unwrap(); + [v[0], v[1]] + } + fn e(seat: usize, contrib: i64, live: bool, hole: Option<&str>) -> Entry { + Entry { seat, contrib, live, hole: hole.map(h) } + } + fn net(v: &[(usize, f64)], seat: usize) -> f64 { + v.iter().find(|x| x.0 == seat).unwrap().1 + } + + #[test] + fn turn_lock_is_exact() { + // AA vs KK on Qc 7d 2h 3s: KK wins only on the 2 remaining kings out of 44 cards. + let b = parse_cards("Qc7d2h3s").unwrap(); + let r = expected_net(&[e(0, 100, true, Some("AhAd")), e(1, 100, true, Some("KsKc"))], &b, 0, 1).unwrap(); + let aa = 200.0 * 42.0 / 44.0 - 100.0; + assert!((net(&r, 0) - aa).abs() < 1e-9, "{r:?}"); + assert!((net(&r, 0) + net(&r, 1)).abs() < 1e-9, "zero-sum"); + } + + #[test] + fn river_is_deterministic_and_ties_split() { + let b = parse_cards("AsKsQsJs2d").unwrap(); + let r = expected_net(&[e(0, 50, true, Some("9c9d")), e(1, 50, true, Some("8c8d"))], &b, 0, 1).unwrap(); + assert!((net(&r, 0) - 50.0).abs() < 1e-9 && (net(&r, 1) + 50.0).abs() < 1e-9); + let r = expected_net(&[e(0, 50, true, Some("3c4d")), e(1, 50, true, Some("3d4c"))], &b, 0, 1).unwrap(); + assert!(net(&r, 0).abs() < 1e-9 && net(&r, 1).abs() < 1e-9); + } + + #[test] + fn side_pots_and_dead_money() { + // Seat 2 all-in for 40 with the best hand, seats 0/1 put in 100 each, seat 3 folded 20. + let b = parse_cards("2c7d9hJs3c").unwrap(); + let r = expected_net( + &[ + e(0, 100, true, Some("KcKd")), + e(1, 100, true, Some("QcQd")), + e(2, 40, true, Some("AcAd")), + e(3, 20, false, None), + ], + &b, + 0, + 1, + ) + .unwrap(); + // Main pot 40*3 + 20 = 140 -> seat 2. Side pot 60*2 = 120 -> seat 0 (KK > QQ). + assert!((net(&r, 2) - (140.0 - 40.0)).abs() < 1e-9); + assert!((net(&r, 0) - (120.0 - 100.0)).abs() < 1e-9); + assert!((net(&r, 1) + 100.0).abs() < 1e-9); + assert!((net(&r, 3) + 20.0).abs() < 1e-9); + let total: f64 = r.iter().map(|x| x.1).sum(); + assert!(total.abs() < 1e-9); + } + + #[test] + fn preflop_monte_carlo_matches_known_equity() { + // AhAd vs KsKc preflop: ~81.9% for aces. + let r = expected_net(&[e(0, 100, true, Some("AhAd")), e(1, 100, true, Some("KsKc"))], &[], 60_000, 7).unwrap(); + let eq = (net(&r, 0) + 100.0) / 200.0; + assert!((eq - 0.819).abs() < 0.01, "equity {eq}"); + } + + #[test] + fn unknown_cards_or_dupes_give_none() { + let b = parse_cards("2c7d9h").unwrap(); + assert!(expected_net(&[e(0, 10, true, Some("AhAd")), e(1, 10, true, None)], &b, 0, 1).is_none()); + assert!(expected_net(&[e(0, 10, true, Some("AhAd")), e(1, 10, true, Some("AhKd"))], &b, 0, 1).is_none()); + assert!(expected_net(&[e(0, 10, true, Some("AhAd")), e(1, 10, false, None)], &b, 0, 1).is_none()); + } +} diff --git a/arena/openpoker/src/guard.rs b/arena/openpoker/src/guard.rs new file mode 100644 index 00000000..4a54164b --- /dev/null +++ b/arena/openpoker/src/guard.rs @@ -0,0 +1,188 @@ +//! Time-boxed search policy for live play. +//! +//! [`GuardedSearch`] wraps a [`SearchPolicy`] so that a decision can never take longer than the +//! budget and a failing search can never take the bot down with it: +//! +//! * Two layers. (1) the solver's cooperative cap (`SearchParams::max_millis`, set by the caller +//! to a fraction of the budget) makes a slow search return a truncated-but-valid solution; +//! (2) the hard guarantee: every search runs on a worker thread against a **clone** of the +//! player and the decision thread waits at most `budget` (`recv_timeout`). On timeout (or a +//! worker panic that unwinds) the decision uses the blueprint action and the trace gets a +//! `fallback_reason`. +//! * State safety. The worker owns a clone; the real player is only replaced by the clone when +//! the worker finished in time. On timeout the real player is `detach_search`ed: fresh +//! solution cell (the abandoned worker holds the old cell's lock) and blueprint play until the +//! next street (`observe_board` re-arms search). Its beliefs/history are untouched, because +//! `observe` calls only ever hit the real player. +//! * At most one abandoned search at a time: while one is still running (`inflight > 0`) new +//! searches are skipped (blueprint) so abandoned work cannot pile up on the thread pool. +//! +//! Caveat: a panic can only be contained if the binary is built with `panic = "unwind"`; +//! the workspace release profile uses `panic = "abort"`, where a search panic aborts the process. + +use bench::policy::{Dist, Event, Player, PolicyFactory, View}; +use cards::Card; +use nlhe::{Action, GameConfig, State}; +use search::policy::{SearchPlayer, SearchPolicy}; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering::Relaxed}; +use std::sync::{mpsc, Arc, Mutex}; +use std::time::{Duration, Instant}; + +#[derive(Default)] +struct GuardStats { + searched: AtomicU64, + timeouts: AtomicU64, + panics: AtomicU64, + skipped_busy: AtomicU64, + /// Wall time (us) of each decision that ran a search (success or not). + micros: Mutex>, +} + +pub struct GuardedSearch { + name: String, + policy: Arc, + budget: Duration, + inflight: Arc, + stats: Arc, +} + +impl GuardedSearch { + pub fn new(name: &str, policy: Arc, budget: Duration) -> Self { + GuardedSearch { name: name.into(), policy, budget, inflight: Arc::new(AtomicUsize::new(0)), stats: Arc::default() } + } + pub fn budget(&self) -> Duration { + self.budget + } + pub fn policy(&self) -> &Arc { + &self.policy + } + pub fn timeouts(&self) -> u64 { + self.stats.timeouts.load(Relaxed) + } + pub fn panics(&self) -> u64 { + self.stats.panics.load(Relaxed) + } + pub fn searched(&self) -> u64 { + self.stats.searched.load(Relaxed) + } + /// (mean, p50, p95, max) in ms over decisions that ran a search. + pub fn latency_ms(&self) -> Option<(f64, f64, f64, f64)> { + let mut v = self.stats.micros.lock().unwrap().clone(); + if v.is_empty() { + return None; + } + v.sort_unstable(); + let q = |p: f64| v[((v.len() - 1) as f64 * p).round() as usize] as f64 / 1e3; + Some((v.iter().sum::() as f64 / v.len() as f64 / 1e3, q(0.5), q(0.95), *v.last().unwrap() as f64 / 1e3)) + } +} + +impl PolicyFactory for GuardedSearch { + fn name(&self) -> String { + self.name.clone() + } + fn new_player(&self, seat: usize, cfg: &GameConfig, seed: u64) -> Box { + Box::new(GuardedPlayer { + p: self.policy.player(seat, cfg, seed), + budget: self.budget, + inflight: self.inflight.clone(), + stats: self.stats.clone(), + note: None, + }) + } + fn report(&self) -> Option { + let s = &self.stats; + let lat = self.latency_ms().map(|(m, p50, p95, mx)| format!(r#","mean_ms":{m:.1},"p50_ms":{p50:.1},"p95_ms":{p95:.1},"max_ms":{mx:.1}"#)).unwrap_or_default(); + Some(format!( + r#"{{"budget_ms":{},"searched":{},"timeouts":{},"panics":{},"skipped_busy":{}{lat}}}"#, + self.budget.as_millis(), + s.searched.load(Relaxed), + s.timeouts.load(Relaxed), + s.panics.load(Relaxed), + s.skipped_busy.load(Relaxed) + )) + } +} + +pub struct GuardedPlayer { + p: SearchPlayer, + budget: Duration, + inflight: Arc, + stats: Arc, + note: Option, +} + +struct InflightGuard(Arc); +impl Drop for InflightGuard { + fn drop(&mut self) { + self.0.fetch_sub(1, Relaxed); + } +} + +impl GuardedPlayer { + fn fallback(&mut self, v: &View, hole: [Card; 2], why: String) -> Dist { + self.p.detach_search(); + self.note = Some(why); + self.p.blueprint_dist(v, hole) + } +} + +impl Player for GuardedPlayer { + fn observe(&mut self, pre: &State, seat: usize, a: Action) { + self.p.observe(pre, seat, a); + } + fn observe_board(&mut self, board: &[Card]) { + self.p.observe_board(board); + } + fn dist(&mut self, v: &View, hole: [Card; 2]) -> Dist { + self.note = None; + if !self.p.needs_search(v) { + // Cheap path (blueprint, or an existing solution): no search will run. + return self.p.dist(v, hole); + } + let t0 = Instant::now(); + if self.inflight.load(Relaxed) > 0 { + self.stats.skipped_busy.fetch_add(1, Relaxed); + return self.fallback(v, hole, "prior_search_still_running: blueprint".into()); + } + let mut worker = self.p.clone(); + let (cfg, state, seat) = (*v.cfg, *v.state, v.seat); + let (board, history): (Vec, Vec) = (v.board.to_vec(), v.history.to_vec()); + let (tx, rx) = mpsc::channel(); + self.inflight.fetch_add(1, Relaxed); + let guard = InflightGuard(self.inflight.clone()); + let spawned = std::thread::Builder::new().name("search-decision".into()).spawn(move || { + let _guard = guard; + let view = View { cfg: &cfg, state: &state, board: &board, history: &history, seat }; + let d = worker.dist(&view, hole); + let _ = tx.send((worker, d)); + }); + if let Err(e) = spawned { + // `guard` was moved into the closure that failed to start and has been dropped with it. + return self.fallback(v, hole, format!("spawn_failed: {e}")); + } + let res = rx.recv_timeout(self.budget); + self.stats.micros.lock().unwrap().push(t0.elapsed().as_micros() as u64); + match res { + Ok((worker, d)) => { + self.stats.searched.fetch_add(1, Relaxed); + self.p = worker; + d + } + Err(mpsc::RecvTimeoutError::Timeout) => { + self.stats.timeouts.fetch_add(1, Relaxed); + self.fallback(v, hole, format!("search_timeout>{}ms: blueprint", self.budget.as_millis())) + } + Err(mpsc::RecvTimeoutError::Disconnected) => { + self.stats.panics.fetch_add(1, Relaxed); + self.fallback(v, hole, "search_panic: blueprint".into()) + } + } + } + fn exposes_probs(&self) -> bool { + true + } + fn take_note(&mut self) -> Option { + self.note.take() + } +} diff --git a/arena/openpoker/src/layout.rs b/arena/openpoker/src/layout.rs new file mode 100644 index 00000000..c1115cb3 --- /dev/null +++ b/arena/openpoker/src/layout.rs @@ -0,0 +1,207 @@ +//! Open Poker seats -> nlhe seats. +//! +//! nlhe convention: seat 0 = small blind, 1 = big blind, 2.. follow, the last seat is the +//! button; heads-up the button is seat 0 (SB). Open Poker numbers seats clockwise and sends +//! `dealer_seat`; the SB is the next dealt-in seat after the dealer, the BB the next after +//! that (verified on recorded hands: dealer 0 -> SB 1, BB 2, first to act 3). +//! +//! **Heads-up (observed live):** Open Poker applies the same rule with two players, so the +//! *dealer is the BB* and the other player is the SB (first to act preflop, second postflop). +//! The roles are standard; only the button-to-role assignment differs from the usual +//! "button = SB". The layout therefore has no heads-up special case. +//! +//! # Fewer than six players +//! - `embed6 = true` (blueprint policies, whose infoset keys encode a 6-player action +//! history): the hand is embedded in the 6-max game. The first `6 - n` non-blind seats +//! (UTG, HJ, ...) are phantom players who fold immediately, so real players keep their true +//! relative order (SB, BB, then the rest, button last) and the blueprint sees a history that +//! "folded around" - exactly what happens in a 6-max game where early positions fold. +//! Valid for 3..=5 players. Heads-up cannot be embedded (the HU button is SB and acts *last* +//! postflop, which no 6-max seat order reproduces), so n = 2 always uses a native 2-player +//! engine and the session decides which policy plays it (see `session::HuMode`). +//! - `embed6 = false` (stateless heuristics like the built-ins): native n-player engine. + +use crate::SCALE; +use nlhe::{GameConfig, MAX_PLAYERS}; +use std::collections::{BTreeMap, BTreeSet}; + +#[derive(Clone, Debug)] +pub struct Layout { + pub n_real: usize, + pub embed6: bool, + /// Number of phantom seats that fold first (engine seats `2..2+prefold`). + pub prefold: usize, + /// engine seat -> Open Poker seat (`None` for phantoms). + pub op_of_nl: Vec>, + pub nl_of_op: BTreeMap, + pub cfg: GameConfig, +} + +pub fn scale(x: i64) -> i32 { + (x * SCALE as i64).clamp(0, i32::MAX as i64 / 2) as i32 +} + +pub fn unscale(x: i32) -> i64 { + ((x as f64) / SCALE as f64).round() as i64 +} + +/// Dealt-in seats in engine order `[SB, BB, ..., BTN]`: the SB is the first seat after the dealer. +pub fn engine_order(participants: &BTreeSet, dealer: usize) -> Vec { + let seats: Vec = participants.iter().copied().collect(); + let n = seats.len(); + let start = seats.iter().position(|&s| s > dealer).unwrap_or(0); + (0..n).map(|i| seats[(start + i) % n]).collect() +} + +impl Layout { + /// `stacks` are start-of-hand stacks (behind the blinds) in Open Poker chips. + pub fn build( + participants: &BTreeSet, + dealer: usize, + stacks: &BTreeMap, + sb: i64, + bb: i64, + embed6: bool, + ) -> Result { + let n = participants.len(); + if !(2..=MAX_PLAYERS).contains(&n) { + return Err(format!("{n} dealt-in players (need 2..=6)")); + } + // Engine order [SB, BB, ..., BTN] in Open Poker seats. + let order = engine_order(participants, dealer); + let embed = embed6 && (3..=5).contains(&n); + let k = if embed { MAX_PLAYERS - n } else { 0 }; + let players = if embed { MAX_PLAYERS } else { n }; + let mut op_of_nl: Vec> = vec![None; players]; + for (i, &s) in order.iter().enumerate() { + let nl = if i < 2 { i } else { i + k }; + op_of_nl[nl] = Some(s); + } + let nl_of_op = op_of_nl + .iter() + .enumerate() + .filter_map(|(nl, s)| s.map(|s| (s, nl))) + .collect(); + let mut st = [0i32; MAX_PLAYERS]; + for (nl, s) in op_of_nl.iter().enumerate() { + st[nl] = match s { + Some(s) => scale(*stacks.get(s).ok_or_else(|| format!("no stack for seat {s}"))?), + None => scale(bb) * 100, // phantom: folds immediately, size irrelevant + }; + } + let cfg = GameConfig { + players, + stack: 0, + small_blind: scale(sb), + big_blind: scale(bb), + stacks: Some(st), + ..GameConfig::new(2) + }; + Ok(Layout { + n_real: n, + embed6: embed, + prefold: k, + op_of_nl, + nl_of_op, + cfg, + }) + } + + pub fn nl(&self, op_seat: usize) -> Option { + self.nl_of_op.get(&op_seat).copied() + } + pub fn op(&self, nl_seat: usize) -> Option { + self.op_of_nl.get(nl_seat).copied().flatten() + } + /// Position name of an engine seat in an n-handed game (for traces/reports). + pub fn position_name(&self, op_seat: usize) -> &'static str { + let Some(nl) = self.nl(op_seat) else { return "?" }; + // index within real players in engine order + let idx = (0..=nl).filter(|&i| self.op_of_nl[i].is_some()).count() - 1; + position_name(self.n_real, idx) + } +} + +/// `idx` = index in engine order (0 = SB, 1 = BB, ..., n-1 = BTN). +pub fn position_name(n: usize, idx: usize) -> &'static str { + if n == 2 { + return ["BTN/SB", "BB"][idx.min(1)]; + } + if idx == 0 { + return "SB"; + } + if idx == 1 { + return "BB"; + } + if idx == n - 1 { + return "BTN"; + } + // Positions between BB and BTN: closest to BTN is CO, then HJ, then UTG. + match n - 1 - idx { + 1 => "CO", + 2 => "HJ", + _ => "UTG", + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parts(v: &[usize]) -> BTreeSet { + v.iter().copied().collect() + } + fn stacks(v: &[usize]) -> BTreeMap { + v.iter().map(|&s| (s, 2000 + s as i64)).collect() + } + + #[test] + fn six_max_rotation_matches_recorded_history() { + // dealer 0: SB seat 1, BB seat 2, UTG seat 3, ..., BTN seat 0. + let l = Layout::build(&parts(&[0, 1, 2, 3, 4, 5]), 0, &stacks(&[0, 1, 2, 3, 4, 5]), 10, 20, true).unwrap(); + assert_eq!(l.op_of_nl, vec![Some(1), Some(2), Some(3), Some(4), Some(5), Some(0)]); + assert_eq!(l.cfg.small_blind, 50); + assert_eq!(l.cfg.stacks.unwrap()[0], 2001 * 5); + assert_eq!(l.position_name(3), "UTG"); + assert_eq!(l.position_name(0), "BTN"); + // dealer 5 wraps + let l = Layout::build(&parts(&[0, 1, 2, 3, 4, 5]), 5, &stacks(&[0, 1, 2, 3, 4, 5]), 10, 20, true).unwrap(); + assert_eq!(l.nl(0), Some(0)); // SB wraps to seat 0 + assert_eq!(l.nl(5), Some(5)); // dealer 5 is the button + } + + #[test] + fn short_handed_embedding_keeps_real_order() { + // 4 players at seats 0,2,3,5, dealer 2: SB 3, BB 5, X 0, BTN 2. + let l = Layout::build(&parts(&[0, 2, 3, 5]), 2, &stacks(&[0, 2, 3, 5]), 10, 20, true).unwrap(); + assert!(l.embed6 && l.prefold == 2 && l.cfg.players == 6); + assert_eq!(l.op_of_nl, vec![Some(3), Some(5), None, None, Some(0), Some(2)]); + assert_eq!(l.position_name(0), "CO"); + // native + let l = Layout::build(&parts(&[0, 2, 3, 5]), 2, &stacks(&[0, 2, 3, 5]), 10, 20, false).unwrap(); + assert!(!l.embed6 && l.cfg.players == 4); + assert_eq!(l.op_of_nl, vec![Some(3), Some(5), Some(0), Some(2)]); + // 3 players: all three early seats are phantoms, BTN is engine seat 5. + let l = Layout::build(&parts(&[1, 2, 4]), 4, &stacks(&[1, 2, 4]), 10, 20, true).unwrap(); + assert_eq!(l.prefold, 3); + assert_eq!(l.op_of_nl, vec![Some(1), Some(2), None, None, None, Some(4)]); + } + + #[test] + fn heads_up_follows_open_poker_dealer_is_bb_and_is_never_embedded() { + // Recorded live: seats 1 and 2, dealer 2 -> seat 1 posts SB and acts first preflop. + let l = Layout::build(&parts(&[1, 2]), 2, &stacks(&[1, 2]), 10, 20, true).unwrap(); + assert!(!l.embed6); + assert_eq!(l.op_of_nl, vec![Some(1), Some(2)]); + assert_eq!(l.position_name(1), "BTN/SB"); + assert_eq!(l.position_name(2), "BB"); + let l = Layout::build(&parts(&[2, 4]), 3, &stacks(&[2, 4]), 10, 20, true).unwrap(); + assert_eq!(l.op_of_nl, vec![Some(4), Some(2)]); + } + + #[test] + fn rejects_bad_counts() { + assert!(Layout::build(&parts(&[1]), 0, &stacks(&[1]), 10, 20, true).is_err()); + assert_eq!(unscale(scale(137)), 137); + } +} diff --git a/arena/openpoker/src/lib.rs b/arena/openpoker/src/lib.rs new file mode 100644 index 00000000..3256a56c --- /dev/null +++ b/arena/openpoker/src/lib.rs @@ -0,0 +1,31 @@ +//! Live 6-max evaluation on Open Poker (openpoker.ai). +//! +//! Layers (bottom up): +//! - [`proto`]: tolerant parsing of server messages, builders for client messages. +//! - [`layout`]: Open Poker seats -> nlhe seats (button/blinds rotation, short-handed +//! embedding into the 6-max game), chip scaling (x[`SCALE`]). +//! - [`sim`]: replay of the table's actions onto an `nlhe::State` plus the hero's bench +//! `Player`; produces a distribution over concrete nlhe actions. +//! - [`mapping`]: nlhe `Action` -> legal Open Poker action (clamp/round/fallback). +//! - [`session`]: socket-free state machine (message in, messages out), unit-testable. +//! - [`live`]: websocket/REST IO, reconnect. +//! - [`trace`]: JSONL trace; [`analyze`] + [`equity`]: bb/100, CIs, all-in EV adjustment. +//! +//! Chips: Open Poker blinds are 10/20, ours 50/100, so every Open Poker chip amount is +//! multiplied by [`SCALE`] = 5 going in and rounded (and clamped to the legal range) going out. + +pub mod analyze; +pub mod equity; +pub mod guard; +pub mod layout; +pub mod live; +pub mod mapping; +pub mod offline; +pub mod proto; +pub mod searchpol; +pub mod session; +pub mod sim; +pub mod trace; + +/// Our chips per Open Poker chip (50/100 blinds vs 10/20). +pub const SCALE: i32 = 5; diff --git a/arena/openpoker/src/live.rs b/arena/openpoker/src/live.rs new file mode 100644 index 00000000..53f19946 --- /dev/null +++ b/arena/openpoker/src/live.rs @@ -0,0 +1,262 @@ +//! Network IO: websocket loop with reconnect, REST helpers, API-key loading. +//! +//! Nothing here is reachable from tests; all logic worth testing is in [`crate::session`]. +//! The API key is read from `OPENPOKER_API_KEY` or a `KEY=VALUE` file and is never printed or +//! traced (it only appears in the `Authorization` header). + +use crate::session::Session; +use crate::trace::now_ms; +use serde_json::{json, Value}; +use std::net::TcpStream; +use std::path::Path; +use std::time::{Duration, Instant}; +use tungstenite::client::IntoClientRequest; +use tungstenite::stream::MaybeTlsStream; +use tungstenite::{connect, Message, WebSocket}; + +pub const WS_URL: &str = "wss://openpoker.ai/ws"; +pub const API_URL: &str = "https://api.openpoker.ai"; + +type Socket = WebSocket>; + +pub struct LiveOpts { + pub ws_url: String, + pub api_url: String, + pub api_key: String, + /// Wall-clock cap for the whole session. + pub timeout: Duration, + pub max_reconnects: u32, +} + +/// Look for the key in the environment, then in the given file, then in the usual places. +pub fn load_api_key(file: Option<&Path>) -> Result { + if let Ok(v) = std::env::var("OPENPOKER_API_KEY") { + if !v.trim().is_empty() { + return Ok(v.trim().to_string()); + } + } + let mut candidates: Vec = Vec::new(); + if let Some(f) = file { + candidates.push(f.to_path_buf()); + } + candidates.push(".env.openpoker".into()); + if let Ok(home) = std::env::var("HOME") { + candidates.push(Path::new(&home).join("pluribus/.env.openpoker")); + } + candidates.push(".env".into()); + for c in &candidates { + if let Ok(text) = std::fs::read_to_string(c) { + if let Some(k) = parse_env_key(&text) { + return Ok(k); + } + } + } + Err("OPENPOKER_API_KEY not found (env var, --env FILE, ./.env.openpoker, ~/pluribus/.env.openpoker)".into()) +} + +pub fn parse_env_key(text: &str) -> Option { + for line in text.lines() { + let line = line.trim().trim_start_matches("export "); + if let Some((k, v)) = line.split_once('=') { + if k.trim() == "OPENPOKER_API_KEY" { + let v = v.trim().trim_matches('"').trim_matches('\'').trim(); + if !v.is_empty() { + return Some(v.to_string()); + } + } + } + } + None +} + +fn connect_ws(opts: &LiveOpts) -> Result { + let mut req = opts + .ws_url + .as_str() + .into_client_request() + .map_err(|e| format!("bad websocket url: {e}"))?; + req.headers_mut().insert( + "Authorization", + format!("Bearer {}", opts.api_key).parse().map_err(|e| format!("auth header: {e}"))?, + ); + let (sock, _) = connect(req).map_err(|e| format!("websocket connect failed: {e}"))?; + set_read_timeout(&sock, Duration::from_secs(5)); + Ok(sock) +} + +fn set_read_timeout(sock: &Socket, d: Duration) { + match sock.get_ref() { + MaybeTlsStream::Plain(s) => { + let _ = s.set_read_timeout(Some(d)); + } + MaybeTlsStream::Rustls(s) => { + let _ = s.get_ref().set_read_timeout(Some(d)); + } + _ => {} + } +} + +fn send(sock: &mut Socket, v: &Value) -> Result<(), String> { + sock.send(Message::Text(v.to_string())).map_err(|e| format!("send failed: {e}")) +} + +fn get_json(opts: &LiveOpts, path: &str) -> Result { + get_json_url(&opts.api_key, &format!("{}{}", opts.api_url.trim_end_matches('/'), path)) +} + +fn get_json_url(key: &str, url: &str) -> Result { + ureq::get(url) + .set("Authorization", &format!("Bearer {key}")) + .timeout(Duration::from_secs(20)) + .call() + .map_err(|e| format!("GET {url}: {e}"))? + .into_json::() + .map_err(|e| format!("GET {url}: not JSON: {e}")) +} + +pub fn fetch_history(api_key: &str, api_url: &str, limit: usize, offset: usize) -> Result { + get_json_url( + api_key, + &format!("{}/api/me/hand-history/export?format=json&limit={limit}&offset={offset}", api_url.trim_end_matches('/')), + ) +} + +pub fn fetch_season_me(api_key: &str, api_url: &str) -> Result { + get_json_url(api_key, &format!("{}/api/season/me", api_url.trim_end_matches('/'))) +} + +/// Run until `session.done`, the wall-clock timeout, a fatal error, or reconnects run out. +/// Returns the reason the loop ended. +pub fn run(opts: &LiveOpts, session: &mut Session) -> Result { + let deadline = Instant::now() + opts.timeout; + let mut reconnects = 0u32; + let mut first = true; + let reason: String = 'outer: loop { + if let Some(f) = &session.fatal { + break f.clone(); + } + if Instant::now() >= deadline { + break "timeout".into(); + } + let mut sock = match connect_ws(opts) { + Ok(s) => s, + Err(e) => { + reconnects += 1; + session_anomaly(session, "connect_failed", &e); + if reconnects > opts.max_reconnects { + return Err(format!("giving up after {reconnects} failed connects: {e}")); + } + std::thread::sleep(Duration::from_secs((2u64 << reconnects.min(5)).min(30))); + continue; + } + }; + // Initial join, or reconcile with the server after a reconnect. + let init: Vec = if first { + session.join_messages() + } else { + match get_json(opts, "/api/me/active-game") { + Ok(v) if v.get("playing").and_then(Value::as_bool) == Some(true) => { + let tid = v + .get("table_id") + .and_then(Value::as_str) + .or_else(|| v.pointer("/table/table_id").and_then(Value::as_str)) + .map(str::to_string); + session_anomaly(session, "reconnect_resync", &format!("table {tid:?}")); + session.resync_message(tid.as_deref()).into_iter().collect() + } + Ok(_) => session.join_messages(), + Err(e) => { + session_anomaly(session, "active_game_failed", &e); + session.join_messages() + } + } + }; + first = false; + for m in &init { + if let Err(e) = send(&mut sock, m) { + session_anomaly(session, "send_failed", &e); + } + } + let mut left_at: Option = None; + loop { + if session.done && left_at.is_none() { + left_at = Some(Instant::now()); + } + if let Some(t) = left_at { + // Give the server a moment to confirm leave_table, then close. + if t.elapsed() > Duration::from_secs(3) { + let _ = sock.close(None); + break 'outer if let Some(f) = &session.fatal { f.clone() } else { "done".to_string() }; + } + } else if Instant::now() >= deadline { + for m in session.leave_messages() { + let _ = send(&mut sock, &m); + } + std::thread::sleep(Duration::from_millis(500)); + let _ = sock.close(None); + break 'outer "timeout".into(); + } + match sock.read() { + Ok(Message::Text(t)) => { + let Ok(v) = serde_json::from_str::(&t) else { + session_anomaly(session, "invalid_json", &t.chars().take(200).collect::()); + continue; + }; + let out = session.on_message(&v); + let mut failed = false; + for m in out { + if let Err(e) = send(&mut sock, &m) { + session_anomaly(session, "send_failed", &e); + failed = true; + break; + } + } + if failed { + break; + } + if session.fatal.is_some() { + let _ = sock.close(None); + break 'outer session.fatal.clone().unwrap(); + } + } + Ok(Message::Close(c)) => { + session_anomaly(session, "closed_by_server", &format!("{c:?}")); + if session.done { + break 'outer "done".into(); + } + break; + } + Ok(_) => {} + Err(tungstenite::Error::Io(e)) + if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => + { + let _ = sock.flush(); + for m in session.on_idle() { + if send(&mut sock, &m).is_err() { + break; + } + } + } + Err(e) => { + session_anomaly(session, "read_failed", &e.to_string()); + if session.done { + break 'outer "done".into(); + } + break; + } + } + } + // Dropped out of the read loop: reconnect. + reconnects += 1; + if reconnects > opts.max_reconnects { + return Err(format!("giving up after {reconnects} reconnects")); + } + std::thread::sleep(Duration::from_secs((1u64 << reconnects.min(4)).min(15))); + }; + session.finish(&reason); + Ok(reason) +} + +fn session_anomaly(session: &mut Session, what: &str, details: &str) { + session.note(json!({"kind": "anomaly", "what": what, "details": details, "t": now_ms()})); +} diff --git a/arena/openpoker/src/main.rs b/arena/openpoker/src/main.rs new file mode 100644 index 00000000..9d153a53 --- /dev/null +++ b/arena/openpoker/src/main.rs @@ -0,0 +1,241 @@ +//! `openpoker` CLI. +//! +//! ```text +//! openpoker live --policy builtin:tag|compact:PATH|search:PATH [--sizing S] [--buckets DIR] [--hands N] +//! [--search-threads 16] [--search-budget-ms 5000] [--search-buckets DIR] [--set k=v,...] +//! [--buy-in 2000] [--timeout-sec S] [--trace FILE] [--seed N] [--hu fallback|policy] +//! [--env FILE] [--no-raw] [--no-auto-rebuy] [--max-stack-bb 150] +//! openpoker offline --policy ... [--hands N] [--seed S] [--trace FILE] (mock table, no network) +//! openpoker analyze --trace FILE | --history FILE [--json] [--mc N] +//! openpoker export --out FILE [--limit N] [--offset N] [--env FILE] +//! openpoker season [--env FILE] +//! ``` + +use bench::bp::{bucketer_by_name, sizing_by_name, BlueprintPolicy}; +use bench::builtin::builtin; +use bench::compact::CompactPolicy; +use bench::policy::PolicyFactory; +use openpoker::analyze::{analyze, load_history, load_trace}; +use openpoker::live::{self, LiveOpts}; +use openpoker::searchpol::{self, SearchOpts}; +use openpoker::session::{HuMode, PolicySpec, Session, SessionConfig}; +use openpoker::trace::FileSink; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +struct Args(HashMap); +impl Args { + fn get(&self, k: &str, d: &str) -> String { + self.0.get(k).cloned().unwrap_or_else(|| d.to_string()) + } + fn opt(&self, k: &str) -> Option { + self.0.get(k).cloned().filter(|v| !v.is_empty()) + } + fn num(&self, k: &str, d: T) -> T { + self.0.get(k).and_then(|v| v.parse().ok()).unwrap_or(d) + } + fn flag(&self, k: &str) -> bool { + self.0.contains_key(k) + } +} + +fn main() { + let argv: Vec = std::env::args().collect(); + let cmd = argv.get(1).cloned().unwrap_or_default(); + let mut m = HashMap::new(); + let mut i = 2; + while i < argv.len() { + let k = argv[i].trim_start_matches("--").to_string(); + if i + 1 < argv.len() && !argv[i + 1].starts_with("--") { + m.insert(k, argv[i + 1].clone()); + i += 2; + } else { + m.insert(k, String::new()); + i += 1; + } + } + if let Err(e) = run(&cmd, &Args(m)) { + eprintln!("error: {e}"); + std::process::exit(1); + } +} + +fn parse_policy(spec: &str, a: &Args) -> Result<(Arc, bool), String> { + let buckets = a.get("buckets", "coarse"); + let bucketer_name = if buckets == "coarse" || buckets.starts_with("tables:") { buckets } else { format!("tables:{buckets}") }; + let sizing = a.get("sizing", "pluribus"); + if let Some(name) = spec.strip_prefix("builtin:") { + return Ok((builtin(name).ok_or(format!("unknown builtin {name}"))?, false)); + } + if let Some(path) = spec.strip_prefix("compact:") { + let b = bucketer_by_name(&bucketer_name).ok_or(format!("cannot load buckets {bucketer_name}"))?; + let s = sizing_by_name(&sizing).ok_or(format!("unknown sizing {sizing}"))?; + return Ok((Arc::new(CompactPolicy::open(Path::new(path), b, s)?), true)); + } + if let Some(path) = spec.strip_prefix("search:") { + let b = bucketer_by_name(&bucketer_name).ok_or(format!("cannot load buckets {bucketer_name}"))?; + let s = sizing_by_name(&sizing).ok_or(format!("unknown sizing {sizing}"))?; + let o = SearchOpts { + threads: a.num("search-threads", 16), + budget_ms: a.num("search-budget-ms", 5000), + sets: a.get("set", ""), + search_buckets: a.opt("search-buckets"), + }; + return Ok((Arc::new(searchpol::build(Path::new(path), b, s, &o)?), true)); + } + if let Some(path) = spec.strip_prefix("bp:") { + let p = BlueprintPolicy::from_file(Path::new(path), &bucketer_name, &sizing, a.num("capacity", 1usize << 26))?; + return Ok((Arc::new(p), true)); + } + Err(format!("policy must be builtin:NAME | compact:PATH | bp:PATH, got {spec}")) +} + +fn run(cmd: &str, a: &Args) -> Result<(), String> { + match cmd { + "live" => cmd_live(a), + "offline" => cmd_offline(a), + "analyze" => cmd_analyze(a), + "export" => { + let key = live::load_api_key(a.opt("env").as_deref().map(Path::new))?; + let v = live::fetch_history(&key, live::API_URL, a.num("limit", 100), a.num("offset", 0))?; + let out = a.opt("out").ok_or("--out FILE required")?; + std::fs::write(&out, serde_json::to_string(&v).unwrap()).map_err(|e| e.to_string())?; + println!("wrote {out}"); + Ok(()) + } + "season" => { + let key = live::load_api_key(a.opt("env").as_deref().map(Path::new))?; + println!("{}", serde_json::to_string_pretty(&live::fetch_season_me(&key, live::API_URL)?).unwrap()); + Ok(()) + } + _ => { + println!("usage: openpoker ... (see arena/openpoker/README.md)"); + Ok(()) + } + } +} + +fn cmd_live(a: &Args) -> Result<(), String> { + let policy = a.get("policy", "builtin:tag"); + let (main_f, embed6) = parse_policy(&policy, a)?; + let fallback = builtin(&a.get("fallback", "tag")).ok_or("unknown --fallback builtin")?; + let hu = match a.get("hu", "fallback").as_str() { + "policy" => HuMode::Policy, + "fallback" => HuMode::Fallback, + o => return Err(format!("--hu must be fallback|policy, got {o}")), + }; + let key = live::load_api_key(a.opt("env").as_deref().map(Path::new))?; + let ts = openpoker::trace::now_ms(); + let trace_path: PathBuf = a.opt("trace").map(PathBuf::from).unwrap_or_else(|| format!("logs/openpoker-{ts}.jsonl").into()); + let sink = FileSink::create(&trace_path).map_err(|e| format!("trace {}: {e}", trace_path.display()))?; + let cfg = SessionConfig { + buy_in: a.num("buy-in", 2000), + target_hands: a.num("hands", 10), + seed: a.num("seed", 1), + auto_rebuy: !a.flag("no-auto-rebuy"), + raw: !a.flag("no-raw"), + sizing: a.get("sizing", "pluribus"), + buckets: a.get("buckets", "coarse"), + max_stack_bb: a.num("max-stack-bb", 150.0), + }; + let spec_main = main_f.clone(); + let spec = PolicySpec { label: policy.clone(), main: main_f, embed6, fallback, hu }; + let mut session = Session::new(cfg, spec, Box::new(sink)); + let opts = LiveOpts { + ws_url: a.get("ws-url", live::WS_URL), + api_url: a.get("api-url", live::API_URL), + api_key: key, + timeout: Duration::from_secs(a.num("timeout-sec", 3600)), + max_reconnects: a.num("max-reconnects", 8), + }; + eprintln!("openpoker live: policy={policy} hands={} buy_in={} trace={}", session.cfg.target_hands, session.cfg.buy_in, trace_path.display()); + let reason = live::run(&opts, &mut session)?; + println!("ended: {reason}"); + if let Some(r) = spec_main.report() { + println!("policy report: {r}"); + } + println!("{}", serde_json::to_string_pretty(&session.counters).unwrap()); + if let Ok(text) = std::fs::read_to_string(&trace_path) { + let (hands, sum) = load_trace(&text); + println!("trace: {} lines, {} rejects, {} anomalies, {} hand records", sum.lines, sum.rejects, sum.anomalies, hands.len()); + println!("{}", analyze(&hands, 20_000).render()); + } + Ok(()) +} + +fn cmd_analyze(a: &Args) -> Result<(), String> { + let mc: usize = a.num("mc", 20_000); + let (hands, note) = if let Some(p) = a.opt("trace") { + let text = std::fs::read_to_string(&p).map_err(|e| format!("{p}: {e}"))?; + let (h, s) = load_trace(&text); + (h, format!("trace {p}: {} lines ({} bad), {} decisions, {} acks, {} rejects, {} anomalies", s.lines, s.bad_lines, s.decisions, s.acks, s.rejects, s.anomalies)) + } else if let Some(p) = a.opt("history") { + let text = std::fs::read_to_string(&p).map_err(|e| format!("{p}: {e}"))?; + let v: serde_json::Value = serde_json::from_str(&text).map_err(|e| format!("{p}: {e}"))?; + (load_history(&v), format!("history {p}")) + } else { + return Err("analyze needs --trace FILE or --history FILE".into()); + }; + let r = analyze(&hands, mc); + if a.flag("json") { + println!("{}", serde_json::to_string_pretty(&r).unwrap()); + } else { + println!("{note}\n{}", r.render()); + } + Ok(()) +} + +/// Play a mock table (5 simple bots) through the real `Session` message path; prints counters and +/// the per-decision latency distribution. No network, no API key. +fn cmd_offline(a: &Args) -> Result<(), String> { + let policy = a.get("policy", "builtin:tag"); + let (main_f, embed6) = parse_policy(&policy, a)?; + let fallback = builtin(&a.get("fallback", "tag")).ok_or("unknown --fallback builtin")?; + let sink = openpoker::trace::MemSink::default(); + let cfg = SessionConfig { + buy_in: 2000, + target_hands: a.num("hands", 100), + seed: a.num("seed", 1), + auto_rebuy: true, + raw: false, + sizing: a.get("sizing", "pluribus"), + buckets: a.get("buckets", "coarse"), + max_stack_bb: a.num("max-stack-bb", 0.0), + }; + let spec_main = main_f.clone(); + let spec = PolicySpec { label: policy.clone(), main: main_f, embed6, fallback, hu: HuMode::Fallback }; + let mut session = Session::new(cfg, spec, Box::new(sink.clone())); + let hands: usize = a.num("hands", 100); + let t = std::time::Instant::now(); + let res = openpoker::offline::run(&mut session, hands, a.num("seed", 1)); + let el = t.elapsed().as_secs_f64(); + if let Some(p) = a.opt("trace") { + let mut f = FileSink::create(Path::new(&p)).map_err(|e| e.to_string())?; + for r in sink.records() { + openpoker::trace::TraceSink::emit(&mut f, r); + } + } + let dec = sink.of_kind("decision"); + let mut lat: Vec = dec.iter().filter_map(|d| d["latency_us"].as_u64()).collect(); + lat.sort_unstable(); + let fb = dec.iter().filter(|d| !d["fallback_reason"].is_null()).count(); + println!("offline: {} hands in {el:.1}s, {} decisions, policy fallbacks {fb}", res.hands, dec.len()); + if !lat.is_empty() { + let q = |p: f64| lat[((lat.len() - 1) as f64 * p).round() as usize] as f64 / 1e3; + println!( + "decision latency ms (all decisions): mean {:.1} p50 {:.1} p95 {:.1} max {:.1}", + lat.iter().sum::() as f64 / lat.len() as f64 / 1e3, + q(0.5), + q(0.95), + *lat.last().unwrap() as f64 / 1e3 + ); + } + if let Some(r) = spec_main.report() { + println!("policy report (search decisions only): {r}"); + } + println!("hero net {:+} op-chips over {} hands; session counters:", res.hero_net, res.hands); + println!("{}", serde_json::to_string(&session.counters).unwrap()); + res.error.map_or(Ok(()), Err) +} diff --git a/arena/openpoker/src/mapping.rs b/arena/openpoker/src/mapping.rs new file mode 100644 index 00000000..b10e91d4 --- /dev/null +++ b/arena/openpoker/src/mapping.rs @@ -0,0 +1,216 @@ +//! nlhe `Action` (our chips) -> a legal Open Poker action (their chips). +//! +//! Open Poker's raise amount is a raise-to total on the current street, which is exactly +//! nlhe's `RaiseTo`, so mapping is: divide by [`crate::SCALE`], round, clamp into the advertised +//! `[min, max]`. Anything the server does not offer degrades to the closest passive action. + +use crate::layout::unscale; +use crate::proto::ValidSet; +use nlhe::Action; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OpAction { + pub action: String, + pub amount: Option, +} + +impl OpAction { + fn simple(a: &str) -> Self { + OpAction { action: a.into(), amount: None } + } + fn raise(x: i64) -> Self { + OpAction { action: "raise".into(), amount: Some(x) } + } + pub fn label(&self) -> String { + match self.amount { + Some(a) => format!("{}:{a}", self.action), + None => self.action.clone(), + } + } +} + +/// How faithfully the nlhe action was realised (for the trace). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Fidelity { + Exact, + /// Raise size rounded/clamped: (wanted, sent) in Open Poker chips. + Adjusted(i64, i64), + /// The wanted action was not on offer; this is the substitute. + Degraded(&'static str), +} + +pub fn map_action(a: Action, v: &ValidSet) -> (OpAction, Fidelity) { + match a { + Action::Fold => { + if v.fold { + (OpAction::simple("fold"), Fidelity::Exact) + } else { + (passive(v), Fidelity::Degraded("fold not offered")) + } + } + Action::Check => { + if v.check { + (OpAction::simple("check"), Fidelity::Exact) + } else if v.call.is_some() { + (OpAction::simple("call"), Fidelity::Degraded("check not offered")) + } else { + (passive(v), Fidelity::Degraded("check not offered")) + } + } + Action::Call => { + if v.call.is_some() { + (OpAction::simple("call"), Fidelity::Exact) + } else if v.check { + (OpAction::simple("check"), Fidelity::Degraded("call not offered")) + } else { + (passive(v), Fidelity::Degraded("call not offered")) + } + } + Action::RaiseTo(t) => { + let want = unscale(t); + if let Some((lo, hi)) = v.raise { + let amt = want.clamp(lo, hi); + let f = if amt == want { Fidelity::Exact } else { Fidelity::Adjusted(want, amt) }; + (OpAction::raise(amt), f) + } else if v.all_in.is_some() { + // Only a (short) all-in is possible; it is the nearest aggressive action. + (OpAction::simple("all_in"), Fidelity::Degraded("raise not offered; all_in")) + } else if v.call.is_some() { + (OpAction::simple("call"), Fidelity::Degraded("raise not offered; call")) + } else if v.check { + (OpAction::simple("check"), Fidelity::Degraded("raise not offered; check")) + } else { + (passive(v), Fidelity::Degraded("raise not offered")) + } + } + } +} + +/// Safest legal action: check, else fold, else call, else all-in. +pub fn passive(v: &ValidSet) -> OpAction { + if v.check { + OpAction::simple("check") + } else if v.fold { + OpAction::simple("fold") + } else if v.call.is_some() { + OpAction::simple("call") + } else if v.all_in.is_some() { + OpAction::simple("all_in") + } else if let Some((lo, _)) = v.raise { + OpAction::raise(lo) + } else { + OpAction::simple("check") + } +} + +/// Effective-stack guard: never commit more than `cap` chips in total in one hand. +/// +/// `prior` = chips committed on earlier streets, `allin_total` = total contribution if we +/// shoved now. A raise/all-in that would exceed `cap` becomes a raise to exactly `cap - prior` +/// on this street, or (if that is not a legal raise) a call, else a check. Folds, checks and +/// calls pass through untouched. Returns the replacement and a trace note. +pub fn cap_action(a: &OpAction, v: &ValidSet, cap: i64, prior: i64, allin_total: i64) -> Option<(OpAction, String)> { + let exceeds = match a.action.as_str() { + "raise" => a.amount.is_some_and(|x| prior + x > cap), + "all_in" => allin_total > cap, + _ => false, + }; + if !exceeds { + return None; + } + let r = cap - prior; + let new = match v.raise { + Some((lo, hi)) if r >= lo => OpAction::raise(r.min(hi)), + _ if v.call.is_some() => OpAction::simple("call"), + _ if v.check => OpAction::simple("check"), + _ => return None, + }; + let note = format!("{} -> {} (cap {cap}, committed on earlier streets {prior})", a.label(), new.label()); + Some((new, note)) +} + +/// Is `a` something `v` offers? (Used by tests and as a last assertion before sending.) +pub fn is_legal(a: &OpAction, v: &ValidSet) -> bool { + match a.action.as_str() { + "fold" => v.fold, + "check" => v.check, + "call" => v.call.is_some(), + "all_in" => v.all_in.is_some(), + "raise" => match (a.amount, v.raise) { + (Some(x), Some((lo, hi))) => x >= lo && x <= hi, + _ => false, + }, + _ => false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use cards::Rng; + + fn vs(fold: bool, check: bool, call: Option, raise: Option<(i64, i64)>, all_in: Option>) -> ValidSet { + ValidSet { fold, check, call, raise, all_in } + } + + #[test] + fn raise_scaling_rounding_and_clamp() { + let v = vs(true, false, Some(20), Some((40, 500)), None); + // 5x chips: 300 -> 60 + assert_eq!(map_action(Action::RaiseTo(300), &v), (OpAction::raise(60), Fidelity::Exact)); + // 303 rounds to 61 (60.6), not exact + assert_eq!(map_action(Action::RaiseTo(303), &v).0, OpAction::raise(61)); + // below min -> min, above max -> max + assert_eq!(map_action(Action::RaiseTo(100), &v), (OpAction::raise(40), Fidelity::Adjusted(20, 40))); + assert_eq!(map_action(Action::RaiseTo(10_000), &v), (OpAction::raise(500), Fidelity::Adjusted(2000, 500))); + } + + #[test] + fn degrade_when_not_offered() { + let only_call = vs(true, false, Some(20), None, None); + assert_eq!(map_action(Action::RaiseTo(500), &only_call).0, OpAction::simple("call")); + let short_shove = vs(true, false, Some(20), None, Some(Some(30))); + assert_eq!(map_action(Action::RaiseTo(500), &short_shove).0, OpAction::simple("all_in")); + let free = vs(false, true, None, Some((20, 100)), None); + assert_eq!(map_action(Action::Fold, &free).0, OpAction::simple("check")); + assert_eq!(map_action(Action::Call, &free).0, OpAction::simple("check")); + let facing = vs(true, false, Some(20), Some((40, 100)), None); + assert_eq!(map_action(Action::Check, &facing).0, OpAction::simple("call")); + } + + /// Fuzz: whatever the (random) offered set and the engine action, the output is offered. + #[test] + fn fuzz_always_legal() { + let mut rng = Rng::new(42); + let mut n = 0; + for _ in 0..200_000 { + let mut v = ValidSet::default(); + v.fold = rng.below(2) == 0; + v.check = !v.fold && rng.below(4) != 0 || rng.below(8) == 0; + if rng.below(2) == 0 { + v.call = Some(rng.below(3000) as i64); + } + if rng.below(3) != 0 { + let lo = 1 + rng.below(2000) as i64; + v.raise = Some((lo, lo + rng.below(3000) as i64)); + } + if rng.below(4) == 0 { + v.all_in = Some(if rng.below(2) == 0 { Some(rng.below(900) as i64) } else { None }); + } + if v.is_empty() { + continue; + } + let a = match rng.below(4) { + 0 => Action::Fold, + 1 => Action::Check, + 2 => Action::Call, + _ => Action::RaiseTo(rng.below(40_000) as i32), + }; + let (m, _) = map_action(a, &v); + assert!(is_legal(&m, &v), "{a:?} -> {m:?} not in {v:?}"); + assert!(is_legal(&passive(&v), &v), "passive illegal in {v:?}"); + n += 1; + } + assert!(n > 100_000); + } +} diff --git a/arena/openpoker/src/offline.rs b/arena/openpoker/src/offline.rs new file mode 100644 index 00000000..20a68de9 --- /dev/null +++ b/arena/openpoker/src/offline.rs @@ -0,0 +1,208 @@ +//! Offline mock table: drives a [`Session`] through the real message path (`hand_start`, +//! `your_turn`, `player_action`, `hand_result`, ...) with five simple scripted opponents, no +//! network. Used by the smoke tests and by `openpoker offline` for latency measurement. +//! +//! Chips are Open Poker chips (blinds 10/20, stacks 2000 reset every hand); the mock keeps an +//! `nlhe` engine at x[`SCALE`] internally. The hero sits in seat 2 and the dealer rotates. + +use crate::layout::{scale, unscale}; +use crate::session::Session; +use crate::SCALE; +use cards::{card_str, Card, Rng}; +use nlhe::{Action, Deal, GameConfig, State, Step}; +use serde_json::{json, Value}; + +pub const HERO: usize = 2; + +#[derive(Debug, Default)] +pub struct OfflineResult { + pub hands: usize, + /// Hero net result in Open Poker chips. + pub hero_net: i64, + /// Protocol-level problem (no/odd answer to a `your_turn`), if any. + pub error: Option, +} + +fn names(stacks: &[i64; 6]) -> Vec { + (0..6).map(|i| json!({"seat": i, "name": format!("bot{i}"), "stack": stacks[i]})).collect() +} + +fn bot_action(st: &State, rng: &mut Rng) -> Action { + let l = st.legal(); + let r = rng.f64(); + let want_raise = if l.can_fold { r >= 0.85 } else { r >= 0.65 }; + if want_raise && l.can_raise { + if rng.f64() < 0.06 { + return Action::RaiseTo(l.max_raise_to); + } + let frac = [0.5, 0.75, 1.0, 2.0][rng.below(4) as usize]; + let want = st.cur_bet() as f64 + frac * st.pot() as f64; + let t = ((want / SCALE as f64).round() as i32 * SCALE).clamp(l.min_raise_to, l.max_raise_to); + return Action::RaiseTo(t); + } + if l.can_fold { + if r < 0.25 { + Action::Fold + } else { + Action::Call + } + } else { + Action::Check + } +} + +fn pa(op: usize, a: Action, st_before: &State, st_after: &State, nl: usize, street: &str) -> Value { + let (name, amount) = match a { + Action::Fold => ("fold", None), + Action::Check => ("check", None), + Action::Call => ("call", Some(unscale(st_before.legal().call_amount))), + Action::RaiseTo(t) => ("raise", Some(unscale(t))), + }; + json!({"type":"player_action","seat":op,"name":format!("bot{op}"),"action":name,"amount":amount, + "street":street,"stack":unscale(st_after.stack(nl)),"pot":unscale(st_after.pot())}) +} + +fn street_name(s: nlhe::Street) -> &'static str { + ["preflop", "flop", "turn", "river"][s.idx()] +} + +/// Play `hands` hands. Stops early (with `error`) if the session misbehaves at the protocol level. +pub fn run(session: &mut Session, hands: usize, seed: u64) -> OfflineResult { + let mut stacks = [2000i64; 6]; + let mut res = OfflineResult::default(); + let mut rng = Rng::new(seed ^ 0x6f66666c696e65); + session.on_message(&json!({"type":"connected","agent_id":"a","name":"me"})); + session.on_message(&json!({"type":"table_joined","table_id":"t1","seat":HERO,"players":names(&[2000; 6])})); + for hn in 0..hands { + match play_hand(session, hn, &mut stacks, &mut rng, &mut res) { + Ok(()) => res.hands += 1, + Err(e) => { + res.error = Some(format!("hand {hn}: {e}")); + break; + } + } + } + res +} + +fn play_hand(session: &mut Session, hn: usize, stacks: &mut [i64; 6], rng: &mut Rng, res: &mut OfflineResult) -> Result<(), String> { + // Stacks carry over; a seat that dropped below 10 big blinds rebuys to 2000 (announced). + for (op, st) in stacks.iter_mut().enumerate() { + if *st < 200 { + *st = 2000; + session.on_message(&json!({"type":"player_joined","seat":op,"name":format!("bot{op}"),"stack":2000})); + } + } + let id = format!("h{hn}"); + let dealer = hn % 6; + let op_of = |nl: usize| (dealer + 1 + nl) % 6; + let nl_of = |op: usize| (op + 6 - dealer - 1) % 6; + let hero_nl = nl_of(HERO); + let deal = Deal::random(rng); + let nl_stacks: Vec = (0..6).map(|nl| scale(stacks[op_of(nl)])).collect(); + let cfg = GameConfig::new(6).with_stacks(&nl_stacks); + let mut st = State::new(&cfg); + let cs = |cs: &[Card]| cs.iter().map(|&c| card_str(c)).collect::>(); + session.on_message(&json!({"type":"hand_start","hand_id":id,"seat":HERO,"dealer_seat":dealer,"blinds":{"small_blind":10,"big_blind":20}})); + session.on_message(&json!({"type":"hole_cards","cards":cs(&deal.holes[hero_nl])})); + let mut shown = 0usize; + let mut turn = 0usize; + let players_json = |st: &State| -> Value { + Value::Array( + (0..6) + .map(|op| { + let nl = nl_of(op); + let status = if st.is_folded(nl) { "folded" } else if st.is_all_in(nl) { "all_in" } else { "active" }; + json!({"seat": op, "name": format!("bot{op}"), "stack": unscale(st.stack(nl)), "status": status}) + }) + .collect(), + ) + }; + let mut step = Step::Continue; + while let Some(nl) = st.to_act() { + let op = op_of(nl); + let before = st; + let street = street_name(st.street()); + let a = if op == HERO { + turn += 1; + let l = st.legal(); + let mut va = vec![]; + if l.can_fold { + va.push(json!({"action":"fold"})); + } + if l.can_check { + va.push(json!({"action":"check"})); + } else { + va.push(json!({"action":"call","amount":unscale(l.call_amount)})); + } + if l.can_raise { + va.push(json!({"action":"raise","min":unscale(l.min_raise_to),"max":unscale(l.max_raise_to)})); + } + let tok = format!("{id}-t{turn}"); + let board = cs(&deal.board[..st.street().board_len()]); + let out = session.on_message(&json!({"type":"your_turn","hand_id":id,"turn_token":tok,"valid_actions":va, + "pot":unscale(st.pot()),"community_cards":board,"players":players_json(&st),"min_raise":null,"max_raise":null})); + let m = out.iter().find(|m| m["type"] == "action").ok_or("no action sent for your_turn")?.clone(); + let amt = m["amount"].as_i64(); + let a = match m["action"].as_str().unwrap_or("") { + "fold" if l.can_fold => Action::Fold, + "fold" | "check" => Action::Check, + "call" => Action::Call, + "raise" => Action::RaiseTo(scale(amt.ok_or("raise without amount")?).clamp(l.min_raise_to, l.max_raise_to)), + "all_in" => Action::RaiseTo(l.max_raise_to), + o => return Err(format!("unexpected action {o}")), + }; + let a = if matches!(a, Action::RaiseTo(_)) && !l.can_raise { Action::Call } else { a }; + let a = if a == Action::Call && l.can_check { Action::Check } else { a }; + session.on_message(&json!({"type":"action_ack","client_action_id":m["client_action_id"],"status":"accepted"})); + a + } else { + bot_action(&st, rng) + }; + step = st.apply(a); + session.on_message(&pa(op, a, &before, &st, nl, street)); + match step { + Step::NewStreet(s) => { + let to = s.board_len(); + session.on_message(&json!({"type":"community_cards","cards":cs(&deal.board[shown..to]),"street":street_name(s)})); + shown = to; + } + Step::Terminal => break, + Step::Continue => {} + } + } + debug_assert!(step == Step::Terminal || st.is_terminal()); + // All-in run-out: the server deals the remaining board before the result. + if st.showdown() { + for to in [3usize, 4, 5] { + if to > shown { + session.on_message(&json!({"type":"community_cards","cards":cs(&deal.board[shown..to])})); + shown = to; + } + } + } + let pay = st.payoffs(&deal); + let mut fin = serde_json::Map::new(); + let mut payouts = vec![]; + let mut winners = vec![]; + for nl in 0..6 { + let op = op_of(nl); + let net = unscale(pay[nl]); + stacks[op] += net; + fin.insert(op.to_string(), json!(stacks[op])); + let gross = unscale(pay[nl] + st.contributed(nl)); + if gross > 0 { + payouts.push(json!({"seat": op, "amount": gross})); + winners.push(json!({"seat": op, "name": format!("bot{op}"), "amount": net, "stack": stacks[op]})); + } + } + res.hero_net += unscale(pay[hero_nl]); + let shown_cards: serde_json::Map = if st.showdown() { + (0..6).filter(|&nl| !st.is_folded(nl)).map(|nl| (op_of(nl).to_string(), json!(cs(&deal.holes[nl])))).collect() + } else { + Default::default() + }; + session.on_message(&json!({"type":"hand_result","hand_id":id,"pot":unscale(st.pot()),"total_pot":unscale(st.pot()), + "winners":winners,"payouts":payouts,"shown_cards":shown_cards,"final_stacks":fin})); + Ok(()) +} diff --git a/arena/openpoker/src/proto.rs b/arena/openpoker/src/proto.rs new file mode 100644 index 00000000..ec9a94c4 --- /dev/null +++ b/arena/openpoker/src/proto.rs @@ -0,0 +1,405 @@ +//! Tolerant parsing of Open Poker server messages and builders for client messages. +//! +//! The docs (docs.openpoker.ai/llms-full.txt) fix the message names and the main fields, but +//! several payload shapes (`final_stacks`, `payouts`, `replayed_events`, `players[].status`) +//! are only loosely specified. Everything here accepts either shape we could plausibly see and +//! never panics on unexpected input; unknown pieces simply come back as `None`. + +use cards::{parse_card, Card}; +use serde_json::{json, Value}; + +pub fn as_i64(v: &Value) -> Option { + match v { + Value::Number(n) => n.as_i64().or_else(|| n.as_f64().map(|f| f.round() as i64)), + Value::String(s) => s.trim().parse::().ok().map(|f| f.round() as i64), + _ => None, + } +} + +pub fn get_i64(v: &Value, k: &str) -> Option { + v.get(k).and_then(as_i64) +} + +pub fn get_u64(v: &Value, k: &str) -> Option { + v.get(k).and_then(as_i64).filter(|x| *x >= 0).map(|x| x as u64) +} + +pub fn get_str<'a>(v: &'a Value, k: &str) -> Option<&'a str> { + v.get(k).and_then(Value::as_str) +} + +pub fn msg_type(v: &Value) -> &str { + get_str(v, "type").unwrap_or("") +} + +/// `"Ah"`, `"10h"`, `"Th"` -> card. +pub fn parse_op_card(s: &str) -> Option { + let s = s.trim(); + if let Some(rest) = s.strip_prefix("10") { + return parse_card(&format!("T{rest}")); + } + parse_card(s) +} + +pub fn parse_cards_value(v: Option<&Value>) -> Vec { + v.and_then(Value::as_array) + .map(|a| { + a.iter() + .filter_map(|c| c.as_str().and_then(parse_op_card)) + .collect() + }) + .unwrap_or_default() +} + +#[derive(Clone, Debug, PartialEq)] +pub struct ValidAction { + pub action: String, + pub amount: Option, + pub min: Option, + pub max: Option, +} + +pub fn parse_valid_actions(v: Option<&Value>) -> Vec { + v.and_then(Value::as_array) + .map(|a| { + a.iter() + .filter_map(|x| { + // Either {"action": "call", "amount": 20} or a bare string "fold". + if let Some(s) = x.as_str() { + return Some(ValidAction { + action: s.to_string(), + amount: None, + min: None, + max: None, + }); + } + Some(ValidAction { + action: get_str(x, "action")?.to_string(), + amount: get_i64(x, "amount"), + min: get_i64(x, "min"), + max: get_i64(x, "max"), + }) + }) + .collect() + }) + .unwrap_or_default() +} + +/// What the server allows right now, in Open Poker chips. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ValidSet { + pub fold: bool, + pub check: bool, + /// Chips to call (as advertised; `Some(0)` if advertised without amount). + pub call: Option, + /// (min, max) raise-to. + pub raise: Option<(i64, i64)>, + /// All-in (distinct from raise): its amount if advertised. + pub all_in: Option>, +} + +impl ValidSet { + pub fn from_actions(va: &[ValidAction], min_raise: Option, max_raise: Option) -> Self { + let mut s = ValidSet::default(); + for a in va { + match a.action.as_str() { + "fold" => s.fold = true, + "check" => s.check = true, + "call" => s.call = Some(a.amount.unwrap_or(0)), + "raise" | "bet" => { + let lo = a.min.or(min_raise).unwrap_or(0); + let hi = a.max.or(max_raise).unwrap_or(lo); + s.raise = Some((lo, hi.max(lo))); + } + "all_in" | "allin" => s.all_in = Some(a.amount), + _ => {} + } + } + s + } + pub fn is_empty(&self) -> bool { + !self.fold && !self.check && self.call.is_none() && self.raise.is_none() && self.all_in.is_none() + } + pub fn describe(&self) -> Vec { + let mut v = Vec::new(); + if self.fold { + v.push("fold".into()); + } + if self.check { + v.push("check".into()); + } + if let Some(c) = self.call { + v.push(format!("call:{c}")); + } + if let Some((a, b)) = self.raise { + v.push(format!("raise:{a}-{b}")); + } + if let Some(a) = self.all_in { + v.push(format!("all_in:{}", a.map_or("?".into(), |x| x.to_string()))); + } + v + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct PlayerInfo { + pub seat: usize, + pub name: Option, + pub stack: Option, + /// Chips committed on the current street (`table_state.seats[].bet`). + pub bet: Option, + pub in_hand: Option, + pub status: Option, +} + +impl PlayerInfo { + /// Was this seat dealt into the current hand (as far as the message tells)? + /// `None` if the message does not say. + pub fn dealt_in(&self) -> Option { + if let Some(s) = &self.status { + let s = s.to_ascii_lowercase(); + if matches!( + s.as_str(), + "sitting_out" | "sit_out" | "sitout" | "empty" | "out" | "busted" | "left" | "away" | "waiting" | "disconnected" + ) { + return Some(false); + } + if matches!(s.as_str(), "folded" | "active" | "all_in" | "allin" | "in_hand" | "playing" | "acting" | "to_act") { + return Some(true); + } + } + // `in_hand == true` is conclusive; `false` is ambiguous (folded vs sitting out). + match self.in_hand { + Some(true) => Some(true), + _ => None, + } + } + pub fn folded_hint(&self) -> bool { + self.status.as_deref().is_some_and(|s| s.eq_ignore_ascii_case("folded")) + } +} + +pub fn parse_players(v: Option<&Value>) -> Vec { + let mut out = Vec::new(); + let Some(a) = v.and_then(Value::as_array) else { + return out; + }; + for p in a { + // Entries may be null for empty seats in `table_state.seats`. + let Some(seat) = p.get("seat").and_then(as_i64) else { + continue; + }; + if !(0..64).contains(&seat) { + continue; + } + out.push(PlayerInfo { + seat: seat as usize, + name: get_str(p, "name").map(str::to_string), + stack: get_i64(p, "stack"), + bet: get_i64(p, "bet"), + in_hand: p.get("in_hand").and_then(Value::as_bool).or_else(|| { + p.get("folded").and_then(Value::as_bool).map(|f| !f) + }), + status: get_str(p, "status").map(str::to_string), + }); + } + out +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ObsKind { + Fold, + Check, + Call, + Raise, + AllIn, + /// Blind posts and anything we do not model. + Ignored, +} + +/// A `player_action` broadcast (also the form of entries in `hand_result.actions`). +#[derive(Clone, Debug, PartialEq)] +pub struct ActionObs { + pub seat: usize, + pub name: Option, + pub kind: ObsKind, + pub raw_action: String, + pub amount: Option, + pub street: Option, + /// Actor's stack after the action. + pub stack: Option, + /// Actor's stack before the action (after any blind already posted). + pub stack_before: Option, + /// Chips this action moved into the pot. + pub delta: Option, + /// Pot after the action. + pub pot: Option, + /// `"to_total"` (raise-to on the street) or `"incremental"`. + pub amount_mode: Option, +} + +pub fn parse_obs_kind(s: &str) -> ObsKind { + match s.to_ascii_lowercase().as_str() { + "fold" => ObsKind::Fold, + "check" => ObsKind::Check, + "call" => ObsKind::Call, + "raise" | "bet" => ObsKind::Raise, + "all_in" | "allin" | "all-in" => ObsKind::AllIn, + _ => ObsKind::Ignored, + } +} + +pub fn parse_player_action(v: &Value) -> Option { + let seat = v.get("seat").and_then(as_i64)?; + let raw = get_str(v, "action")?.to_string(); + Some(ActionObs { + seat: usize::try_from(seat).ok()?, + name: get_str(v, "name").map(str::to_string), + kind: parse_obs_kind(&raw), + raw_action: raw, + amount: get_i64(v, "amount"), + street: get_str(v, "street").map(str::to_string), + stack: get_i64(v, "stack_after").or_else(|| get_i64(v, "stack")), + stack_before: get_i64(v, "stack_before"), + delta: get_i64(v, "contribution_delta"), + pot: get_i64(v, "pot_after").or_else(|| get_i64(v, "pot")), + amount_mode: get_str(v, "amount_mode").map(str::to_string), + }) +} + +/// `{"1": 1990, "3": 2010}` or `[{"seat":1,"stack":1990}, ...]` -> (seat, stack) pairs. +pub fn parse_seat_numbers(v: Option<&Value>, value_keys: &[&str]) -> Vec<(usize, i64)> { + let mut out = Vec::new(); + match v { + Some(Value::Object(m)) => { + for (k, x) in m { + if let (Ok(seat), Some(n)) = (k.parse::(), as_i64(x)) { + out.push((seat, n)); + } + } + } + Some(Value::Array(a)) => { + for x in a { + let Some(seat) = x.get("seat").and_then(as_i64) else { continue }; + let n = value_keys.iter().find_map(|k| x.get(*k).and_then(as_i64)); + if let (Ok(seat), Some(n)) = (usize::try_from(seat), n) { + out.push((seat, n)); + } + } + } + _ => {} + } + out.sort_unstable(); + out +} + +// ---- client messages ---- + +pub fn join_lobby(buy_in: i64) -> Value { + json!({"type": "join_lobby", "buy_in": buy_in}) +} +pub fn set_auto_rebuy(enabled: bool) -> Value { + json!({"type": "set_auto_rebuy", "enabled": enabled}) +} +pub fn rebuy() -> Value { + json!({"type": "rebuy", "amount": 1500}) +} +pub fn leave_table() -> Value { + json!({"type": "leave_table"}) +} +pub fn resync_request(table_id: &str, last_table_seq: u64) -> Value { + json!({"type": "resync_request", "table_id": table_id, "last_table_seq": last_table_seq}) +} +pub fn action_msg(hand_id: &str, action: &str, amount: Option, client_action_id: &str, turn_token: &str) -> Value { + let mut m = json!({ + "type": "action", + "hand_id": hand_id, + "action": action, + "client_action_id": client_action_id, + "turn_token": turn_token, + }); + if let Some(a) = amount { + m["amount"] = json!(a); + } + m +} + +/// Codes that mean "your action was not accepted". +pub fn is_rejection_code(code: &str) -> bool { + matches!( + code, + "action_rejected" + | "not_your_turn" + | "stale_hand_action" + | "stale_turn_token" + | "invalid_action" + | "legacy_action_protocol" + | "missing_action_id" + | "action_id_conflict" + | "no_hand_in_progress" + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cards_parse_with_ten() { + assert_eq!(parse_op_card("10h"), parse_card("Th")); + assert_eq!(parse_op_card("Ah"), parse_card("Ah")); + assert_eq!(parse_op_card("zz"), None); + let v = json!(["Ah", "Kd", "bad"]); + assert_eq!(parse_cards_value(Some(&v)).len(), 2); + } + + #[test] + fn valid_actions_shapes() { + let v = json!([{"action":"fold"},{"action":"call","amount":40.0},{"action":"raise","min":80,"max":1990},{"action":"all_in","amount":1990}]); + let s = ValidSet::from_actions(&parse_valid_actions(Some(&v)), None, None); + assert!(s.fold && !s.check); + assert_eq!(s.call, Some(40)); + assert_eq!(s.raise, Some((80, 1990))); + assert_eq!(s.all_in, Some(Some(1990))); + let v = json!(["check", "fold"]); + let s = ValidSet::from_actions(&parse_valid_actions(Some(&v)), None, None); + assert!(s.check && s.fold); + // min/max fall back to top-level fields + let v = json!([{"action":"raise"}]); + let s = ValidSet::from_actions(&parse_valid_actions(Some(&v)), Some(40), Some(500)); + assert_eq!(s.raise, Some((40, 500))); + } + + #[test] + fn player_status_semantics() { + let v = json!([ + {"seat":0,"stack":1000,"status":"sitting_out"}, + {"seat":1,"stack":1000,"status":"folded"}, + {"seat":2,"stack":1000,"in_hand":true}, + {"seat":3,"stack":1000,"in_hand":false}, + null, + {"seat":4,"stack":0,"status":"all_in"} + ]); + let p = parse_players(Some(&v)); + assert_eq!(p.len(), 5); + assert_eq!(p[0].dealt_in(), Some(false)); + assert_eq!(p[1].dealt_in(), Some(true)); + assert!(p[1].folded_hint()); + assert_eq!(p[2].dealt_in(), Some(true)); + assert_eq!(p[3].dealt_in(), None); + assert_eq!(p[4].dealt_in(), Some(true)); + } + + #[test] + fn player_action_and_seat_numbers() { + let v = json!({"type":"player_action","seat":3,"name":"x","action":"raise","amount":60,"street":"preflop","stack":1940,"pot":90}); + let a = parse_player_action(&v).unwrap(); + assert_eq!((a.seat, a.kind, a.amount, a.stack, a.pot), (3, ObsKind::Raise, Some(60), Some(1940), Some(90))); + let a = parse_player_action(&json!({"seat":1,"action":"small_blind","amount":10})).unwrap(); + assert_eq!(a.kind, ObsKind::Ignored); + let m = parse_seat_numbers(Some(&json!({"1": 1990, "3": "2010"})), &["stack"]); + assert_eq!(m, vec![(1, 1990), (3, 2010)]); + let m = parse_seat_numbers(Some(&json!([{"seat":2,"stack":5},{"seat":0,"final_stack":7}])), &["stack", "final_stack"]); + assert_eq!(m, vec![(0, 7), (2, 5)]); + } +} diff --git a/arena/openpoker/src/searchpol.rs b/arena/openpoker/src/searchpol.rs new file mode 100644 index 00000000..46cfc0a4 --- /dev/null +++ b/arena/openpoker/src/searchpol.rs @@ -0,0 +1,120 @@ +//! `--policy search:PATH`: a [`SearchPolicy`] over a compact blueprint, wrapped in the +//! time-boxed [`GuardedSearch`]. Mirrors `search/examples/vsbp.rs` (default `SearchParams`, +//! blueprint beliefs, dedicated rayon pool). + +use crate::guard::GuardedSearch; +use bench::bp::sizing_by_name; +use blueprint::compact::Compact; +use blueprint::trainer::Bucketer; +use nlhe::abstraction::{BetSizing, TrackOpts}; +use nlhe::Street; +use search::bp::Blueprint; +use search::policy::SearchPolicy; +use search::solver::SearchParams; +use std::path::Path; +use std::sync::Arc; +use std::time::Duration; + +pub struct SearchOpts { + /// Threads of the dedicated search pool. + pub threads: usize, + /// Hard per-decision budget; slower searches fall back to the blueprint action. + pub budget_ms: u64, + /// `k=v,...` overrides of `SearchParams` (same keys as `vsbp --set`). + pub sets: String, + /// Directory of per-flop search buckets (`SearchParams::search_buckets`); unset = off (default config). + pub search_buckets: Option, +} + +impl Default for SearchOpts { + fn default() -> Self { + SearchOpts { threads: 16, budget_ms: 5000, sets: String::new(), search_buckets: None } + } +} + +/// Parse `--set` overrides. Errors instead of panicking. +pub fn apply_sets(prm: &mut SearchParams, sets: &str) -> Result<(), String> { + fn p(k: &str, v: &str) -> Result { + v.parse().map_err(|_| format!("--set {k}={v}: bad value")) + } + for kv in sets.split(',').filter(|x| !x.is_empty()) { + let (k, v) = kv.split_once('=').unwrap_or((kv, "1")); + let b = v != "0" && v != "false"; + match k { + "iters" => prm.iters = p(k, v)?, + "warm" => prm.warm_start = p(k, v)?, + "focus" => prm.focus_own = p(k, v)?, + "leaf" => prm.leaf = if v == "bp" { search::solver::LeafMode::Blueprint } else { search::solver::LeafMode::Cont4 }, + "final" => prm.play_final = b, + "flop" => prm.search_flop = b, + "turn" => prm.search_turn = b, + "river" => prm.search_river = b, + "pre" => prm.preflop_search = b, + "post" => prm.postflop_search = b, + "bpbeliefs" => prm.blueprint_beliefs = b, + "offbel" => prm.offtree_search_beliefs = b, + "ownbel" => prm.own_search_beliefs = b, + "tremble" => prm.belief_tremble = p(k, v)?, + "prune" => prm.prune_prob = p(k, v)?, + "ms" => prm.max_millis = Some(p(k, v)?), + "minflop" => prm.min_flop_players = p(k, v)?, + "vecmin" => prm.vec_min_street = match v { "flop" => Street::Flop, "turn" => Street::Turn, _ => Street::River }, + "vector" => prm.vector = b, + "sizing" | "later" => { + let s: BetSizing = match v { + "small" => search::tree::small_sizing(), + o => sizing_by_name(o).ok_or(format!("--set {k}={o}: unknown sizing"))?, + }; + if k == "sizing" { + prm.sizing = s; + } else { + prm.later_sizing = s; + } + } + _ => return Err(format!("unknown --set key {k}")), + } + } + Ok(()) +} + +/// Build the guarded search factory over the compact blueprint at `path`. +pub fn build( + path: &Path, + bucketer: Arc, + sizing: BetSizing, + o: &SearchOpts, +) -> Result { + let compact = Arc::new(Compact::open(path).map_err(|e| format!("compact {}: {e}", path.display()))?); + let bp = Blueprint::from_source(compact, bucketer, sizing).with_opts(TrackOpts::default()); + finish(bp, o) +} + +/// Same, over an already-built blueprint (tests). +pub fn finish(bp: Blueprint, o: &SearchOpts) -> Result { + let mut prm = SearchParams::default(); + apply_sets(&mut prm, &o.sets)?; + if let Some(dir) = &o.search_buckets { + let sb = abstraction::search_buckets::SearchBuckets::new( + Some(dir.into()), + abstraction::search_buckets::BuildParams::default(), + 64, + ) + .map_err(|e| format!("search buckets {dir}: {e}"))?; + prm.search_buckets = Some(Arc::new(sb)); + } + prm.parallel = true; + prm.pool = Some(Arc::new( + rayon::ThreadPoolBuilder::new() + .num_threads(o.threads.max(1)) + .thread_name(|i| format!("search-pool-{i}")) + .build() + .map_err(|e| format!("thread pool: {e}"))?, + )); + // Cooperative cap well under the hard budget: a slow search returns a truncated (still + // valid) solution instead of tripping the hard timeout. + if prm.max_millis.is_none() { + prm.max_millis = Some((o.budget_ms * 7 / 10).max(1)); + } + let policy = Arc::new(SearchPolicy::new("search", bp, prm)); + Ok(GuardedSearch::new("search", policy, Duration::from_millis(o.budget_ms))) +} diff --git a/arena/openpoker/src/session.rs b/arena/openpoker/src/session.rs new file mode 100644 index 00000000..a54918bf --- /dev/null +++ b/arena/openpoker/src/session.rs @@ -0,0 +1,1237 @@ +//! The socket-free session state machine: server messages in, client messages out. +//! +//! One `Session` plays any number of hands at whatever tables the matchmaker gives us. All +//! network IO lives in [`crate::live`]; this module is driven by recorded messages in tests. +//! +//! # Per-hand flow +//! `hand_start` opens a context. `player_action` / `community_cards` / `hole_cards` are +//! buffered until our first `your_turn`; then the engine replay is built (start stacks derived +//! from the server's current stacks, see `build_sim`), the policy is queried, the chosen +//! action is mapped to a legal Open Poker action and sent. Later actions are applied as they +//! arrive. `hand_result` closes the hand and emits the `hand` trace record. +//! +//! # Failure policy +//! Anything that makes the replay untrustworthy (unplaceable action, hero not to act per the +//! engine, policy error) marks the hand `desync` and answers with the safest legal action +//! (check, else fold). The hand is still recorded. A rejected action is retried once with the +//! safe action. We never sit out. + +use crate::analyze::{cards_to_strs, shown_from_value, HandAct, HandPlayer, HandRecord}; +use crate::layout::{engine_order, Layout}; +use crate::mapping::{cap_action, is_legal, map_action, passive, Fidelity, OpAction}; +use crate::proto::{self, ActionObs, ObsKind, PlayerInfo, ValidSet}; +use crate::sim::Sim; +use crate::trace::{now_ms, TraceSink}; +use bench::mix; +use bench::policy::PolicyFactory; +use cards::{Card, Rng}; +use nlhe::Action; +use serde::Serialize; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet, HashSet}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum HuMode { + /// Heads-up hands are played by the fallback policy (default; a 6-max blueprint has no + /// heads-up strategy). + Fallback, + /// Heads-up hands go to the main policy on a native 2-player engine (out of distribution + /// for a 6-max blueprint; its history keys will not mean what they meant in training). + Policy, +} + +#[derive(Clone)] +pub struct PolicySpec { + pub label: String, + pub main: Arc, + /// Embed short-handed hands in the 6-max game (blueprints) instead of a native n-player + /// engine (heuristics). + pub embed6: bool, + pub fallback: Arc, + pub hu: HuMode, +} + +#[derive(Clone, Debug)] +pub struct SessionConfig { + pub buy_in: i64, + pub target_hands: usize, + pub seed: u64, + pub auto_rebuy: bool, + pub raw: bool, + pub sizing: String, + pub buckets: String, + /// Stack-depth limit in big blinds (the blueprint/search are trained at 100 bb; Pluribus resets + /// stacks every hand). `0` disables both layers. Layer 1: after a hand, if our stack exceeds + /// this many bb, leave the table and rejoin the lobby with `buy_in`. Layer 2: never commit more + /// than this many bb in total in one hand. + pub max_stack_bb: f64, +} + +/// Hands to wait before trying a stack reset again after the server refused/ignored one. +const RESET_COOLDOWN_HANDS: u64 = 25; +/// Resend `join_lobby` if no table/lobby confirmation arrived within this long. +const REJOIN_RETRY: Duration = Duration::from_secs(15); +const REJOIN_MAX_TRIES: u32 = 6; + +/// Stack-reset state machine (layer 1). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ResetState { + Idle, + /// `leave_table` sent after a hand; waiting for our own `player_left`. + Leaving { hands_seen: u32 }, + /// Left; `join_lobby` sent; waiting for `table_joined`. + Rejoining { since: Instant, tries: u32 }, +} + +#[derive(Clone, Debug, Default, Serialize)] +pub struct Counters { + pub hands_started: u64, + pub hands_done: u64, + pub decisions: u64, + pub acks: u64, + pub rejects: u64, + pub retries: u64, + pub fallbacks: u64, + /// Decisions where the policy itself fell back (e.g. search timeout -> blueprint action). + pub policy_fallbacks: u64, + pub desync_hands: u64, + pub issues: u64, + pub anomalies: u64, + pub resyncs: u64, + pub rebuys: u64, + /// Completed stack resets (left an over-deep table and rejoined with the normal buy-in). + pub stack_resets: u64, + /// Resets that the server refused/ignored (fell back to the effective-stack guard). + pub reset_aborts: u64, + /// Decisions where the effective-stack guard replaced the policy's action. + pub stack_guards: u64, +} + +#[derive(PartialEq, Debug)] +enum PendState { + Sent, + Echoed, + Synth, +} + +struct Pending { + client_action_id: String, + hand_id: String, + turn_token: String, + action: OpAction, + state: PendState, + retried: bool, + seat: usize, +} + +struct HandCtx { + hand_id: String, + hand_no: u64, + hero_op: usize, + dealer: usize, + sb: i64, + bb: i64, + hole: Option<[Card; 2]>, + board: Vec, + events: Vec, + sim: Option, + start_stacks: BTreeMap, + names: BTreeMap, + decisions: u32, + fallbacks: u32, + issues: u32, + desync: bool, + policy: String, + hint_stacks: BTreeMap, + /// Seats that joined while this hand was running (not dealt in). + joined_mid: BTreeSet, + rebuilds: u32, +} + +pub struct Session { + pub cfg: SessionConfig, + spec: PolicySpec, + sink: Box, + pub counters: Counters, + hand: Option, + pending: Option, + table_id: Option, + roster: BTreeMap, Option)>, + last_table_seq: u64, + handled_tokens: HashSet, + hand_counter: u64, + action_counter: u64, + pub hero_name: Option, + pub agent_id: Option, + pub done: bool, + pub fatal: Option, + awaiting_rebuy: bool, + pub in_lobby_or_table: bool, + last_valid: Option, + reset: ResetState, + reset_cooldown_until: u64, + my_seat: Option, +} + +fn act_label(a: Action) -> String { + match a { + Action::Fold => "fold".into(), + Action::Check => "check".into(), + Action::Call => "call".into(), + Action::RaiseTo(t) => format!("raise:{t}"), + } +} + +impl Session { + pub fn new(cfg: SessionConfig, spec: PolicySpec, sink: Box) -> Session { + let mut s = Session { + cfg, + spec, + sink, + counters: Counters::default(), + hand: None, + pending: None, + table_id: None, + roster: BTreeMap::new(), + last_table_seq: 0, + handled_tokens: HashSet::new(), + hand_counter: 0, + action_counter: 0, + hero_name: None, + agent_id: None, + done: false, + fatal: None, + awaiting_rebuy: false, + in_lobby_or_table: false, + last_valid: None, + reset: ResetState::Idle, + reset_cooldown_until: 0, + my_seat: None, + }; + s.emit(json!({ + "kind": "session_start", + "policy": s.spec.label, + "embed6": s.spec.embed6, + "hu_mode": format!("{:?}", s.spec.hu), + "buy_in": s.cfg.buy_in, + "target_hands": s.cfg.target_hands, + "seed": s.cfg.seed, + "max_stack_bb": s.cfg.max_stack_bb, + "sizing": s.cfg.sizing, + "buckets": s.cfg.buckets, + "scale": crate::SCALE, + })); + s + } + + fn emit(&mut self, rec: Value) { + self.sink.emit(rec); + } + + /// Trace a record from outside (IO layer); counts as an anomaly if it is one. + pub fn note(&mut self, rec: Value) { + if rec.get("kind").and_then(Value::as_str) == Some("anomaly") { + self.counters.anomalies += 1; + } + self.emit(rec); + } + + fn anomaly(&mut self, what: &str, details: Value) { + self.counters.anomalies += 1; + self.emit(json!({"kind": "anomaly", "what": what, "details": details})); + } + + fn out(&mut self, v: Value) -> Value { + if self.cfg.raw { + self.emit(json!({"kind": "raw", "dir": "out", "msg": v})); + } + v + } + + /// Messages to send right after (re)connecting with no known table. + pub fn join_messages(&mut self) -> Vec { + self.in_lobby_or_table = true; + if matches!(self.reset, ResetState::Leaving { .. }) { + self.reset = ResetState::Idle; // a reconnect / table_closed overtook the reset + } + let mut v = vec![self.out(proto::join_lobby(self.cfg.buy_in))]; + if self.cfg.auto_rebuy { + v.push(self.out(proto::set_auto_rebuy(true))); + } + v + } + + /// After a reconnect when the server says we are still seated. + pub fn resync_message(&mut self, table_id: Option<&str>) -> Option { + let t = table_id.map(str::to_string).or_else(|| self.table_id.clone())?; + self.counters.resyncs += 1; + let m = proto::resync_request(&t, self.last_table_seq); + Some(self.out(m)) + } + + pub fn leave_messages(&mut self) -> Vec { + vec![self.out(proto::leave_table())] + } + + pub fn finish(&mut self, reason: &str) { + let c = serde_json::to_value(&self.counters).unwrap_or(Value::Null); + self.emit(json!({"kind": "session_end", "reason": reason, "counters": c})); + } + + // ------------------------------------------------------------------ dispatch + + pub fn on_message(&mut self, msg: &Value) -> Vec { + if self.cfg.raw { + self.emit(json!({"kind": "raw", "dir": "in", "msg": msg})); + } + // Envelope: ignore duplicates/regressions of table_seq for table-scoped messages. + if let Some(seq) = proto::get_u64(msg, "table_seq") { + if seq != 0 && seq <= self.last_table_seq && proto::msg_type(msg) != "resync_response" { + return Vec::new(); + } + if seq > self.last_table_seq { + self.last_table_seq = seq; + } + } + let mut out = Vec::new(); + match proto::msg_type(msg) { + "connected" => { + self.hero_name = proto::get_str(msg, "name").map(str::to_string); + self.agent_id = proto::get_str(msg, "agent_id").map(str::to_string); + } + "lobby_joined" | "auto_rebuy_set" | "auto_rebuy_scheduled" | "chips_skimmed" => {} + "table_joined" => self.on_table_joined(msg), + "player_joined" => { + if let Some(seat) = proto::get_i64(msg, "seat") { + let name = proto::get_str(msg, "name").map(str::to_string); + let stack = proto::get_i64(msg, "stack"); + self.roster.insert(seat as usize, (name, stack)); + if let Some(h) = self.hand.as_mut() { + h.joined_mid.insert(seat as usize); + } + } + } + "player_left" => out.extend(self.on_player_left(msg)), + "hand_start" => self.on_hand_start(msg), + "hole_cards" => { + if let Some(h) = self.hand.as_mut() { + let c = proto::parse_cards_value(msg.get("cards")); + if c.len() == 2 { + h.hole = Some([c[0], c[1]]); + } + } + } + "player_action" => self.on_player_action(msg), + "community_cards" => self.on_community(msg), + "your_turn" => out.extend(self.on_your_turn(msg)), + "action_ack" => self.on_ack(msg), + "hand_result" => self.on_hand_result(msg, &mut out), + "table_state" => out.extend(self.on_table_state(msg)), + "resync_response" => out.extend(self.on_resync(msg)), + "busted" => { + self.abandon_hand("busted"); + if !self.cfg.auto_rebuy && !self.done { + self.awaiting_rebuy = true; + self.counters.rebuys += 1; + let m = self.out(proto::rebuy()); + out.push(m); + } + } + "rebuy_confirmed" => { + if self.awaiting_rebuy && !self.done { + self.awaiting_rebuy = false; + let m = self.out(proto::join_lobby(self.cfg.buy_in)); + out.push(m); + } + } + "table_closed" | "season_ended" => { + self.abandon_hand(proto::msg_type(msg)); + if matches!(self.reset, ResetState::Leaving { .. }) { + self.reset = ResetState::Idle; + } + self.table_id = None; + self.roster.clear(); + self.last_table_seq = 0; + if !self.done { + out.extend(self.join_messages()); + } + } + "action_rejected" => out.extend(self.on_reject(msg)), + "error" => out.extend(self.on_error(msg)), + _ => {} + } + out + } + + fn on_table_joined(&mut self, msg: &Value) { + self.reset = ResetState::Idle; + self.my_seat = proto::get_i64(msg, "seat").map(|x| x as usize); + self.table_id = proto::get_str(msg, "table_id").map(str::to_string); + self.last_table_seq = 0; + self.roster.clear(); + for p in proto::parse_players(msg.get("players")) { + self.roster.insert(p.seat, (p.name, p.stack)); + } + } + + fn on_error(&mut self, msg: &Value) -> Vec { + let code = proto::get_str(msg, "code").unwrap_or(""); + if proto::is_rejection_code(code) { + return self.on_reject(msg); + } + match code { + "auth_failed" => { + self.fatal = Some("auth_failed: check the API key".into()); + self.done = true; + } + "insufficient_funds" => { + self.anomaly("insufficient_funds", msg.clone()); + if !self.done { + let m = self.out(proto::rebuy()); + self.awaiting_rebuy = true; + return vec![m]; + } + } + // After a bust the season balance may still hold chips: the server refuses the + // rebuy and expects us to simply rejoin a table (seen live; otherwise we idle forever). + "cannot_rebuy" => { + self.anomaly("cannot_rebuy", msg.clone()); + self.awaiting_rebuy = false; + if !self.done { + return self.join_messages(); + } + } + "not_at_table" | "no_hand_in_progress" => { + if matches!(self.reset, ResetState::Leaving { .. }) { + // Already off the table: carry on with the rejoin. + return self.finish_leave("not_at_table"); + } + } + "already_seated" if !matches!(self.reset, ResetState::Idle) => { + self.reset_failed(&format!("already_seated: {msg}")); + } + _ if matches!(self.reset, ResetState::Leaving { .. }) => { + self.anomaly("server_error", msg.clone()); + self.reset_failed(&format!("leave_table refused: {msg}")); + } + _ => self.anomaly("server_error", msg.clone()), + } + Vec::new() + } + + // ------------------------------------------------------------------ hand lifecycle + + fn on_hand_start(&mut self, msg: &Value) { + let hand_id = proto::get_str(msg, "hand_id").unwrap_or("").to_string(); + if self.hand.as_ref().is_some_and(|h| h.hand_id == hand_id) { + return; // replay of a known hand_start (resync) + } + self.abandon_hand("new hand_start"); + if let ResetState::Leaving { hands_seen } = self.reset { + if hands_seen >= 2 { + self.reset_failed("leave_table not honoured after 3 further hands"); + } else { + self.reset = ResetState::Leaving { hands_seen: hands_seen + 1 }; + } + } + let hero_op = proto::get_i64(msg, "seat").unwrap_or(0) as usize; + let dealer = proto::get_i64(msg, "dealer_seat").unwrap_or(0) as usize; + let (sb, bb) = msg + .get("blinds") + .map(|b| (proto::get_i64(b, "small_blind").unwrap_or(10), proto::get_i64(b, "big_blind").unwrap_or(20))) + .unwrap_or((10, 20)); + self.hand_counter += 1; + self.counters.hands_started += 1; + let hint_stacks: BTreeMap = self.roster.iter().filter_map(|(s, (_, st))| st.map(|x| (*s, x))).collect(); + let names: BTreeMap = self.roster.iter().filter_map(|(s, (n, _))| n.clone().map(|x| (*s, x))).collect(); + self.hand = Some(HandCtx { + hand_id, + hand_no: self.hand_counter, + hero_op, + dealer, + sb, + bb, + hole: None, + board: Vec::new(), + events: Vec::new(), + sim: None, + start_stacks: BTreeMap::new(), + names, + decisions: 0, + fallbacks: 0, + issues: 0, + desync: false, + policy: String::new(), + hint_stacks, + joined_mid: BTreeSet::new(), + rebuilds: 0, + }); + self.pending = None; + } + + fn abandon_hand(&mut self, why: &str) { + if let Some(h) = self.hand.take() { + self.anomaly("hand_abandoned", json!({"hand_id": h.hand_id, "why": why, "events": h.events.len()})); + } + self.pending = None; + } + + fn flush_hero_pending(&mut self) { + let Some(p) = self.pending.as_mut() else { return }; + if p.state != PendState::Sent { + return; + } + let Some(h) = self.hand.as_mut() else { return }; + if h.hand_id != p.hand_id { + return; + } + let (kind, amount) = match p.action.action.as_str() { + "fold" => (ObsKind::Fold, None), + "check" => (ObsKind::Check, None), + "call" => (ObsKind::Call, None), + "raise" => (ObsKind::Raise, p.action.amount), + _ => (ObsKind::AllIn, None), + }; + let o = ActionObs { + seat: p.seat, + name: self.hero_name.clone(), + kind, + raw_action: p.action.action.clone(), + amount, + street: None, + stack: None, + stack_before: None, + delta: None, + pot: None, + amount_mode: None, + }; + p.state = PendState::Synth; + self.record_obs(o, true); + } + + /// Append to the hand's event list and apply to the engine if it exists. + fn record_obs(&mut self, o: ActionObs, synthetic: bool) { + let Some(h) = self.hand.as_mut() else { return }; + let mut fail = None; + if let Some(sim) = h.sim.as_mut() { + if !h.desync { + if let Err(e) = sim.apply_obs(&o) { + fail = Some(e); + } + let iss = sim.take_issues(); + h.issues += iss.len() as u32; + if !iss.is_empty() { + let hid = h.hand_id.clone(); + self.counters.issues += iss.len() as u64; + self.sink.emit(json!({"kind": "anomaly", "what": "engine_server_mismatch", "details": {"hand_id": hid, "issues": iss, "synthetic": synthetic}})); + self.counters.anomalies += 1; + } + } + } + let Some(h) = self.hand.as_mut() else { return }; + if let Some(n) = &o.name { + h.names.insert(o.seat, n.clone()); + } + h.events.push(o); + if let Some(e) = fail { + // Drop the replay; the next decision rebuilds it from the full event list (this + // usually means the set of dealt-in players was guessed wrong at the first build). + h.sim = None; + h.rebuilds += 1; + let hid = h.hand_id.clone(); + self.counters.anomalies += 1; + self.sink.emit(json!({"kind": "anomaly", "what": "replay_failed_will_rebuild", "details": {"hand_id": hid, "error": e}})); + } + } + + fn on_player_action(&mut self, msg: &Value) { + let Some(o) = proto::parse_player_action(msg) else { + self.anomaly("unparsable_player_action", msg.clone()); + return; + }; + if self.hand.is_none() { + return; + } + // Echo of our own action? + let hero = self.hand.as_ref().map(|h| h.hero_op); + if Some(o.seat) == hero { + if let Some(p) = self.pending.as_mut() { + match p.state { + PendState::Synth => { + // Already applied synthetically; drop the late echo. + p.state = PendState::Echoed; + return; + } + PendState::Sent => p.state = PendState::Echoed, + PendState::Echoed => {} + } + } + } else { + self.flush_hero_pending(); + } + self.record_obs(o, false); + } + + fn on_community(&mut self, msg: &Value) { + self.flush_hero_pending(); + let cards = proto::parse_cards_value(msg.get("cards")); + let Some(h) = self.hand.as_mut() else { return }; + match cards.len() { + 0 => {} + 1 => h.board.push(cards[0]), + _ => h.board = cards, + } + let b = h.board.clone(); + if let Some(sim) = h.sim.as_mut() { + sim.set_board(&b); + } + } + + fn on_ack(&mut self, msg: &Value) { + self.counters.acks += 1; + let status = proto::get_str(msg, "status").unwrap_or(""); + let id = proto::get_str(msg, "client_action_id").unwrap_or("").to_string(); + self.emit(json!({"kind": "ack", "client_action_id": id, "status": status})); + } + + fn on_reject(&mut self, msg: &Value) -> Vec { + self.counters.rejects += 1; + self.emit(json!({"kind": "reject", "msg": msg})); + let code = proto::get_str(msg, "code").unwrap_or("").to_string(); + let Some(p) = self.pending.as_mut() else { return Vec::new() }; + if p.state == PendState::Sent && !p.retried && code == "invalid_action" { + // Retry once with the safest legal action on the same turn. + p.retried = true; + self.counters.retries += 1; + let v = self.last_valid.clone().unwrap_or_default(); + let a = passive(&v); + self.action_counter += 1; + let id = format!("plu-{}-r{}", self.hand_counter, self.action_counter); + let Some(p) = self.pending.as_mut() else { return Vec::new() }; + p.client_action_id = id.clone(); + p.action = a.clone(); + let m = proto::action_msg(&p.hand_id, &a.action, a.amount, &id, &p.turn_token); + return vec![self.out(m)]; + } + // Not retryable (stale token / not our turn / already retried): the server will + // auto-act at the deadline; do not apply anything locally. + if matches!(p.state, PendState::Sent) { + self.pending = None; + } + Vec::new() + } +} + +// ---------------------------------------------------------------------- decisions + +/// Fallback reason strings end up in the trace. +struct Chosen { + op: OpAction, + fidelity: Option, + nl_action: Option, + dist: Vec<(Action, f64)>, + u: f64, + fallback: Option, + /// Policy-reported fallback (search timeout/panic -> blueprint action); not a session fallback. + policy_note: Option, + issues: Vec, +} + +impl Session { + fn on_your_turn(&mut self, msg: &Value) -> Vec { + self.flush_hero_pending(); + let hand_id = proto::get_str(msg, "hand_id").unwrap_or("").to_string(); + let token = proto::get_str(msg, "turn_token").unwrap_or("").to_string(); + if !token.is_empty() && !self.handled_tokens.insert(token.clone()) { + return Vec::new(); // duplicate delivery (e.g. via resync snapshot) + } + if self.handled_tokens.len() > 512 { + self.handled_tokens.clear(); + } + let va = proto::parse_valid_actions(msg.get("valid_actions")); + let valid = ValidSet::from_actions(&va, proto::get_i64(msg, "min_raise"), proto::get_i64(msg, "max_raise")); + self.last_valid = Some(valid.clone()); + let server_pot = proto::get_i64(msg, "pot"); + let board_msg = proto::parse_cards_value(msg.get("community_cards")); + let players = proto::parse_players(msg.get("players")); + let t0 = Instant::now(); + + let mut ctx = match self.hand.take() { + Some(h) if h.hand_id == hand_id || hand_id.is_empty() => Some(h), + other => { + self.hand = other; + None + } + }; + let seed = self.cfg.seed; + let mut chosen = Chosen { + op: passive(&valid), + fidelity: None, + nl_action: None, + dist: Vec::new(), + u: 0.0, + fallback: None, + policy_note: None, + issues: Vec::new(), + }; + let mut meta = json!({}); + if let Some(h) = ctx.as_mut() { + if board_msg.len() > h.board.len() { + h.board = board_msg.clone(); + } + if h.sim.is_none() && !h.desync { + match Self::build_sim(h, &self.spec, &players, server_pot, mix(seed, h.hand_no)) { + Ok(notes) => { + if !notes.is_empty() { + self.sink.emit(json!({"kind":"note","what":"stack_derivation","details":{"hand_id":h.hand_id,"notes":notes}})); + } + } + Err(e) => { + h.desync = true; + self.counters.anomalies += 1; + self.sink.emit(json!({"kind":"anomaly","what":"desync","details":{"hand_id":h.hand_id,"error":e,"stage":"build_sim"}})); + } + } + } + let board_now = h.board.clone(); + if let Some(sim) = h.sim.as_mut() { + sim.set_board(&board_now); + } + if h.desync || h.sim.is_none() { + chosen.fallback = Some("desync".into()); + } else { + let sim = h.sim.as_mut().unwrap(); + let mut issues = sim.compare_legal(&valid, server_pot); + for p in &players { + if let (Some(st), Some(mine)) = (p.stack, sim.stack_op(p.seat)) { + if st != mine { + issues.push(format!("stack seat {}: server {st} vs engine {mine}", p.seat)); + } + } + } + issues.extend(sim.take_issues()); + chosen.issues = issues; + let mut rng = Rng::new(mix(mix(seed, h.hand_no), h.decisions as u64 + 1)); + chosen.u = rng.f64(); + match sim.decide(chosen.u) { + Ok(d) => { + let (op, fid) = map_action(d.chosen, &valid); + chosen.dist = d.dist; + chosen.policy_note = d.note; + chosen.nl_action = Some(d.chosen); + chosen.op = op; + chosen.fidelity = Some(fid); + } + Err(e) => { + h.desync = true; + chosen.fallback = Some(format!("decide: {e}")); + } + } + } + meta = json!({ + "hand_no": h.hand_no, "hero_seat": h.hero_op, "policy": h.policy, + "position": h.sim.as_ref().map(|s| s.layout.position_name(h.hero_op)).unwrap_or("?"), + "n_players": h.sim.as_ref().map(|s| s.layout.n_real), + "hole": h.hole.map(|x| cards_to_strs(&x)), "board": cards_to_strs(&h.board), + "street": h.sim.as_ref().map(|s| format!("{:?}", s.street())), + }); + h.decisions += 1; + h.issues += chosen.issues.len() as u32; + if chosen.fallback.is_some() { + h.fallbacks += 1; + } + } else { + chosen.fallback = Some("no hand context".into()); + self.counters.anomalies += 1; + self.sink.emit(json!({"kind":"anomaly","what":"your_turn_without_hand","details":{"hand_id":hand_id}})); + } + self.hand = ctx.or(self.hand.take()); + // Last line of defence: never send something the server did not offer. + let mut stack_guard: Option = None; + if let (Some(h), true) = (self.hand.as_ref(), chosen.fallback.is_none()) { + if let (Some(cap), Some(sim)) = (self.cap_chips(h.bb), h.sim.as_ref()) { + let me = h.hero_op; + if let (Some(total), Some(bet), Some(stack)) = (sim.contributed_op(me), sim.street_bet_op(me), sim.stack_op(me)) { + if let Some((op, note)) = cap_action(&chosen.op, &valid, cap, total - bet, total + stack) { + stack_guard = Some(note); + chosen.op = op; + self.counters.stack_guards += 1; + } + } + } + } + if !is_legal(&chosen.op, &valid) { + self.counters.anomalies += 1; + self.sink.emit(json!({"kind":"anomaly","what":"illegal_choice_replaced","details":{"chosen":chosen.op.label(),"valid":valid.describe()}})); + chosen.op = passive(&valid); + chosen.fallback.get_or_insert_with(|| "illegal mapped action".into()); + } + if chosen.fallback.is_some() { + self.counters.fallbacks += 1; + } + if chosen.policy_note.is_some() { + self.counters.policy_fallbacks += 1; + } + self.counters.decisions += 1; + self.counters.issues += chosen.issues.len() as u64; + self.action_counter += 1; + let cid = format!("plu-{}-{}", self.hand_counter, self.action_counter); + let latency_us = t0.elapsed().as_micros() as u64; + self.emit(json!({ + "kind": "decision", "hand_id": hand_id, "client_action_id": cid, "meta": meta, + "pot": server_pot, "valid": valid.describe(), + "players": players.iter().map(|p| json!({"seat": p.seat, "stack": p.stack, "in_hand": p.in_hand, "status": p.status})).collect::>(), + "issues": chosen.issues, "fallback": chosen.fallback, "fallback_reason": chosen.policy_note, + "dist": chosen.dist.iter().map(|(a, p)| json!([act_label(*a), (p * 1e6).round() / 1e6])).collect::>(), + "u": chosen.u, "chosen": chosen.nl_action.map(act_label), + "sent": chosen.op.label(), "stack_guard": stack_guard, "fidelity": chosen.fidelity.as_ref().map(|f| format!("{f:?}")), + "latency_us": latency_us, + })); + let seat = self.hand.as_ref().map(|h| h.hero_op).unwrap_or(0); + self.pending = Some(Pending { + client_action_id: cid.clone(), + hand_id: hand_id.clone(), + turn_token: token.clone(), + action: chosen.op.clone(), + state: PendState::Sent, + retried: false, + seat, + }); + let m = proto::action_msg(&hand_id, &chosen.op.action, chosen.op.amount, &cid, &token); + vec![self.out(m)] + } + + /// Build the engine replay at the hero's first decision. Tries the plausible sets of + /// dealt-in players and keeps the first whose replay is consistent with the server's pot. + /// Returns informational notes. + fn build_sim( + h: &mut HandCtx, + spec: &PolicySpec, + players: &[PlayerInfo], + server_pot: Option, + seed: u64, + ) -> Result, String> { + let hole = h.hole.ok_or("your_turn before hole_cards")?; + let evidence: BTreeSet = h + .events + .iter() + .filter(|e| e.kind != ObsKind::Ignored) + .map(|e| e.seat) + .chain(std::iter::once(h.hero_op)) + .collect(); + for p in players { + if let Some(n) = &p.name { + h.names.insert(p.seat, n.clone()); + } + } + // Dealt-in set: evidence (seats that acted, hero) plus any subset of the other seated + // players (your_turn.players carries no status and seats can join mid-hand). Try the + // largest subsets first; a candidate is valid when every event replays, the hero is to + // act and the pot matches the server's. + let optional: Vec = players + .iter() + .filter(|p| p.dealt_in() != Some(false) && !h.joined_mid.contains(&p.seat) && !evidence.contains(&p.seat)) + .map(|p| p.seat) + .collect(); + let mut masks: Vec = if optional.len() <= 5 { (0..(1u32 << optional.len())).collect() } else { vec![(1u32 << optional.len()) - 1, 0] }; + masks.sort_by_key(|m| std::cmp::Reverse(m.count_ones())); + let mut best: Option<(Sim, BTreeMap, String, Vec)> = None; + let mut first_err = None; + for mask in masks { + let mut parts = evidence.clone(); + for (i, s) in optional.iter().enumerate() { + if mask >> i & 1 == 1 { + parts.insert(*s); + } + } + if parts.len() < 2 { + continue; + } + match Self::try_build(h, spec, &parts, players, hole, seed) { + Ok((sim, stacks, label, notes)) => { + let valid = sim.hero_to_act() && server_pot.map_or(true, |p| p == sim.pot_op()); + if best.is_none() || valid { + best = Some((sim, stacks, label, notes)); + } + if valid { + break; + } + } + Err(e) => { + first_err.get_or_insert(e); + } + } + } + let (mut sim, stacks, label, mut notes) = best.ok_or_else(|| first_err.unwrap_or_else(|| "no layout".into()))?; + notes.extend(sim.take_issues()); + sim.set_board(&h.board); + h.start_stacks = stacks; + h.policy = label; + h.sim = Some(sim); + Ok(notes) + } + + fn try_build( + h: &HandCtx, + spec: &PolicySpec, + parts: &BTreeSet, + players: &[PlayerInfo], + hole: [Card; 2], + seed: u64, + ) -> Result<(Sim, BTreeMap, String, Vec), String> { + let n = parts.len(); + let fallback = n == 2 && spec.hu == HuMode::Fallback; + let (factory, embed6, label): (Arc, bool, String) = if fallback { + (spec.fallback.clone(), false, format!("fallback:{}", spec.fallback.name())) + } else { + (spec.main.clone(), spec.embed6, spec.label.clone()) + }; + const BIG: i64 = 200_000; + let mut notes = Vec::new(); + let reported: BTreeMap = players.iter().filter_map(|p| p.stack.map(|s| (p.seat, s))).collect(); + let order = engine_order(parts, h.dealer); + let blind_of = |s: usize| -> i64 { + if order.first() == Some(&s) { + h.sb + } else if order.get(1) == Some(&s) { + h.bb + } else { + 0 + } + }; + // First recorded action of each seat: its stack_before (or stack_after + delta). + let mut first: BTreeMap> = BTreeMap::new(); + for e in h.events.iter().filter(|e| e.kind != ObsKind::Ignored) { + first + .entry(e.seat) + .or_insert_with(|| e.stack_before.or_else(|| e.stack.zip(e.delta).map(|(s, d)| s + d))); + } + let mut stacks: BTreeMap = BTreeMap::new(); + let direct = parts.iter().all(|s| match first.get(s) { + Some(Some(_)) => true, + Some(None) => false, + None => reported.contains_key(s) || h.hint_stacks.contains_key(s), + }); + if direct { + // Exact: stack before the first action (or the current stack of a seat that has + // not acted yet) plus the blind that seat posted. + for &s in parts { + let base = match first.get(&s) { + Some(Some(b)) => *b, + _ => reported.get(&s).or_else(|| h.hint_stacks.get(&s)).copied().unwrap_or(BIG), + }; + stacks.insert(s, base + blind_of(s)); + } + } else { + // Fallback (messages without stack_before): start = current stack + chips committed, + // iterated because all-in caps depend on the stacks themselves. + notes.push("start stacks derived from current stacks + replayed contributions".into()); + let contrib = |st: &BTreeMap| -> Result, String> { + let layout = Layout::build(parts, h.dealer, st, h.sb, h.bb, embed6)?; + let mut sim = Sim::new(layout, h.hero_op, hole, None, 0)?; + for e in &h.events { + sim.apply_obs(e)?; + } + Ok(parts.iter().map(|&s| (s, sim.contributed_op(s).unwrap_or(0))).collect()) + }; + stacks = parts.iter().map(|&s| (s, h.hint_stacks.get(&s).copied().unwrap_or(BIG))).collect(); + let mut c = contrib(&stacks)?; + for _ in 0..4 { + let next: BTreeMap = parts + .iter() + .map(|&s| (s, reported.get(&s).map_or_else(|| h.hint_stacks.get(&s).copied().unwrap_or(BIG), |r| r + c[&s]))) + .collect(); + if next == stacks { + break; + } + stacks = next; + c = contrib(&stacks)?; + } + } + for (s, st) in &stacks { + if let Some(hint) = h.hint_stacks.get(s) { + if hint != st { + notes.push(format!("start stack seat {s}: hint {hint} vs derived {st}")); + } + } + } + let layout = Layout::build(parts, h.dealer, &stacks, h.sb, h.bb, embed6)?; + let mut sim = Sim::new(layout, h.hero_op, hole, Some(&*factory), seed)?; + for e in &h.events { + sim.apply_obs(e)?; + } + Ok((sim, stacks, label, notes)) + } + + // ------------------------------------------------------------------ results + + fn on_hand_result(&mut self, msg: &Value, out: &mut Vec) { + self.flush_hero_pending(); + let Some(mut h) = self.hand.take() else { + // A hand we never saw start (e.g. joined mid-hand). Still keep the roster fresh. + for (seat, st) in proto::parse_seat_numbers(msg.get("final_stacks"), &["stack", "final_stack"]) { + self.roster.entry(seat).or_insert((None, None)).1 = Some(st); + } + return; + }; + self.pending = None; + let final_stacks = proto::parse_seat_numbers(msg.get("final_stacks"), &["stack", "final_stack", "final"]); + let winners = msg.get("winners").and_then(Value::as_array).cloned().unwrap_or_default(); + let shown = shown_from_value(msg.get("shown_cards")); + let board_msg = proto::parse_cards_value(msg.get("community_cards").or_else(|| msg.get("board"))); + if board_msg.len() > h.board.len() { + h.board = board_msg; + } + let hero = h.hero_op; + let start_hero = h.start_stacks.get(&hero).or_else(|| h.hint_stacks.get(&hero)).copied(); + let end_hero = final_stacks.iter().find(|x| x.0 == hero).map(|x| x.1); + let by_stacks = match (start_hero, end_hero) { + (Some(s), Some(e)) => Some(e - s), + _ => None, + }; + let contrib_hero = h.sim.as_ref().and_then(|s| s.contributed_op(hero)); + // `payouts[].amount` is the gross amount paid to a seat (`winners[].amount` is net). + let payouts = proto::parse_seat_numbers(msg.get("payouts"), &["amount"]); + let won_gross: i64 = payouts.iter().filter(|x| x.0 == hero).map(|x| x.1).sum(); + let by_winners = if payouts.is_empty() { None } else { contrib_hero.map(|c| won_gross - c) }; + let (profit, src) = match (by_stacks, by_winners) { + (Some(a), Some(b)) => { + // They legitimately differ when an uncalled bet is refunded (the refund is not a + // payout); `final_stacks` is authoritative. Keep the difference for debugging. + if a != b { + self.sink.emit(json!({"kind":"note","what":"profit_sources_differ","details":{"hand_id":h.hand_id,"final_stacks":a,"payouts_minus_contrib":b}})); + } + (Some(a), "final_stacks") + } + (Some(a), None) => (Some(a), "final_stacks"), + (None, Some(b)) => (Some(b), "winners-contrib"), + (None, None) => (None, "unknown"), + }; + for (seat, st) in &final_stacks { + let e = self.roster.entry(*seat).or_insert((None, None)); + e.1 = Some(*st); + } + // Players table. + let mut players = Vec::new(); + if let Some(sim) = &h.sim { + for (&op, &nl) in &sim.layout.nl_of_op { + players.push(HandPlayer { + seat: op, + name: h.names.get(&op).cloned(), + start_stack: h.start_stacks.get(&op).copied(), + contrib: sim.contributed_op(op), + folded: Some(sim.state.is_folded(nl)), + shown: shown.get(&op).cloned(), + }); + } + } else { + let seats: BTreeSet = h.events.iter().map(|e| e.seat).chain(std::iter::once(hero)).collect(); + for op in seats { + players.push(HandPlayer { + seat: op, + name: h.names.get(&op).cloned(), + start_stack: h.hint_stacks.get(&op).copied(), + contrib: None, + folded: None, + shown: shown.get(&op).cloned(), + }); + } + } + let rec = HandRecord { + hand_id: h.hand_id.clone(), + table_id: self.table_id.clone(), + hand_no: h.hand_no, + hero_seat: hero, + dealer_seat: h.dealer, + sb: h.sb, + bb: h.bb, + n_players: h.sim.as_ref().map(|s| s.layout.n_real).unwrap_or(players.len()), + position: h.sim.as_ref().map(|s| s.layout.position_name(hero).to_string()).unwrap_or_default(), + hero_hole: h.hole.map(|x| cards_to_strs(&x)).unwrap_or_default(), + board: cards_to_strs(&h.board), + players, + actions: h + .events + .iter() + .filter(|e| e.kind != ObsKind::Ignored) + .map(|e| HandAct { seat: e.seat, street: e.street.clone(), action: e.raw_action.clone(), amount: e.amount }) + .collect(), + profit, + profit_src: src.into(), + lock_len: h.sim.as_ref().and_then(|s| s.lock_len), + showdown: !shown.is_empty() || h.sim.as_ref().is_some_and(|s| s.state.showdown()), + policy: h.policy.clone(), + decisions: h.decisions, + fallbacks: h.fallbacks, + issues: h.issues, + desync: h.desync, + }; + self.counters.hands_done += 1; + self.counters.desync_hands += h.desync as u64; + let ts = now_ms(); + self.emit(json!({"kind": "hand", "t": ts, "hand": rec, "hero_end_stack": end_hero, "winners": winners})); + if self.counters.hands_done as usize >= self.cfg.target_hands && !self.done { + self.done = true; + out.extend(self.leave_messages()); + } else if !self.done { + let end = end_hero.or_else(|| self.roster.get(&hero).and_then(|r| r.1)); + if let Some(m) = self.maybe_reset(end, h.bb) { + out.push(m); + } + } + } + + // ------------------------------------------------------------------ stack reset (layer 1) + + fn cap_chips(&self, bb: i64) -> Option { + (self.cfg.max_stack_bb > 0.0).then(|| (self.cfg.max_stack_bb * bb as f64).round() as i64) + } + + /// Called right after a hand is closed (never mid-hand): leave if our stack is too deep. + fn maybe_reset(&mut self, end_stack: Option, bb: i64) -> Option { + let cap = self.cap_chips(bb)?; + let st = end_stack?; + if st <= cap || self.reset != ResetState::Idle || self.counters.hands_done < self.reset_cooldown_until { + return None; + } + self.reset = ResetState::Leaving { hands_seen: 0 }; + self.emit(json!({"kind":"note","what":"stack_reset_leave","details":{"stack":st,"bb":bb,"cap":cap,"stack_bb":st as f64 / bb.max(1) as f64,"buy_in":self.cfg.buy_in}})); + Some(self.out(proto::leave_table())) + } + + fn reset_failed(&mut self, why: &str) { + self.reset = ResetState::Idle; + self.reset_cooldown_until = self.counters.hands_done + RESET_COOLDOWN_HANDS; + self.counters.reset_aborts += 1; + self.emit(json!({"kind":"note","what":"stack_reset_aborted","details":{"why":why,"cooldown_hands":RESET_COOLDOWN_HANDS,"fallback":"stack_guard"}})); + } + + /// We are off the table: forget it and queue for a new one with the normal buy-in. + fn finish_leave(&mut self, how: &str) -> Vec { + self.counters.stack_resets += 1; + self.table_id = None; + self.roster.clear(); + self.last_table_seq = 0; + self.in_lobby_or_table = true; + self.reset = ResetState::Rejoining { since: Instant::now(), tries: 1 }; + self.emit(json!({"kind":"note","what":"stack_reset_rejoin","details":{"how":how,"buy_in":self.cfg.buy_in}})); + vec![self.out(proto::join_lobby(self.cfg.buy_in))] + } + + fn on_player_left(&mut self, msg: &Value) -> Vec { + let Some(seat) = proto::get_i64(msg, "seat").map(|x| x as usize) else { return Vec::new() }; + let name = proto::get_str(msg, "name"); + let mine = match (name, self.hero_name.as_deref()) { + (Some(n), Some(h)) => n == h, + _ => self.my_seat == Some(seat), + }; + self.roster.remove(&seat); + if !mine || self.done { + return Vec::new(); + } + let reason = proto::get_str(msg, "reason").unwrap_or(""); + match self.reset { + ResetState::Leaving { .. } if reason != "busted" => self.finish_leave("player_left"), + ResetState::Idle if reason == "left" => { + // We left (e.g. a leave that was queued after we gave up waiting): do not idle. + self.anomaly("unexpected_self_left", msg.clone()); + self.finish_leave("late_player_left") + } + _ => Vec::new(), + } + } + + /// Periodic tick from the IO layer (read timeouts): retry a stalled rejoin. + pub fn on_idle(&mut self) -> Vec { + self.on_idle_at(Instant::now()) + } + + pub fn on_idle_at(&mut self, now: Instant) -> Vec { + let ResetState::Rejoining { since, tries } = self.reset else { return Vec::new() }; + if self.done || now.saturating_duration_since(since) < REJOIN_RETRY { + return Vec::new(); + } + if tries >= REJOIN_MAX_TRIES { + self.reset = ResetState::Idle; + self.anomaly("rejoin_gave_up", json!({"tries": tries})); + return Vec::new(); + } + self.reset = ResetState::Rejoining { since: now, tries: tries + 1 }; + self.emit(json!({"kind":"note","what":"stack_reset_rejoin_retry","details":{"try":tries + 1}})); + vec![self.out(proto::join_lobby(self.cfg.buy_in))] + } + + fn on_table_state(&mut self, msg: &Value) -> Vec { + if let Some(t) = proto::get_str(msg, "table_id") { + self.table_id = Some(t.to_string()); + } + let seats = proto::parse_players(msg.get("seats")); + let fresh = self.hand.as_ref().map_or(true, |h| h.events.is_empty() && h.sim.is_none()); + if fresh { + for p in &seats { + if let Some(st) = p.stack { + let start = st + p.bet.unwrap_or(0); + let e = self.roster.entry(p.seat).or_insert((None, None)); + e.1 = Some(start); + if p.name.is_some() { + e.0 = p.name.clone(); + } + if let Some(h) = self.hand.as_mut() { + h.hint_stacks.insert(p.seat, start); + } + } + } + } + // Resync with a live turn for us: rebuild the private `your_turn`. + let hero = msg.get("hero"); + if let Some(hero) = hero { + if let Some(h) = self.hand.as_mut() { + let c = proto::parse_cards_value(hero.get("hole_cards")); + if c.len() == 2 && h.hole.is_none() { + h.hole = Some([c[0], c[1]]); + } + } + let token = proto::get_str(hero, "turn_token"); + let actor = proto::get_i64(msg, "actor_seat"); + let seat = proto::get_i64(hero, "seat"); + if let (Some(token), Some(actor), Some(seat)) = (token, actor, seat) { + if actor == seat && !self.handled_tokens.contains(token) { + let hand_id = proto::get_str(msg, "hand_id") + .map(str::to_string) + .or_else(|| self.hand.as_ref().map(|h| h.hand_id.clone())) + .unwrap_or_default(); + let synth = json!({ + "type": "your_turn", "hand_id": hand_id, "turn_token": token, + "valid_actions": hero.get("valid_actions").cloned().unwrap_or(json!([])), + "pot": msg.get("pot"), "community_cards": msg.get("board").cloned().unwrap_or(json!([])), + "players": msg.get("seats").cloned().unwrap_or(json!([])), + "min_raise": msg.get("min_raise_to"), "max_raise": msg.get("max_raise_to"), + }); + self.emit(json!({"kind": "anomaly", "what": "your_turn_from_snapshot", "details": {"hand_id": hand_id}})); + return self.on_your_turn(&synth); + } + } + } + Vec::new() + } + + fn on_resync(&mut self, msg: &Value) -> Vec { + let mut out = Vec::new(); + if let Some(events) = msg.get("replayed_events").and_then(Value::as_array) { + for ev in events.clone() { + // Events are server messages (possibly wrapped as {"event": {...}}). + let inner = ev.get("event").cloned().unwrap_or(ev); + out.extend(self.on_message(&inner)); + } + } + if let Some(to) = proto::get_u64(msg, "to_table_seq") { + self.last_table_seq = self.last_table_seq.max(to); + } + if let Some(snap) = msg.get("snapshot") { + out.extend(self.on_table_state(snap)); + } + out + } +} diff --git a/arena/openpoker/src/sim.rs b/arena/openpoker/src/sim.rs new file mode 100644 index 00000000..b8850da0 --- /dev/null +++ b/arena/openpoker/src/sim.rs @@ -0,0 +1,349 @@ +//! Replay of the table's actions onto an `nlhe::State`, plus the hero's bench `Player`. +//! +//! The simulation is *observational*: it never decides what the table does, it only applies +//! what the server reports (`player_action`) and cross-checks the engine against the +//! server's own numbers (pot, stacks, legal actions). Disagreements are collected as +//! `issues` (strings) and end up in the trace; the session treats a failed `apply_obs` as a +//! desync and falls back to a passive legal action. + +use crate::layout::{scale, unscale, Layout}; +use crate::proto::{ActionObs, ObsKind, ValidSet}; +use bench::policy::{Dist, Event, Player, PolicyFactory, View}; +use cards::Card; +use nlhe::{Action, State, Step, Street}; + +pub struct Sim { + pub layout: Layout, + pub state: State, + pub hero_op: usize, + pub hero_nl: usize, + pub hole: [Card; 2], + pub board: Vec, + pub history: Vec, + player: Option>, + /// Non-fatal disagreements between engine and server since the last `take_issues`. + issues: Vec, + /// Applied actions as (open poker seat, nlhe action in our chips), in order. + pub applied: Vec<(usize, Action)>, + /// Board cards visible when the last betting round closed with a showdown ahead + /// (`Some(5)` = ordinary river showdown, `Some(<5)` = all-in run-out). + pub lock_len: Option, +} + +/// What `decide` produced. +#[derive(Clone, Debug)] +pub struct Decision { + /// Full distribution over concrete nlhe actions (empty for non-exposing players). + pub dist: Vec<(Action, f64)>, + pub chosen: Action, + /// Policy diagnostic for this decision (e.g. a search fallback reason). + pub note: Option, +} + +impl Sim { + /// `factory = None` builds a bare replay (contribution bookkeeping only). + pub fn new( + layout: Layout, + hero_op: usize, + hole: [Card; 2], + factory: Option<&dyn PolicyFactory>, + seed: u64, + ) -> Result { + let hero_nl = layout + .nl(hero_op) + .ok_or_else(|| format!("hero seat {hero_op} not dealt in"))?; + let state = State::new(&layout.cfg); + let player = factory.map(|f| f.new_player(hero_nl, &layout.cfg, seed)); + let mut sim = Sim { + layout, + state, + hero_op, + hero_nl, + hole, + board: Vec::new(), + history: Vec::new(), + player, + issues: Vec::new(), + applied: Vec::new(), + lock_len: None, + }; + // Phantom seats (embedded short-handed game) fold first. + for k in 0..sim.layout.prefold { + let nl = 2 + k; + if sim.state.to_act() != Some(nl) { + return Err(format!("phantom fold: engine expects seat {:?}, not {nl}", sim.state.to_act())); + } + sim.push(nl, Action::Fold); + } + Ok(sim) + } + + fn push(&mut self, nl: usize, a: Action) -> Step { + let pre = self.state; + let street = pre.street(); + let step = self.state.apply(a); + if self.state.showdown() && self.lock_len.is_none() { + self.lock_len = Some(street.board_len()); + } + self.history.push(Event { seat: nl as u8, street, action: a }); + if let Some(p) = self.player.as_mut() { + p.observe(&pre, nl, a); + } + step + } + + pub fn take_issues(&mut self) -> Vec { + std::mem::take(&mut self.issues) + } + + /// Apply a reported action. `Err` = the action cannot be placed (desync); the state is + /// unchanged in that case. + pub fn apply_obs(&mut self, o: &ActionObs) -> Result<(), String> { + if o.kind == ObsKind::Ignored { + return Ok(()); + } + let nl = self + .layout + .nl(o.seat) + .ok_or_else(|| format!("action from seat {} which is not dealt in", o.seat))?; + if self.state.is_terminal() { + return Err(format!("action from seat {} after the hand ended", o.seat)); + } + if self.state.to_act() != Some(nl) { + return Err(format!( + "out of turn: engine expects nlhe seat {:?}, got seat {} (nlhe {nl})", + self.state.to_act(), + o.seat + )); + } + let l = self.state.legal(); + let note = |s: String, issues: &mut Vec| issues.push(format!("seat {}: {s}", o.seat)); + let mut issues = Vec::new(); + let act = match o.kind { + ObsKind::Fold => { + if l.can_fold { + Action::Fold + } else { + note("fold while check is free; treated as check".into(), &mut issues); + Action::Check + } + } + ObsKind::Check => { + if l.can_check { + Action::Check + } else { + note("check while facing a bet; treated as call".into(), &mut issues); + Action::Call + } + } + ObsKind::Call => { + if l.can_check { + Action::Check + } else { + Action::Call + } + } + ObsKind::Raise => { + let Some(x) = o.amount else { + return Err(format!("raise from seat {} without amount", o.seat)); + }; + // `amount_mode: "to_total"` (the only mode seen for raises) is raise-to on the + // street; if a server ever says "incremental", add it to what the actor has in. + let t = if o.amount_mode.as_deref() == Some("incremental") { + self.state.street_bet(nl) + scale(x) + } else { + scale(x) + }; + if !l.can_raise { + note(format!("raise to {x} but engine cannot raise; treated as call"), &mut issues); + if l.can_check { Action::Check } else { Action::Call } + } else if t < l.min_raise_to || t > l.max_raise_to { + let c = t.clamp(l.min_raise_to, l.max_raise_to); + note( + format!("raise to {x} outside engine range {}..{} (op chips); clamped", unscale(l.min_raise_to), unscale(l.max_raise_to)), + &mut issues, + ); + Action::RaiseTo(c) + } else { + Action::RaiseTo(t) + } + } + ObsKind::AllIn => { + if l.can_raise { + if let Some(x) = o.amount { + let t = scale(x); + // `amount` may be the raise-to total or the chips added; both must + // end at the stack, so the engine's all-in is authoritative. + if t != l.max_raise_to && t != 0 { + note(format!("all_in amount {x} != engine all-in {}", unscale(l.max_raise_to)), &mut issues); + } + } + Action::RaiseTo(l.max_raise_to) + } else if l.can_check { + Action::Check + } else { + Action::Call + } + } + ObsKind::Ignored => unreachable!(), + }; + self.push(nl, act); + self.applied.push((o.seat, act)); + // Cross-checks against the server's own numbers. Not for `all_in`: the live server's + // broadcast for that action carries the *pre-action* stack/pot (contribution_delta 0), + // while the next event's `pot_before` already includes the chips. + if o.kind == ObsKind::AllIn { + self.issues.extend(issues); + return Ok(()); + } + if let Some(s) = o.stack { + let mine = unscale(self.state.stack(nl)); + if mine != s { + issues.push(format!("seat {}: stack after action server {s} vs engine {mine}", o.seat)); + } + } + if let Some(p) = o.pot { + let mine = unscale(self.state.pot()); + if mine != p { + issues.push(format!("pot after seat {}'s action server {p} vs engine {mine}", o.seat)); + } + } + self.issues.extend(issues); + Ok(()) + } + + /// Reveal board cards (full board so far). Calls `observe_board` for each new street. + pub fn set_board(&mut self, board: &[Card]) { + if board.len() <= self.board.len() { + return; + } + let mut lens: Vec = Vec::new(); + for to in [3usize, 4, 5] { + if to > self.board.len() && to <= board.len() { + lens.push(to); + } + } + for to in lens { + if let Some(p) = self.player.as_mut() { + p.observe_board(&board[..to]); + } + } + self.board = board.to_vec(); + } + + pub fn hero_to_act(&self) -> bool { + !self.state.is_terminal() && self.state.to_act() == Some(self.hero_nl) + } + + pub fn street(&self) -> Street { + self.state.street() + } + + pub fn pot_op(&self) -> i64 { + unscale(self.state.pot()) + } + + pub fn contributed_op(&self, op_seat: usize) -> Option { + self.layout.nl(op_seat).map(|nl| unscale(self.state.contributed(nl))) + } + + pub fn street_bet_op(&self, op_seat: usize) -> Option { + self.layout.nl(op_seat).map(|nl| unscale(self.state.street_bet(nl))) + } + + pub fn stack_op(&self, op_seat: usize) -> Option { + self.layout.nl(op_seat).map(|nl| unscale(self.state.stack(nl))) + } + + /// Compare the engine's legal actions for the hero with the server's. Returns issues. + pub fn compare_legal(&self, v: &ValidSet, server_pot: Option) -> Vec { + let mut out = Vec::new(); + if !self.hero_to_act() { + out.push(format!( + "engine says nlhe seat {:?} to act, hero is {}", + self.state.to_act(), + self.hero_nl + )); + return out; + } + let l = self.state.legal(); + if let Some(p) = server_pot { + if p != self.pot_op() { + out.push(format!("pot server {p} vs engine {}", self.pot_op())); + } + } + if l.can_check != v.check { + out.push(format!("check offered: server {} engine {}", v.check, l.can_check)); + } + // The server also lists fold when checking is free; only a missing fold is a problem. + if l.can_fold && !v.fold { + out.push("engine expects fold to be offered, server does not".into()); + } + if let Some(c) = v.call { + let e = unscale(l.call_amount); + // Servers may report the call as the total to match instead of the increment. + if c != e { + out.push(format!("call amount server {c} vs engine {e}")); + } + } else if !l.can_check { + out.push("engine expects a call, server offers none".into()); + } + match (v.raise, l.can_raise) { + (Some((lo, hi)), true) => { + if unscale(l.min_raise_to) != lo { + out.push(format!("min raise-to server {lo} vs engine {}", unscale(l.min_raise_to))); + } + if unscale(l.max_raise_to) != hi { + out.push(format!("max raise-to server {hi} vs engine {}", unscale(l.max_raise_to))); + } + } + (Some(_), false) => out.push("server offers raise, engine cannot raise".into()), + (None, true) => { + if v.all_in.is_none() { + out.push("engine can raise, server offers neither raise nor all_in".into()); + } + } + (None, false) => {} + } + out + } + + /// Ask the hero's policy. `u` in [0,1) is the sampling draw. + pub fn decide(&mut self, u: f64) -> Result { + if !self.hero_to_act() { + return Err("hero is not to act".into()); + } + let need = self.state.street().board_len(); + if self.board.len() < need { + return Err(format!("board has {} cards, street needs {need}", self.board.len())); + } + let hole = self.hole; + let seat = self.hero_nl; + let player = self.player.as_mut().ok_or("simulation has no policy")?; + let view = View { + cfg: &self.layout.cfg, + state: &self.state, + board: &self.board, + history: &self.history, + seat, + }; + if player.exposes_probs() { + let d: Dist = player.dist(&view, hole); + if d.is_empty() { + return Err("policy returned an empty distribution".into()); + } + let i = d.sample(u); + let dist = (0..d.len()).map(|k| (d.action(k), d.prob(k))).collect(); + let note = player.take_note(); + Ok(Decision { dist, chosen: d.action(i), note }) + } else { + let a = player.act(&view, hole, u); + let note = player.take_note(); + Ok(Decision { dist: Vec::new(), chosen: a, note }) + } + } + + pub fn is_terminal(&self) -> bool { + self.state.is_terminal() + } +} diff --git a/arena/openpoker/src/trace.rs b/arena/openpoker/src/trace.rs new file mode 100644 index 00000000..a2a001bd --- /dev/null +++ b/arena/openpoker/src/trace.rs @@ -0,0 +1,83 @@ +//! Strict JSONL trace. One JSON object per line, `kind` discriminates: +//! +//! | kind | content | +//! |---|---| +//! | `session_start` | policy, sizing, buckets, buy-in, seed, crate config | +//! | `raw` | every websocket message in (`dir:"in"`) and out (`dir:"out"`) | +//! | `decision` | state summary, server legal set, engine/server consistency issues, our full distribution, sampled `u`, chosen nlhe action, mapped Open Poker action + fidelity, latency | +//! | `ack` / `reject` | server's verdict on an action | +//! | `anomaly` | desync, unparsable message, reconnect, rebuy, anything surprising | +//! | `hand` | per-hand result (see [`crate::analyze::HandRecord`]), the analyzer's input | +//! | `session_end` | counters | +//! +//! Every line carries `t` (unix ms). Lines are flushed immediately so a crash loses nothing. + +use serde_json::Value; +use std::fs::{File, OpenOptions}; +use std::io::{BufWriter, Write}; +use std::path::Path; +use std::sync::{Arc, Mutex}; + +pub trait TraceSink: Send { + fn emit(&mut self, rec: Value); +} + +pub fn now_ms() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0) +} + +pub struct FileSink { + w: BufWriter, +} + +impl FileSink { + pub fn create(path: &Path) -> std::io::Result { + if let Some(dir) = path.parent() { + if !dir.as_os_str().is_empty() { + std::fs::create_dir_all(dir)?; + } + } + let f = OpenOptions::new().create(true).append(true).open(path)?; + Ok(FileSink { w: BufWriter::new(f) }) + } +} + +impl TraceSink for FileSink { + fn emit(&mut self, mut rec: Value) { + if let Value::Object(m) = &mut rec { + m.entry("t").or_insert(Value::from(now_ms())); + } + let _ = writeln!(self.w, "{rec}"); + let _ = self.w.flush(); + } +} + +/// In-memory sink for tests (clone the handle to read it back). +#[derive(Clone, Default)] +pub struct MemSink(pub Arc>>); + +impl TraceSink for MemSink { + fn emit(&mut self, rec: Value) { + self.0.lock().unwrap().push(rec); + } +} + +impl MemSink { + pub fn records(&self) -> Vec { + self.0.lock().unwrap().clone() + } + pub fn of_kind(&self, kind: &str) -> Vec { + self.records() + .into_iter() + .filter(|r| r.get("kind").and_then(Value::as_str) == Some(kind)) + .collect() + } +} + +pub struct NullSink; +impl TraceSink for NullSink { + fn emit(&mut self, _rec: Value) {} +} diff --git a/arena/openpoker/tests/fixtures/history_sample.json b/arena/openpoker/tests/fixtures/history_sample.json new file mode 100644 index 00000000..bcbee92f --- /dev/null +++ b/arena/openpoker/tests/fixtures/history_sample.json @@ -0,0 +1 @@ +{"hands": [{"hand_id": "8f253c18-19b1-4117-a7e2-1287903b2c87", "hand_url": "/hand/8f253c18-19b1-4117-a7e2-1287903b2c87", "table_id": "e2d2ab92-9bfd-477d-938e-132e079b56d7", "hand_number": 63, "seat": 3, "stack_start": 1980, "stack_end": 2000, "profit": 20, "actions": [{"action": "raise", "amount": 50, "street": "preflop"}], "all_actions": [{"seat": 1, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 1}, {"seat": 2, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 2}, {"seat": 3, "action": "raise", "amount": 50, "street": "preflop", "sequence_in_hand": 3}, {"seat": 0, "action": "fold", "amount": 0, "street": "showdown", "sequence_in_hand": 4}], "started_at": "2026-05-20T01:50:46.682125+00:00", "ended_at": "2026-05-20T01:50:46.682125+00:00", "board": [], "pot_total": 20, "num_players": 4, "small_blind": 10, "big_blind": 20, "dealer_seat": 2, "winners": [{"seat": 3, "name": "hero_bot"}], "hole_cards": ["Qh", "6s"], "shown_cards": {}, "hand_description": null, "is_winner": true, "evidence_hash": "fd354d4fe6fbdabd890e095f933f2d8399523a43df2ad2120ae1f733abf709d0", "evidence_url": "https://digitalevidence.constellationnetwork.io/fingerprint/fd354d4fe6fbdabd890e095f933f2d8399523a43df2ad2120ae1f733abf709d0"}, {"hand_id": "187dbf80-4484-4ac1-9fbb-29af3021972a", "hand_url": "/hand/187dbf80-4484-4ac1-9fbb-29af3021972a", "table_id": "e2d2ab92-9bfd-477d-938e-132e079b56d7", "hand_number": 62, "seat": 3, "stack_start": 2000, "stack_end": 1980, "profit": -20, "actions": [{"action": "fold", "amount": null, "street": "preflop"}], "all_actions": [{"seat": 0, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 1}, {"seat": 1, "action": "raise", "amount": 46, "street": "preflop", "sequence_in_hand": 2}, {"seat": 2, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 3}, {"seat": 3, "action": "fold", "amount": 0, "street": "showdown", "sequence_in_hand": 4}], "started_at": "2026-05-20T01:50:29.425805+00:00", "ended_at": "2026-05-20T01:50:29.425805+00:00", "board": [], "pot_total": 30, "num_players": 4, "small_blind": 10, "big_blind": 20, "dealer_seat": 1, "winners": [{"seat": 1, "name": "player_13"}], "hole_cards": ["Kh", "8d"], "shown_cards": {}, "hand_description": null, "is_winner": false, "evidence_hash": "f634633eae875c2f53a5c1c51a6856cb735167b0eaeb0f9d76f730f0aebb744f", "evidence_url": "https://digitalevidence.constellationnetwork.io/fingerprint/f634633eae875c2f53a5c1c51a6856cb735167b0eaeb0f9d76f730f0aebb744f"}, {"hand_id": "9b28d417-a45b-4c43-84ec-7bc45a5450d3", "hand_url": "/hand/9b28d417-a45b-4c43-84ec-7bc45a5450d3", "table_id": "e2d2ab92-9bfd-477d-938e-132e079b56d7", "hand_number": 34, "seat": 3, "stack_start": 1940, "stack_end": 1950, "profit": 10, "actions": [], "all_actions": [{"seat": 0, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 1}, {"seat": 1, "action": "fold", "amount": 0, "street": "showdown", "sequence_in_hand": 2}], "started_at": "2026-05-20T01:38:30.106417+00:00", "ended_at": "2026-05-20T01:38:30.106417+00:00", "board": [], "pot_total": 10, "num_players": 3, "small_blind": 10, "big_blind": 20, "dealer_seat": 0, "winners": [{"seat": 3, "name": "hero_bot"}], "hole_cards": ["7c", "Qh"], "shown_cards": {}, "hand_description": null, "is_winner": true, "evidence_hash": "cd031f67b951b7afdfaa9b34eb348a6956a94e8c9db4df612ae2a19378775eee", "evidence_url": "https://digitalevidence.constellationnetwork.io/fingerprint/cd031f67b951b7afdfaa9b34eb348a6956a94e8c9db4df612ae2a19378775eee"}, {"hand_id": "46634b4f-2674-494b-95e4-15566483a2cd", "hand_url": "/hand/46634b4f-2674-494b-95e4-15566483a2cd", "table_id": "e2d2ab92-9bfd-477d-938e-132e079b56d7", "hand_number": 33, "seat": 3, "stack_start": 2000, "stack_end": 1940, "profit": -60, "actions": [{"action": "raise", "amount": 60, "street": "preflop"}, {"action": "check", "amount": null, "street": "flop"}, {"action": "check", "amount": null, "street": "turn"}, {"action": "check", "amount": null, "street": "river"}], "all_actions": [{"seat": 3, "action": "raise", "amount": 60, "street": "preflop", "sequence_in_hand": 1}, {"seat": 0, "action": "call", "amount": 0, "street": "preflop", "sequence_in_hand": 2}, {"seat": 1, "action": "call", "amount": 0, "street": "flop", "sequence_in_hand": 3}, {"seat": 0, "action": "check", "amount": 0, "street": "flop", "sequence_in_hand": 4}, {"seat": 1, "action": "check", "amount": 0, "street": "flop", "sequence_in_hand": 5}, {"seat": 3, "action": "check", "amount": 0, "street": "turn", "sequence_in_hand": 6}, {"seat": 0, "action": "check", "amount": 130, "street": "turn", "sequence_in_hand": 7}, {"seat": 1, "action": "check", "amount": 0, "street": "turn", "sequence_in_hand": 8}, {"seat": 3, "action": "check", "amount": 0, "street": "river", "sequence_in_hand": 9}, {"seat": 0, "action": "check", "amount": 0, "street": "river", "sequence_in_hand": 10}, {"seat": 1, "action": "check", "amount": 0, "street": "river", "sequence_in_hand": 11}, {"seat": 3, "action": "check", "amount": 0, "street": "showdown", "sequence_in_hand": 12}], "started_at": "2026-05-20T01:38:19.060938+00:00", "ended_at": "2026-05-20T01:38:19.060938+00:00", "board": ["2s", "Ks", "5s", "Ah", "6h"], "pot_total": 120, "num_players": 3, "small_blind": 10, "big_blind": 20, "dealer_seat": 3, "winners": [{"seat": 1, "name": "player_13", "hand_description": "One pair"}], "hole_cards": ["7d", "5c"], "shown_cards": {"0": ["8h", "As"], "1": ["Tc", "Ac"], "3": ["7d", "5c"]}, "hand_description": null, "is_winner": false, "evidence_hash": "a7ae1d7f9e629f2efa43262c2ab113495b37a27f7b68b47d3de90b555fa3c9d3", "evidence_url": "https://digitalevidence.constellationnetwork.io/fingerprint/a7ae1d7f9e629f2efa43262c2ab113495b37a27f7b68b47d3de90b555fa3c9d3"}, {"hand_id": "65166e6d-1cda-4b84-92a0-a0b937f57a83", "hand_url": "/hand/65166e6d-1cda-4b84-92a0-a0b937f57a83", "table_id": "4f635acd-31f8-4df8-a5ba-41a5763af851", "hand_number": 5429, "seat": 2, "stack_start": 1950, "stack_end": 1940, "profit": -10, "actions": [{"action": "fold", "amount": null, "street": "preflop"}], "all_actions": [{"seat": 4, "action": "raise", "amount": 64, "street": "preflop", "sequence_in_hand": 1}, {"seat": 5, "action": "call", "amount": 0, "street": "preflop", "sequence_in_hand": 2}, {"seat": 0, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 3}, {"seat": 1, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 4}, {"seat": 2, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 5}, {"seat": 3, "action": "call", "amount": 0, "street": "flop", "sequence_in_hand": 6}, {"seat": 3, "action": "raise", "amount": 101, "street": "flop", "sequence_in_hand": 7}, {"seat": 4, "action": "call", "amount": 0, "street": "flop", "sequence_in_hand": 8}, {"seat": 5, "action": "fold", "amount": 0, "street": "turn", "sequence_in_hand": 9}, {"seat": 3, "action": "check", "amount": 0, "street": "turn", "sequence_in_hand": 10}, {"seat": 4, "action": "check", "amount": 0, "street": "river", "sequence_in_hand": 11}, {"seat": 3, "action": "raise", "amount": 202, "street": "river", "sequence_in_hand": 12}, {"seat": 4, "action": "call", "amount": 0, "street": "showdown", "sequence_in_hand": 13}], "started_at": "2026-05-20T01:04:13.166396+00:00", "ended_at": "2026-05-20T01:04:13.166396+00:00", "board": ["Ad", "9d", "Qc", "6c", "Ac"], "pot_total": 441, "num_players": 6, "small_blind": 10, "big_blind": 20, "dealer_seat": 1, "winners": [{"seat": 4, "name": "player_9", "hand_description": "Two pair"}], "hole_cards": ["6h", "3c"], "shown_cards": {"3": ["9h", "Kc"], "4": ["Kd", "Kh"]}, "hand_description": null, "is_winner": false, "evidence_hash": "43b66a7d8e778dd8e31376d846f84bb419c3110248398dd800d9f9ead45a6a2b", "evidence_url": "https://digitalevidence.constellationnetwork.io/fingerprint/43b66a7d8e778dd8e31376d846f84bb419c3110248398dd800d9f9ead45a6a2b"}, {"hand_id": "043f5efe-1571-4ff5-a1b1-8d61e5b809ad", "hand_url": "/hand/043f5efe-1571-4ff5-a1b1-8d61e5b809ad", "table_id": "4f635acd-31f8-4df8-a5ba-41a5763af851", "hand_number": 5428, "seat": 2, "stack_start": 1970, "stack_end": 1950, "profit": -20, "actions": [{"action": "fold", "amount": null, "street": "preflop"}], "all_actions": [{"seat": 3, "action": "raise", "amount": 56, "street": "preflop", "sequence_in_hand": 1}, {"seat": 4, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 2}, {"seat": 5, "action": "raise", "amount": 168, "street": "preflop", "sequence_in_hand": 3}, {"seat": 0, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 4}, {"seat": 1, "action": "call", "amount": 0, "street": "preflop", "sequence_in_hand": 5}, {"seat": 2, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 6}, {"seat": 3, "action": "call", "amount": 0, "street": "flop", "sequence_in_hand": 7}, {"seat": 1, "action": "check", "amount": 0, "street": "flop", "sequence_in_hand": 8}, {"seat": 3, "action": "raise", "amount": 262, "street": "flop", "sequence_in_hand": 9}, {"seat": 5, "action": "raise", "amount": 524, "street": "flop", "sequence_in_hand": 10}, {"seat": 1, "action": "raise", "amount": 838, "street": "flop", "sequence_in_hand": 11}, {"seat": 3, "action": "call", "amount": 0, "street": "flop", "sequence_in_hand": 12}, {"seat": 5, "action": "raise", "amount": 1771, "street": "flop", "sequence_in_hand": 13}, {"seat": 1, "action": "fold", "amount": 0, "street": "flop", "sequence_in_hand": 14}, {"seat": 3, "action": "call", "amount": 0, "street": "turn", "sequence_in_hand": 15}, {"seat": 3, "action": "raise", "amount": 2452, "street": "turn", "sequence_in_hand": 16}, {"seat": 5, "action": "fold", "amount": 0, "street": "showdown", "sequence_in_hand": 17}], "started_at": "2026-05-20T01:03:32.747231+00:00", "ended_at": "2026-05-20T01:03:32.747231+00:00", "board": ["Qc", "Ad", "6c", "9h"], "pot_total": 2965, "num_players": 6, "small_blind": 10, "big_blind": 20, "dealer_seat": 0, "winners": [{"seat": 3, "name": "player_15"}], "hole_cards": ["5c", "6h"], "shown_cards": {}, "hand_description": null, "is_winner": false, "evidence_hash": "8fc8885452581465f7ae000ade1dabbb0e3d19252737c8e7a3e1ff8f7edd664b", "evidence_url": "https://digitalevidence.constellationnetwork.io/fingerprint/8fc8885452581465f7ae000ade1dabbb0e3d19252737c8e7a3e1ff8f7edd664b"}, {"hand_id": "e39d0119-e8c8-4bed-b633-b79f99e944a5", "hand_url": "/hand/e39d0119-e8c8-4bed-b633-b79f99e944a5", "table_id": "4f635acd-31f8-4df8-a5ba-41a5763af851", "hand_number": 5427, "seat": 2, "stack_start": 1970, "stack_end": 1970, "profit": 0, "actions": [{"action": "fold", "amount": null, "street": "preflop"}], "all_actions": [{"seat": 2, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 1}, {"seat": 3, "action": "raise", "amount": 50, "street": "preflop", "sequence_in_hand": 2}, {"seat": 4, "action": "call", "amount": 0, "street": "preflop", "sequence_in_hand": 3}, {"seat": 5, "action": "call", "amount": 0, "street": "preflop", "sequence_in_hand": 4}, {"seat": 0, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 5}, {"seat": 1, "action": "fold", "amount": 0, "street": "flop", "sequence_in_hand": 6}, {"seat": 3, "action": "check", "amount": 0, "street": "flop", "sequence_in_hand": 7}, {"seat": 4, "action": "check", "amount": 0, "street": "flop", "sequence_in_hand": 8}, {"seat": 5, "action": "check", "amount": 0, "street": "turn", "sequence_in_hand": 9}, {"seat": 3, "action": "check", "amount": 0, "street": "turn", "sequence_in_hand": 10}, {"seat": 4, "action": "check", "amount": 0, "street": "turn", "sequence_in_hand": 11}, {"seat": 5, "action": "check", "amount": 0, "street": "river", "sequence_in_hand": 12}, {"seat": 3, "action": "check", "amount": 0, "street": "river", "sequence_in_hand": 13}, {"seat": 4, "action": "check", "amount": 0, "street": "river", "sequence_in_hand": 14}, {"seat": 5, "action": "raise", "amount": 126, "street": "river", "sequence_in_hand": 15}, {"seat": 3, "action": "call", "amount": 0, "street": "river", "sequence_in_hand": 16}, {"seat": 4, "action": "call", "amount": 0, "street": "showdown", "sequence_in_hand": 17}], "started_at": "2026-05-20T01:01:56.820174+00:00", "ended_at": "2026-05-20T01:01:56.820174+00:00", "board": ["4h", "Ah", "2h", "7d", "As"], "pot_total": 382, "num_players": 6, "small_blind": 10, "big_blind": 20, "dealer_seat": 5, "winners": [{"seat": 5, "name": "player_18", "hand_description": "Flush"}], "hole_cards": ["7c", "3d"], "shown_cards": {"3": ["8s", "Kd"], "4": ["Qc", "Tc"], "5": ["5h", "6h"]}, "hand_description": null, "is_winner": false, "evidence_hash": "0b3361d0d121fa2ec9680661b5a4433a055efff5e87b6b89dae2b5e933200179", "evidence_url": "https://digitalevidence.constellationnetwork.io/fingerprint/0b3361d0d121fa2ec9680661b5a4433a055efff5e87b6b89dae2b5e933200179"}, {"hand_id": "edb41a16-572d-4fa1-81a7-bd87e56b2895", "hand_url": "/hand/edb41a16-572d-4fa1-81a7-bd87e56b2895", "table_id": "4f635acd-31f8-4df8-a5ba-41a5763af851", "hand_number": 5426, "seat": 2, "stack_start": 1970, "stack_end": 1970, "profit": 0, "actions": [{"action": "fold", "amount": null, "street": "preflop"}], "all_actions": [{"seat": 1, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 1}, {"seat": 2, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 2}, {"seat": 3, "action": "raise", "amount": 50, "street": "preflop", "sequence_in_hand": 3}, {"seat": 4, "action": "call", "amount": 0, "street": "preflop", "sequence_in_hand": 4}, {"seat": 5, "action": "call", "amount": 0, "street": "preflop", "sequence_in_hand": 5}, {"seat": 0, "action": "fold", "amount": 0, "street": "flop", "sequence_in_hand": 6}, {"seat": 5, "action": "check", "amount": 110, "street": "flop", "sequence_in_hand": 7}, {"seat": 3, "action": "raise", "amount": 85, "street": "flop", "sequence_in_hand": 8}, {"seat": 4, "action": "raise", "amount": 170, "street": "flop", "sequence_in_hand": 9}, {"seat": 5, "action": "fold", "amount": 0, "street": "flop", "sequence_in_hand": 10}, {"seat": 3, "action": "call", "amount": 0, "street": "turn", "sequence_in_hand": 11}, {"seat": 3, "action": "raise", "amount": 255, "street": "turn", "sequence_in_hand": 12}, {"seat": 4, "action": "raise", "amount": 510, "street": "turn", "sequence_in_hand": 13}, {"seat": 3, "action": "call", "amount": 0, "street": "river", "sequence_in_hand": 14}, {"seat": 3, "action": "check", "amount": 0, "street": "river", "sequence_in_hand": 15}, {"seat": 4, "action": "check", "amount": 0, "street": "showdown", "sequence_in_hand": 16}], "started_at": "2026-05-20T01:00:54.044552+00:00", "ended_at": "2026-05-20T01:00:54.044552+00:00", "board": ["3d", "3s", "9s", "Th", "2s"], "pot_total": 800, "num_players": 6, "small_blind": 10, "big_blind": 20, "dealer_seat": 4, "winners": [{"seat": 4, "name": "player_9", "hand_description": "One pair"}], "hole_cards": ["4h", "4s"], "shown_cards": {"3": ["8d", "Jd"], "4": ["Kh", "Js"]}, "hand_description": null, "is_winner": false, "evidence_hash": "f6d3ad5b9bae0bd83e81088611f8c1fd5de23f238b7314f41f14307e7a0480c7", "evidence_url": "https://digitalevidence.constellationnetwork.io/fingerprint/f6d3ad5b9bae0bd83e81088611f8c1fd5de23f238b7314f41f14307e7a0480c7"}, {"hand_id": "06827ae4-586b-473c-b770-a9835a797c1c", "hand_url": "/hand/06827ae4-586b-473c-b770-a9835a797c1c", "table_id": "4f635acd-31f8-4df8-a5ba-41a5763af851", "hand_number": 5425, "seat": 2, "stack_start": 1970, "stack_end": 1970, "profit": 0, "actions": [{"action": "fold", "amount": null, "street": "preflop"}], "all_actions": [{"seat": 0, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 1}, {"seat": 1, "action": "raise", "amount": 48, "street": "preflop", "sequence_in_hand": 2}, {"seat": 2, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 3}, {"seat": 3, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 4}, {"seat": 4, "action": "call", "amount": 0, "street": "preflop", "sequence_in_hand": 5}, {"seat": 5, "action": "call", "amount": 0, "street": "flop", "sequence_in_hand": 6}, {"seat": 4, "action": "check", "amount": 0, "street": "flop", "sequence_in_hand": 7}, {"seat": 5, "action": "check", "amount": 0, "street": "flop", "sequence_in_hand": 8}, {"seat": 1, "action": "raise", "amount": 92, "street": "flop", "sequence_in_hand": 9}, {"seat": 4, "action": "fold", "amount": 0, "street": "flop", "sequence_in_hand": 10}, {"seat": 5, "action": "fold", "amount": 0, "street": "showdown", "sequence_in_hand": 11}], "started_at": "2026-05-20T00:59:48.954860+00:00", "ended_at": "2026-05-20T00:59:48.954860+00:00", "board": ["Th", "5c", "3h"], "pot_total": 96, "num_players": 6, "small_blind": 10, "big_blind": 20, "dealer_seat": 3, "winners": [{"seat": 1, "name": "player_11"}], "hole_cards": ["5h", "Qh"], "shown_cards": {}, "hand_description": null, "is_winner": false, "evidence_hash": "d4698b0a6ad0409facc910332fef54616e7381b2946cd23469d6018731145f19", "evidence_url": "https://digitalevidence.constellationnetwork.io/fingerprint/d4698b0a6ad0409facc910332fef54616e7381b2946cd23469d6018731145f19"}, {"hand_id": "704daa40-57e3-4d47-92eb-aa4259b404a5", "hand_url": "/hand/704daa40-57e3-4d47-92eb-aa4259b404a5", "table_id": "4f635acd-31f8-4df8-a5ba-41a5763af851", "hand_number": 5424, "seat": 2, "stack_start": 1970, "stack_end": 1970, "profit": 0, "actions": [{"action": "fold", "amount": null, "street": "preflop"}], "all_actions": [{"seat": 5, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 1}, {"seat": 0, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 2}, {"seat": 1, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 3}, {"seat": 2, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 4}, {"seat": 3, "action": "fold", "amount": 0, "street": "showdown", "sequence_in_hand": 5}], "started_at": "2026-05-20T00:59:09.918471+00:00", "ended_at": "2026-05-20T00:59:09.918471+00:00", "board": [], "pot_total": 10, "num_players": 6, "small_blind": 10, "big_blind": 20, "dealer_seat": 2, "winners": [{"seat": 4, "name": "player_9"}], "hole_cards": ["9c", "3s"], "shown_cards": {}, "hand_description": null, "is_winner": false, "evidence_hash": "67a719f49bec4e0a7197007874621eb9eeba03dddadd19e5af076ed8871ed199", "evidence_url": "https://digitalevidence.constellationnetwork.io/fingerprint/67a719f49bec4e0a7197007874621eb9eeba03dddadd19e5af076ed8871ed199"}, {"hand_id": "f720914c-568f-4dae-b374-79ee93d77609", "hand_url": "/hand/f720914c-568f-4dae-b374-79ee93d77609", "table_id": "4f635acd-31f8-4df8-a5ba-41a5763af851", "hand_number": 5423, "seat": 2, "stack_start": 1980, "stack_end": 1970, "profit": -10, "actions": [{"action": "fold", "amount": null, "street": "preflop"}], "all_actions": [{"seat": 4, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 1}, {"seat": 5, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 2}, {"seat": 0, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 3}, {"seat": 1, "action": "raise", "amount": 44, "street": "preflop", "sequence_in_hand": 4}, {"seat": 2, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 5}, {"seat": 3, "action": "fold", "amount": 0, "street": "showdown", "sequence_in_hand": 6}], "started_at": "2026-05-20T00:58:49.430978+00:00", "ended_at": "2026-05-20T00:58:49.430978+00:00", "board": [], "pot_total": 30, "num_players": 6, "small_blind": 10, "big_blind": 20, "dealer_seat": 1, "winners": [{"seat": 1, "name": "player_11"}], "hole_cards": ["6s", "5h"], "shown_cards": {}, "hand_description": null, "is_winner": false, "evidence_hash": "250200c5d6b4ad36718e69220db97f1c31f5bd12dfe64a0abdb0c2565e95b4ad", "evidence_url": "https://digitalevidence.constellationnetwork.io/fingerprint/250200c5d6b4ad36718e69220db97f1c31f5bd12dfe64a0abdb0c2565e95b4ad"}, {"hand_id": "69b39ada-55b3-413d-8438-905745d8ecee", "hand_url": "/hand/69b39ada-55b3-413d-8438-905745d8ecee", "table_id": "4f635acd-31f8-4df8-a5ba-41a5763af851", "hand_number": 5422, "seat": 2, "stack_start": 2000, "stack_end": 1980, "profit": -20, "actions": [{"action": "fold", "amount": null, "street": "preflop"}], "all_actions": [{"seat": 3, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 1}, {"seat": 4, "action": "raise", "amount": 60, "street": "preflop", "sequence_in_hand": 2}, {"seat": 5, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 3}, {"seat": 0, "action": "call", "amount": 0, "street": "preflop", "sequence_in_hand": 4}, {"seat": 1, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 5}, {"seat": 2, "action": "fold", "amount": 0, "street": "flop", "sequence_in_hand": 6}, {"seat": 4, "action": "check", "amount": 0, "street": "flop", "sequence_in_hand": 7}, {"seat": 0, "action": "check", "amount": 0, "street": "turn", "sequence_in_hand": 8}, {"seat": 4, "action": "raise", "amount": 75, "street": "turn", "sequence_in_hand": 9}, {"seat": 0, "action": "call", "amount": 0, "street": "river", "sequence_in_hand": 10}, {"seat": 4, "action": "check", "amount": 0, "street": "river", "sequence_in_hand": 11}, {"seat": 0, "action": "check", "amount": 0, "street": "showdown", "sequence_in_hand": 12}], "started_at": "2026-05-20T00:58:25.862582+00:00", "ended_at": "2026-05-20T00:58:25.862582+00:00", "board": ["As", "8h", "9h", "4d", "3c"], "pot_total": 165, "num_players": 6, "small_blind": 10, "big_blind": 20, "dealer_seat": 0, "winners": [{"seat": 4, "name": "player_9", "hand_description": "One pair"}], "hole_cards": ["2h", "8d"], "shown_cards": {"4": ["6c", "6s"], "0": ["5h", "Qh"]}, "hand_description": null, "is_winner": false, "evidence_hash": "277cac272e2b34e8516c56fe82e7236bad0b6b60fb95cc33683230d770a0da80", "evidence_url": "https://digitalevidence.constellationnetwork.io/fingerprint/277cac272e2b34e8516c56fe82e7236bad0b6b60fb95cc33683230d770a0da80"}, {"hand_id": "421ad9c6-2b0a-450e-8724-49bbbce7c29d", "hand_url": "/hand/421ad9c6-2b0a-450e-8724-49bbbce7c29d", "table_id": "4f635acd-31f8-4df8-a5ba-41a5763af851", "hand_number": 5421, "seat": 2, "stack_start": 2000, "stack_end": 2000, "profit": 0, "actions": [{"action": "fold", "amount": null, "street": "preflop"}], "all_actions": [{"seat": 2, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 1}, {"seat": 3, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 2}, {"seat": 4, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 3}, {"seat": 5, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 4}, {"seat": 0, "action": "raise", "amount": 60, "street": "preflop", "sequence_in_hand": 5}, {"seat": 1, "action": "fold", "amount": 0, "street": "showdown", "sequence_in_hand": 6}], "started_at": "2026-05-20T00:57:44.191060+00:00", "ended_at": "2026-05-20T00:57:44.191060+00:00", "board": [], "pot_total": 20, "num_players": 6, "small_blind": 10, "big_blind": 20, "dealer_seat": 5, "winners": [{"seat": 0, "name": "player_17"}], "hole_cards": ["Ad", "6h"], "shown_cards": {}, "hand_description": null, "is_winner": false, "evidence_hash": "95c0c47b16ff5b915b0e495df4705460f09dca533173c2f1c47db477c22c0c54", "evidence_url": "https://digitalevidence.constellationnetwork.io/fingerprint/95c0c47b16ff5b915b0e495df4705460f09dca533173c2f1c47db477c22c0c54"}, {"hand_id": "fddc40c8-b749-4414-ad11-97f9a6992ab4", "hand_url": "/hand/fddc40c8-b749-4414-ad11-97f9a6992ab4", "table_id": "309196cb-19aa-4de8-a56f-c170b3558f66", "hand_number": 160, "seat": 4, "stack_start": 1980, "stack_end": 1970, "profit": -10, "actions": [{"action": "fold", "amount": null, "street": "preflop"}], "all_actions": [{"seat": 0, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 1}, {"seat": 1, "action": "raise", "amount": 48, "street": "preflop", "sequence_in_hand": 2}, {"seat": 2, "action": "call", "amount": 0, "street": "preflop", "sequence_in_hand": 3}, {"seat": 3, "action": "call", "amount": 0, "street": "preflop", "sequence_in_hand": 4}, {"seat": 5, "action": "fold", "amount": 0, "street": "flop", "sequence_in_hand": 5}, {"seat": 1, "action": "raise", "amount": 125, "street": "flop", "sequence_in_hand": 6}, {"seat": 2, "action": "fold", "amount": 0, "street": "flop", "sequence_in_hand": 7}, {"seat": 3, "action": "raise", "amount": 250, "street": "flop", "sequence_in_hand": 8}, {"seat": 1, "action": "call", "amount": 0, "street": "turn", "sequence_in_hand": 9}, {"seat": 1, "action": "check", "amount": 0, "street": "turn", "sequence_in_hand": 10}, {"seat": 3, "action": "check", "amount": 0, "street": "river", "sequence_in_hand": 11}, {"seat": 1, "action": "check", "amount": 0, "street": "river", "sequence_in_hand": 12}, {"seat": 3, "action": "check", "amount": 0, "street": "showdown", "sequence_in_hand": 13}], "started_at": "2026-05-20T00:56:35.058779+00:00", "ended_at": "2026-05-20T00:56:35.058779+00:00", "board": ["2h", "7c", "8h", "6d", "Tc"], "pot_total": 376, "num_players": 6, "small_blind": 10, "big_blind": 20, "dealer_seat": 3, "winners": [{"seat": 1, "name": "player_10", "hand_description": "One pair"}], "hole_cards": ["4s", "4d"], "shown_cards": {"1": ["3c", "3s"], "3": ["5h", "Kd"]}, "hand_description": null, "is_winner": false, "evidence_hash": "2e0b7df4b3f1da44c76973e299d9f5cca24abf5921ee5357758dedd9e53c88fb", "evidence_url": "https://digitalevidence.constellationnetwork.io/fingerprint/2e0b7df4b3f1da44c76973e299d9f5cca24abf5921ee5357758dedd9e53c88fb"}, {"hand_id": "cf3a6b36-ae83-4af9-8e57-5b8e5aeaae6e", "hand_url": "/hand/cf3a6b36-ae83-4af9-8e57-5b8e5aeaae6e", "table_id": "309196cb-19aa-4de8-a56f-c170b3558f66", "hand_number": 159, "seat": 4, "stack_start": 2000, "stack_end": 1980, "profit": -20, "actions": [{"action": "fold", "amount": null, "street": "preflop"}], "all_actions": [{"seat": 5, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 1}, {"seat": 0, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 2}, {"seat": 1, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 3}, {"seat": 2, "action": "raise", "amount": 205, "street": "preflop", "sequence_in_hand": 4}, {"seat": 3, "action": "call", "amount": 0, "street": "preflop", "sequence_in_hand": 5}, {"seat": 4, "action": "fold", "amount": 0, "street": "showdown", "sequence_in_hand": 6}], "started_at": "2026-05-20T00:55:37.410567+00:00", "ended_at": "2026-05-20T00:55:37.410567+00:00", "board": ["7s", "9c", "2s", "9d", "Qc"], "pot_total": 225, "num_players": 6, "small_blind": 10, "big_blind": 20, "dealer_seat": 2, "winners": [{"seat": 2, "name": "player_14", "hand_description": "Three of a kind"}], "hole_cards": ["Ks", "4s"], "shown_cards": {"3": ["8s", "Jh"], "2": ["Kc", "9h"]}, "hand_description": null, "is_winner": false, "evidence_hash": "1ecca59284eae48d21fb0877e0a0c94689fbc44f3c3f15282075bd0a92414af2", "evidence_url": "https://digitalevidence.constellationnetwork.io/fingerprint/1ecca59284eae48d21fb0877e0a0c94689fbc44f3c3f15282075bd0a92414af2"}, {"hand_id": "d9d9f9b3-c704-4d7c-8aa5-1f6d5761dbaa", "hand_url": "/hand/d9d9f9b3-c704-4d7c-8aa5-1f6d5761dbaa", "table_id": "309196cb-19aa-4de8-a56f-c170b3558f66", "hand_number": 158, "seat": 4, "stack_start": 2000, "stack_end": 2000, "profit": 0, "actions": [{"action": "fold", "amount": null, "street": "preflop"}], "all_actions": [{"seat": 4, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 1}, {"seat": 5, "action": "raise", "amount": 54, "street": "preflop", "sequence_in_hand": 2}, {"seat": 0, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 3}, {"seat": 1, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 4}, {"seat": 2, "action": "call", "amount": 0, "street": "preflop", "sequence_in_hand": 5}, {"seat": 3, "action": "call", "amount": 0, "street": "flop", "sequence_in_hand": 6}, {"seat": 2, "action": "raise", "amount": 107, "street": "flop", "sequence_in_hand": 7}, {"seat": 3, "action": "raise", "amount": 214, "street": "flop", "sequence_in_hand": 8}, {"seat": 5, "action": "raise", "amount": 321, "street": "flop", "sequence_in_hand": 9}, {"seat": 2, "action": "call", "amount": 0, "street": "flop", "sequence_in_hand": 10}, {"seat": 3, "action": "call", "amount": 672, "street": "turn", "sequence_in_hand": 11}, {"seat": 2, "action": "check", "amount": 0, "street": "turn", "sequence_in_hand": 12}, {"seat": 3, "action": "raise", "amount": 1330, "street": "turn", "sequence_in_hand": 13}, {"seat": 5, "action": "call", "amount": 0, "street": "turn", "sequence_in_hand": 14}, {"seat": 2, "action": "call", "amount": 0, "street": "river", "sequence_in_hand": 15}, {"seat": 2, "action": "raise", "amount": 242, "street": "river", "sequence_in_hand": 16}, {"seat": 5, "action": "call", "amount": 0, "street": "showdown", "sequence_in_hand": 17}], "started_at": "2026-05-20T00:55:14.933485+00:00", "ended_at": "2026-05-20T00:55:14.933485+00:00", "board": ["Qs", "2c", "2d", "8s", "9s"], "pot_total": 1742, "num_players": 6, "small_blind": 10, "big_blind": 20, "dealer_seat": 1, "winners": [{"seat": 3, "name": "player_12", "hand_description": "Two pair"}, {"seat": 5, "name": "player_16", "hand_description": "Two pair"}], "hole_cards": ["5h", "3d"], "shown_cards": {"2": ["8c", "Ah"], "3": ["Ks", "Qd"], "5": ["Qh", "Kc"]}, "hand_description": null, "is_winner": false, "evidence_hash": "78615ffe2b6ee006b14ab0a7ac160a821b1473cac9f0c72d3945feec2e0d1315", "evidence_url": "https://digitalevidence.constellationnetwork.io/fingerprint/78615ffe2b6ee006b14ab0a7ac160a821b1473cac9f0c72d3945feec2e0d1315"}, {"hand_id": "6b7ec313-510c-4cb2-9879-19fa177bf3c2", "hand_url": "/hand/6b7ec313-510c-4cb2-9879-19fa177bf3c2", "table_id": "309196cb-19aa-4de8-a56f-c170b3558f66", "hand_number": 157, "seat": 4, "stack_start": 2000, "stack_end": 2000, "profit": 0, "actions": [{"action": "fold", "amount": null, "street": "preflop"}], "all_actions": [{"seat": 3, "action": "call", "amount": 0, "street": "preflop", "sequence_in_hand": 1}, {"seat": 4, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 2}, {"seat": 5, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 3}, {"seat": 0, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 4}, {"seat": 1, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 5}, {"seat": 2, "action": "check", "amount": 0, "street": "flop", "sequence_in_hand": 6}, {"seat": 2, "action": "check", "amount": 0, "street": "flop", "sequence_in_hand": 7}, {"seat": 3, "action": "raise", "amount": 33, "street": "flop", "sequence_in_hand": 8}, {"seat": 2, "action": "call", "amount": 0, "street": "turn", "sequence_in_hand": 9}, {"seat": 2, "action": "raise", "amount": 84, "street": "turn", "sequence_in_hand": 10}, {"seat": 3, "action": "call", "amount": 0, "street": "river", "sequence_in_hand": 11}, {"seat": 2, "action": "raise", "amount": 216, "street": "river", "sequence_in_hand": 12}, {"seat": 3, "action": "fold", "amount": 432, "street": "showdown", "sequence_in_hand": 13}], "started_at": "2026-05-20T00:53:46.022194+00:00", "ended_at": "2026-05-20T00:53:46.022194+00:00", "board": ["Th", "Ts", "Td", "Tc", "5s"], "pot_total": 147, "num_players": 6, "small_blind": 10, "big_blind": 20, "dealer_seat": 0, "winners": [{"seat": 2, "name": "player_14"}], "hole_cards": ["Ac", "7s"], "shown_cards": {}, "hand_description": null, "is_winner": false, "evidence_hash": "0d06091efb51185cc91ae9f729c41d84063365593ba6d0377d967e5982d7913c", "evidence_url": "https://digitalevidence.constellationnetwork.io/fingerprint/0d06091efb51185cc91ae9f729c41d84063365593ba6d0377d967e5982d7913c"}, {"hand_id": "c3b1212d-437d-456a-9ff8-dd176b4dc19d", "hand_url": "/hand/c3b1212d-437d-456a-9ff8-dd176b4dc19d", "table_id": "309196cb-19aa-4de8-a56f-c170b3558f66", "hand_number": 155, "seat": 4, "stack_start": 1990, "stack_end": 1990, "profit": 0, "actions": [{"action": "fold", "amount": null, "street": "preflop"}], "all_actions": [{"seat": 1, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 1}, {"seat": 2, "action": "raise", "amount": 62, "street": "preflop", "sequence_in_hand": 2}, {"seat": 3, "action": "call", "amount": 0, "street": "preflop", "sequence_in_hand": 3}, {"seat": 4, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 4}, {"seat": 5, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 5}, {"seat": 0, "action": "fold", "amount": 0, "street": "showdown", "sequence_in_hand": 6}], "started_at": "2026-05-20T00:52:13.824815+00:00", "ended_at": "2026-05-20T00:52:13.824815+00:00", "board": ["5s", "Kd", "7s", "Kc", "Jc"], "pot_total": 92, "num_players": 6, "small_blind": 10, "big_blind": 20, "dealer_seat": 4, "winners": [{"seat": 3, "name": "player_12", "hand_description": "Three of a kind"}], "hole_cards": ["4d", "6c"], "shown_cards": {"2": ["8c", "8s"], "3": ["Ks", "3c"]}, "hand_description": null, "is_winner": false, "evidence_hash": "2f899570c0f73d577322b6c4238ef6c8d7147f917b073805bdd351303d54335b", "evidence_url": "https://digitalevidence.constellationnetwork.io/fingerprint/2f899570c0f73d577322b6c4238ef6c8d7147f917b073805bdd351303d54335b"}, {"hand_id": "9240b516-9be7-4e10-bba2-58ca7bad2d57", "hand_url": "/hand/9240b516-9be7-4e10-bba2-58ca7bad2d57", "table_id": "309196cb-19aa-4de8-a56f-c170b3558f66", "hand_number": 154, "seat": 4, "stack_start": 2000, "stack_end": 1990, "profit": -10, "actions": [{"action": "fold", "amount": null, "street": "preflop"}], "all_actions": [{"seat": 0, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 1}, {"seat": 1, "action": "raise", "amount": 48, "street": "preflop", "sequence_in_hand": 2}, {"seat": 2, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 3}, {"seat": 3, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 4}, {"seat": 4, "action": "fold", "amount": 0, "street": "preflop", "sequence_in_hand": 5}, {"seat": 5, "action": "fold", "amount": 0, "street": "showdown", "sequence_in_hand": 6}], "started_at": "2026-05-20T00:51:50.263713+00:00", "ended_at": "2026-05-20T00:51:50.263713+00:00", "board": [], "pot_total": 30, "num_players": 6, "small_blind": 10, "big_blind": 20, "dealer_seat": 3, "winners": [{"seat": 1, "name": "player_10"}], "hole_cards": ["3d", "6h"], "shown_cards": {}, "hand_description": null, "is_winner": false, "evidence_hash": "5abfe424b923f5ee9e52ea26ef1e4524a6dc1a6caf98ff193f51fb0ce13690b9", "evidence_url": "https://digitalevidence.constellationnetwork.io/fingerprint/5abfe424b923f5ee9e52ea26ef1e4524a6dc1a6caf98ff193f51fb0ce13690b9"}], "total_hands": 19} \ No newline at end of file diff --git a/arena/openpoker/tests/fixtures/smoke_raw.jsonl b/arena/openpoker/tests/fixtures/smoke_raw.jsonl new file mode 100644 index 00000000..8059fdbe --- /dev/null +++ b/arena/openpoker/tests/fixtures/smoke_raw.jsonl @@ -0,0 +1,404 @@ +{"dir": "out", "msg": {"buy_in": 2000, "type": "join_lobby"}} +{"dir": "out", "msg": {"enabled": true, "type": "set_auto_rebuy"}} +{"dir": "in", "msg": {"agent_id": "agent-id", "name": "hero_bot", "type": "connected"}} +{"dir": "in", "msg": {"estimated_wait": "~30s", "position": 1, "type": "lobby_joined"}} +{"dir": "in", "msg": {"hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 47, "players": [{"avatar_url": null, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 5070}, {"avatar_url": null, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 2000}, {"avatar_url": null, "is_pro": false, "name": "player_8", "public_profile_slug": "player_8", "seat": 2, "stack": 2557}, {"avatar_url": null, "is_pro": false, "name": "hero_bot", "public_profile_slug": null, "seat": 3, "stack": 2000}, {"avatar_url": null, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1011}, {"avatar_url": "/avatar.webp", "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948}], "seat": 3, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 9934, "ts": "2026-10-13T05:45:45.028344+00:00", "type": "table_joined"}} +{"dir": "in", "msg": {"actor_seat": 1, "big_blind": 20, "board": [], "dealer_seat": 0, "hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 48, "hero": {"seat": 3}, "pot": 60, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 5050, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1980, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_8", "public_profile_slug": "player_8", "seat": 2, "stack": 2537, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2000, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1011, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:20d09eca6040bba6c382c4ba4fd87bac4b3f937963e7cde7660f19355c17572b", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 9935, "ts": "2026-10-13T05:45:45.028709+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"enabled": true, "type": "auto_rebuy_set"}} +{"dir": "in", "msg": {"cards": ["5s", "4c", "3c"], "hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 50, "state_hash": null, "stream": "event", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 9937, "ts": "2026-10-13T05:45:45.738024+00:00", "type": "community_cards"}} +{"dir": "in", "msg": {"actor_seat": 1, "big_blind": 20, "board": ["5s", "4c", "3c"], "dealer_seat": 0, "hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 51, "hero": {"seat": 3}, "pot": 60, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 5050, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1980, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_8", "public_profile_slug": "player_8", "seat": 2, "stack": 2537, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2000, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1011, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:b3be3a22c9c01cdf09005108d203a4230785ac58f8bec179e6eba85ffaf3d770", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 9938, "ts": "2026-10-13T05:45:45.739042+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "check", "action_id": "54e59922-7d50-4a46-a8da-2f769441229c", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 56, "name": "player_5", "player_stack_after": 1980, "player_stack_before": 1980, "pot": 60, "pot_after": 60, "pot_before": 60, "reason": null, "seat": 1, "stack": 1980, "stack_after": 1980, "stack_before": 1980, "state_hash": null, "stream": "event", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 9943, "to_call_before": null, "ts": "2026-10-13T05:45:46.021218+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 2, "big_blind": 20, "board": ["5s", "4c", "3c"], "dealer_seat": 0, "hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 57, "hero": {"seat": 3}, "pot": 60, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 5050, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1980, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_8", "public_profile_slug": "player_8", "seat": 2, "stack": 2537, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2000, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1011, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:a0528110e605a947bef6fa28a910c18fc6e56d2e0f948aeac311b19a01663282", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 9944, "ts": "2026-10-13T05:45:46.023154+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "check", "action_id": "85530087-400a-46d0-bb25-7fac979edcff", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 62, "name": "player_8", "player_stack_after": 2537, "player_stack_before": 2537, "pot": 60, "pot_after": 60, "pot_before": 60, "reason": null, "seat": 2, "stack": 2537, "stack_after": 2537, "stack_before": 2537, "state_hash": null, "stream": "event", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 9949, "to_call_before": null, "ts": "2026-10-13T05:45:49.033918+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": ["5s", "4c", "3c"], "dealer_seat": 0, "hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 63, "hero": {"seat": 3}, "pot": 60, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 5050, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1980, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_8", "public_profile_slug": "player_8", "seat": 2, "stack": 2537, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2000, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1011, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:fb12f156fc6920971b3d234c95862a9097ecf08f66fb66877c197b8a40c0bb79", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 9950, "ts": "2026-10-13T05:45:49.035666+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "raise", "action_id": "f75e2dc3-d113-4ed2-9fdf-d2a3bac36a21", "amount": 60, "amount_mode": "to_total", "contribution_delta": 60, "hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 68, "name": "player_1", "player_stack_after": 4990, "player_stack_before": 5050, "pot": 120, "pot_after": 120, "pot_before": 60, "reason": null, "seat": 0, "stack": 4990, "stack_after": 4990, "stack_before": 5050, "state_hash": null, "stream": "event", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 9955, "to_call_before": null, "ts": "2026-10-13T05:45:52.310471+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 1, "big_blind": 20, "board": ["5s", "4c", "3c"], "dealer_seat": 0, "hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 69, "hero": {"seat": 3}, "pot": 120, "seats": [{"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4990, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1980, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_8", "public_profile_slug": "player_8", "seat": 2, "stack": 2537, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2000, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1011, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:e33900267a2a79a63f7f80bef67675ec8f0c9f1f927e24398b493c0f0de9c66a", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 9956, "ts": "2026-10-13T05:45:52.311481+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "call", "action_id": "b122b1b1-ed3b-4405-adc5-9fec585794d1", "amount": null, "amount_mode": "incremental", "contribution_delta": 60, "hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 74, "name": "player_5", "player_stack_after": 1920, "player_stack_before": 1980, "pot": 180, "pot_after": 180, "pot_before": 120, "reason": null, "seat": 1, "stack": 1920, "stack_after": 1920, "stack_before": 1980, "state_hash": null, "stream": "event", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 9961, "to_call_before": 60, "ts": "2026-10-13T05:45:55.591363+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 2, "big_blind": 20, "board": ["5s", "4c", "3c"], "dealer_seat": 0, "hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 75, "hero": {"seat": 3}, "pot": 180, "seats": [{"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4990, "status": "active"}, {"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1920, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_8", "public_profile_slug": "player_8", "seat": 2, "stack": 2537, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2000, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1011, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:50e875eca0f187067f1398b1a86f0e3185192d9a088ccc525efc14525c7bad8d", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 9962, "ts": "2026-10-13T05:45:55.593114+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "raise", "action_id": "b96722de-4902-4543-8e29-7a67f5a45d06", "amount": 120, "amount_mode": "to_total", "contribution_delta": 120, "hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 80, "name": "player_8", "player_stack_after": 2417, "player_stack_before": 2537, "pot": 300, "pot_after": 300, "pot_before": 180, "reason": null, "seat": 2, "stack": 2417, "stack_after": 2417, "stack_before": 2537, "state_hash": null, "stream": "event", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 9967, "to_call_before": 60, "ts": "2026-10-13T05:45:58.601976+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": ["5s", "4c", "3c"], "dealer_seat": 0, "hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 81, "hero": {"seat": 3}, "pot": 300, "seats": [{"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4990, "status": "active"}, {"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1920, "status": "active"}, {"bet": 120, "folded": false, "in_hand": true, "is_pro": false, "name": "player_8", "public_profile_slug": "player_8", "seat": 2, "stack": 2417, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2000, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1011, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:8b7f81649163f0d0d662cd84411a210b78c87eeb6ecc4c754112cfe783e5910e", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 9968, "ts": "2026-10-13T05:45:58.602906+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "call", "action_id": "9169b0c1-2529-4135-b3fe-0911ad6e22f5", "amount": null, "amount_mode": "incremental", "contribution_delta": 60, "hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 86, "name": "player_1", "player_stack_after": 4930, "player_stack_before": 4990, "pot": 360, "pot_after": 360, "pot_before": 300, "reason": null, "seat": 0, "stack": 4930, "stack_after": 4930, "stack_before": 4990, "state_hash": null, "stream": "event", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 9973, "to_call_before": 60, "ts": "2026-10-13T05:46:01.902968+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 1, "big_blind": 20, "board": ["5s", "4c", "3c"], "dealer_seat": 0, "hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 87, "hero": {"seat": 3}, "pot": 360, "seats": [{"bet": 120, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4930, "status": "active"}, {"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1920, "status": "active"}, {"bet": 120, "folded": false, "in_hand": true, "is_pro": false, "name": "player_8", "public_profile_slug": "player_8", "seat": 2, "stack": 2417, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2000, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1011, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:395d0a4c4904e6fa9bed6f8acc7a7929a8d1948fd73030308677ce710170398e", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 9974, "ts": "2026-10-13T05:46:01.904227+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "call", "action_id": "7a3f625d-c5de-4b2f-84fd-2a1ae657a9b0", "amount": null, "amount_mode": "incremental", "contribution_delta": 60, "hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 92, "name": "player_5", "player_stack_after": 1860, "player_stack_before": 1920, "pot": 420, "pot_after": 420, "pot_before": 360, "reason": null, "seat": 1, "stack": 1860, "stack_after": 1860, "stack_before": 1920, "state_hash": null, "stream": "event", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 9979, "to_call_before": 60, "ts": "2026-10-13T05:46:05.196422+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 1, "big_blind": 20, "board": ["5s", "4c", "3c"], "dealer_seat": 0, "hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 93, "hero": {"seat": 3}, "pot": 420, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4930, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_8", "public_profile_slug": "player_8", "seat": 2, "stack": 2417, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2000, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1011, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:269f173c40bd7093dd76ab1c932a299320cf30722b4acc96afde39c3dc5fe93f", "stream": "state", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 9980, "ts": "2026-10-13T05:46:05.197414+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"cards": ["5s", "4c", "3c", "5c"], "hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 94, "state_hash": null, "stream": "event", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 9981, "ts": "2026-10-13T05:46:08.203180+00:00", "type": "community_cards"}} +{"dir": "in", "msg": {"actor_seat": 1, "big_blind": 20, "board": ["5s", "4c", "3c", "5c"], "dealer_seat": 0, "hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 95, "hero": {"seat": 3}, "pot": 420, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4930, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_8", "public_profile_slug": "player_8", "seat": 2, "stack": 2417, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2000, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1011, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:a040dc9790a8d7d531dde678905807d236e29179c7912b863ca9db9c8eb2ce4b", "stream": "state", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 9982, "ts": "2026-10-13T05:46:08.204535+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "check", "action_id": "55b71270-9615-4809-a1e0-bba6e2c3a1f9", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 100, "name": "player_5", "player_stack_after": 1860, "player_stack_before": 1860, "pot": 420, "pot_after": 420, "pot_before": 420, "reason": null, "seat": 1, "stack": 1860, "stack_after": 1860, "stack_before": 1860, "state_hash": null, "stream": "event", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 9987, "to_call_before": null, "ts": "2026-10-13T05:46:08.484715+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 2, "big_blind": 20, "board": ["5s", "4c", "3c", "5c"], "dealer_seat": 0, "hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 101, "hero": {"seat": 3}, "pot": 420, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4930, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_8", "public_profile_slug": "player_8", "seat": 2, "stack": 2417, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2000, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1011, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:10f7517ce188bc94bbea72779efa9fe466c6b2549b551ca974ffd2f3404ade5b", "stream": "state", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 9988, "ts": "2026-10-13T05:46:08.485758+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "raise", "action_id": "5f60aff2-e21b-4fd7-9c8c-a4c756560c74", "amount": 302, "amount_mode": "to_total", "contribution_delta": 302, "hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 106, "name": "player_8", "player_stack_after": 2115, "player_stack_before": 2417, "pot": 722, "pot_after": 722, "pot_before": 420, "reason": null, "seat": 2, "stack": 2115, "stack_after": 2115, "stack_before": 2417, "state_hash": null, "stream": "event", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 9993, "to_call_before": null, "ts": "2026-10-13T05:46:11.494717+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": ["5s", "4c", "3c", "5c"], "dealer_seat": 0, "hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 107, "hero": {"seat": 3}, "pot": 722, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4930, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 302, "folded": false, "in_hand": true, "is_pro": false, "name": "player_8", "public_profile_slug": "player_8", "seat": 2, "stack": 2115, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2000, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1011, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:85d2b6ee2aa4ee345f9884b6d3f4e444f49cd90295e02adc7540d9f0a200a79c", "stream": "state", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 9994, "ts": "2026-10-13T05:46:11.495610+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "6d3c7d23-b7c8-4578-ac87-067ee1fe1598", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 112, "name": "player_1", "player_stack_after": 4930, "player_stack_before": 4930, "pot": 722, "pot_after": 722, "pot_before": 722, "reason": null, "seat": 0, "stack": 4930, "stack_after": 4930, "stack_before": 4930, "state_hash": null, "stream": "event", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 9999, "to_call_before": 302, "ts": "2026-10-13T05:46:14.839728+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 1, "big_blind": 20, "board": ["5s", "4c", "3c", "5c"], "dealer_seat": 0, "hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 113, "hero": {"seat": 3}, "pot": 722, "seats": [{"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4930, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 302, "folded": false, "in_hand": true, "is_pro": false, "name": "player_8", "public_profile_slug": "player_8", "seat": 2, "stack": 2115, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2000, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1011, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:3f81891b6bdd12750a532afb24b392ed9606582997d67fa2deb9674af6db4ec9", "stream": "state", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10000, "ts": "2026-10-13T05:46:14.841348+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "d11383f3-d95a-48f9-9ce2-d8e1dfa37bd7", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 118, "name": "player_5", "player_stack_after": 1860, "player_stack_before": 1860, "pot": 722, "pot_after": 722, "pot_before": 722, "reason": null, "seat": 1, "stack": 1860, "stack_after": 1860, "stack_before": 1860, "state_hash": null, "stream": "event", "street": "showdown", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10005, "to_call_before": 302, "ts": "2026-10-13T05:46:18.229808+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"big_blind": 20, "board": ["5s", "4c", "3c", "5c"], "dealer_seat": 0, "hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 119, "hero": {"seat": 3}, "pot": 0, "seats": [{"bet": 0, "in_hand": false, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4930, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_8", "public_profile_slug": "player_8", "seat": 2, "stack": 2837, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2000, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1011, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "in_hand": false, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:aea85f2a5c2c25ffbb3e271de9ca0f2781ed18df367a9d8afbe7479b5f671bbd", "stream": "state", "street": "idle", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10006, "ts": "2026-10-13T05:46:18.230833+00:00", "type": "table_state", "waiting_details": {"active_players": 6, "away_players": 0, "connected_players": 6, "disconnected_players": 0, "eligible_players": 6, "min_required": 2, "player_count": 6}, "waiting_reason": "awaiting_hand_start"}} +{"dir": "in", "msg": {"actions": [{"action": "fold", "amount": null, "seat": 4, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 5, "street": "preflop"}, {"action": "call", "amount": null, "seat": 0, "street": "preflop"}, {"action": "call", "amount": null, "seat": 1, "street": "preflop"}, {"action": "check", "amount": null, "seat": 2, "street": "preflop"}, {"action": "check", "amount": null, "seat": 1, "street": "flop"}, {"action": "check", "amount": null, "seat": 2, "street": "flop"}, {"action": "raise", "amount": 60, "seat": 0, "street": "flop"}, {"action": "call", "amount": null, "seat": 1, "street": "flop"}, {"action": "raise", "amount": 120, "seat": 2, "street": "flop"}, {"action": "call", "amount": null, "seat": 0, "street": "flop"}, {"action": "call", "amount": null, "seat": 1, "street": "flop"}, {"action": "check", "amount": null, "seat": 1, "street": "turn"}, {"action": "raise", "amount": 302, "seat": 2, "street": "turn"}, {"action": "fold", "amount": null, "seat": 0, "street": "turn"}, {"action": "fold", "amount": null, "seat": 1, "street": "turn"}], "final_stacks": {"0": 4930, "1": 1860, "2": 2837, "4": 1011, "5": 2948}, "hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 120, "outcome_kind": "win", "payouts": [{"amount": 420, "seat": 2}], "pot": 280, "pot_kind": "transferable", "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10007, "total_pot": 420, "transferable_pot": 280, "ts": "2026-10-13T05:46:18.350873+00:00", "type": "hand_result", "winners": [{"amount": 280, "hand_description": null, "name": "player_8", "seat": 2, "stack": 2837}]}} +{"dir": "in", "msg": {"hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 122, "name": "player_8", "reason": "left", "seat": 2, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10009, "ts": "2026-10-13T05:46:18.394323+00:00", "type": "player_left"}} +{"dir": "in", "msg": {"avatar": null, "avatar_url": null, "hand_id": "88344e89-05f5-4df8-b195-8aac88f2c08e", "hand_seq": 125, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2000, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10012, "ts": "2026-10-13T05:46:19.057956+00:00", "type": "player_joined"}} +{"dir": "in", "msg": {"blinds": {"big_blind": 20, "small_blind": 10}, "dealer_seat": 1, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 4, "seat": 3, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10016, "ts": "2026-10-13T05:46:19.088391+00:00", "type": "hand_start"}} +{"dir": "in", "msg": {"cards": ["7s", "7c"], "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 9, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10021, "ts": "2026-10-13T05:46:19.095713+00:00", "type": "hole_cards"}} +{"dir": "in", "msg": {"actor_seat": 4, "big_blind": 20, "board": [], "dealer_seat": 1, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 10, "hero": {"hole_cards": ["7s", "7c"], "seat": 3}, "pot": 30, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4930, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1980, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1011, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:27141a30a717d2f3f54ba9cee041ff9d452f684fe37d3b57ff23dd41ebb5b0ab", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10022, "ts": "2026-10-13T05:46:19.095908+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "raise", "action_id": "0bac6ec4-9efa-4d74-a3f0-4b6029eead26", "amount": 56, "amount_mode": "to_total", "contribution_delta": 56, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 24, "name": "player_4", "player_stack_after": 955, "player_stack_before": 1011, "pot": 86, "pot_after": 86, "pot_before": 30, "reason": null, "seat": 4, "stack": 955, "stack_after": 955, "stack_before": 1011, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10036, "to_call_before": 20, "ts": "2026-10-13T05:46:22.105917+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 5, "big_blind": 20, "board": [], "dealer_seat": 1, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 25, "hero": {"hole_cards": ["7s", "7c"], "seat": 3}, "pot": 86, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4930, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1980, "status": "active"}, {"bet": 56, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 955, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:b08b103bdffe4310cd7e66d0fbc5dc5bf12ec8221db0fc5065d9e5cf10dbb525", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10037, "ts": "2026-10-13T05:46:22.107380+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "cd8473dc-1c6b-48b8-bad6-e7fd83d08e55", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 30, "name": "player_2", "player_stack_after": 2948, "player_stack_before": 2948, "pot": 86, "pot_after": 86, "pot_before": 86, "reason": null, "seat": 5, "stack": 2948, "stack_after": 2948, "stack_before": 2948, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10042, "to_call_before": 56, "ts": "2026-10-13T05:46:25.370917+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": [], "dealer_seat": 1, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 31, "hero": {"hole_cards": ["7s", "7c"], "seat": 3}, "pot": 86, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4930, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1980, "status": "active"}, {"bet": 56, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 955, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:ff46777693d894cded394326d08566a429573f2a0c0134a162bdbd356f330dcd", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10043, "ts": "2026-10-13T05:46:25.371828+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "call", "action_id": "d70d7911-bef9-42d2-a037-87cd971db466", "amount": null, "amount_mode": "incremental", "contribution_delta": 56, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 36, "name": "player_1", "player_stack_after": 4874, "player_stack_before": 4930, "pot": 142, "pot_after": 142, "pot_before": 86, "reason": null, "seat": 0, "stack": 4874, "stack_after": 4874, "stack_before": 4930, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10048, "to_call_before": 56, "ts": "2026-10-13T05:46:28.674036+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 1, "big_blind": 20, "board": [], "dealer_seat": 1, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 37, "hero": {"hole_cards": ["7s", "7c"], "seat": 3}, "pot": 142, "seats": [{"bet": 56, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4874, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1980, "status": "active"}, {"bet": 56, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 955, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:b4a97c51d429c717e7eb0f689dfa53b526ee2fd70080efae5b34d0f41c3ef7c0", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10049, "ts": "2026-10-13T05:46:28.675842+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "6db42ed5-b01d-4f70-a185-dd7ee5020966", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 42, "name": "player_5", "player_stack_after": 1860, "player_stack_before": 1860, "pot": 142, "pot_after": 142, "pot_before": 142, "reason": null, "seat": 1, "stack": 1860, "stack_after": 1860, "stack_before": 1860, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10054, "to_call_before": 56, "ts": "2026-10-13T05:46:31.956034+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 2, "big_blind": 20, "board": [], "dealer_seat": 1, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 43, "hero": {"hole_cards": ["7s", "7c"], "seat": 3}, "pot": 142, "seats": [{"bet": 56, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4874, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1980, "status": "active"}, {"bet": 56, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 955, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:2b74b1dcc060d8e028d62532ff349a511b77f39bb79ecefe7fc11eb70f615f88", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10055, "ts": "2026-10-13T05:46:31.956749+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "oc-b19008fb9c3a-50", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 48, "name": "player_3", "player_stack_after": 1990, "player_stack_before": 1990, "pot": 142, "pot_after": 142, "pot_before": 142, "reason": null, "seat": 2, "stack": 1990, "stack_after": 1990, "stack_before": 1990, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10060, "to_call_before": 46, "ts": "2026-10-13T05:46:35.196374+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": [], "dealer_seat": 1, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 49, "hero": {"hole_cards": ["7s", "7c"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 36}, {"action": "raise", "max": 2000, "min": 92}, {"action": "all_in", "amount": 2000}]}, "max_raise_to": 2000, "min_raise_to": 92, "pot": 142, "seats": [{"bet": 56, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4874, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 10, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1980, "status": "active"}, {"bet": 56, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 955, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:a544f38c54f81fd8c71b6dd321419781bce959467114695f37139314a20b9cf7", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10061, "to_call": 36, "ts": "2026-10-13T05:46:35.197092+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"community_cards": [], "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 50, "max_raise": 2000, "min_raise": 92, "players": [{"avatar_url": null, "is_pro": false, "name": "player_1", "public_profile_slug": null, "seat": 0, "stack": 4874}, {"avatar_url": null, "is_pro": false, "name": "player_5", "public_profile_slug": null, "seat": 1, "stack": 1860}, {"avatar_url": null, "is_pro": false, "name": "player_3", "public_profile_slug": null, "seat": 2, "stack": 1990}, {"avatar_url": null, "is_pro": false, "name": "hero_bot", "public_profile_slug": null, "seat": 3, "stack": 1980}, {"avatar_url": null, "is_pro": false, "name": "player_4", "public_profile_slug": null, "seat": 4, "stack": 955}, {"avatar_url": null, "is_pro": false, "name": "player_2", "public_profile_slug": null, "seat": 5, "stack": 2948}], "pot": 142, "seat": 3, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10062, "ts": "2026-10-13T05:46:38.203297+00:00", "turn_token": "21f2ea0d-6a46-474e-b7d8-2059e290dbd9", "type": "your_turn", "valid_actions": [{"action": "fold", "amount": null, "max": null, "min": null}, {"action": "call", "amount": 36, "max": null, "min": null}, {"action": "raise", "amount": null, "max": 2000, "min": 92}, {"action": "all_in", "amount": 2000, "max": null, "min": null}]}} +{"dir": "out", "msg": {"action": "call", "client_action_id": "plu-1-1", "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "turn_token": "21f2ea0d-6a46-474e-b7d8-2059e290dbd9", "type": "action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": [], "dealer_seat": 1, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 51, "hero": {"hole_cards": ["7s", "7c"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 36}, {"action": "raise", "max": 2000, "min": 92}, {"action": "all_in", "amount": 2000}]}, "max_raise_to": 2000, "min_raise_to": 92, "pot": 142, "seats": [{"bet": 56, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4874, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 10, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1980, "status": "active"}, {"bet": 56, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 955, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:a544f38c54f81fd8c71b6dd321419781bce959467114695f37139314a20b9cf7", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10063, "to_call": 36, "ts": "2026-10-13T05:46:38.203658+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"client_action_id": "plu-1-1", "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 53, "status": "accepted", "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10065, "ts": "2026-10-13T05:46:38.359228+00:00", "type": "action_ack"}} +{"dir": "in", "msg": {"action": "call", "action_id": "plu-1-1", "amount": null, "amount_mode": "incremental", "contribution_delta": 36, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 54, "name": "hero_bot", "player_stack_after": 1944, "player_stack_before": 1980, "pot": 178, "pot_after": 178, "pot_before": 142, "reason": null, "seat": 3, "stack": 1944, "stack_after": 1944, "stack_before": 1980, "state_hash": null, "stream": "event", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10066, "to_call_before": 36, "ts": "2026-10-13T05:46:38.362176+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": [], "dealer_seat": 1, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 55, "hero": {"hole_cards": ["7s", "7c"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "check"}, {"action": "raise", "max": 1944, "min": 20}, {"action": "all_in", "amount": 1944}]}, "max_raise_to": 1944, "min_raise_to": 20, "pot": 178, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4874, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1944, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 955, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:86273efc5086a1d5635ec673a40c6ccf3d9c80e46bc14c808686c9408eaa037a", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10067, "ts": "2026-10-13T05:46:38.362874+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"cards": ["5s", "3s", "3h"], "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 56, "state_hash": null, "stream": "event", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10068, "ts": "2026-10-13T05:46:41.364848+00:00", "type": "community_cards"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": ["5s", "3s", "3h"], "dealer_seat": 1, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 57, "hero": {"hole_cards": ["7s", "7c"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "check"}, {"action": "raise", "max": 1944, "min": 20}, {"action": "all_in", "amount": 1944}]}, "max_raise_to": 1944, "min_raise_to": 20, "pot": 178, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4874, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1944, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 955, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:a284193a67ba4ae028a48b11f5ffa2e02522bfec9140bfdd1f3c350662c16884", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10069, "ts": "2026-10-13T05:46:41.365853+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"community_cards": ["5s", "3s", "3h"], "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 58, "max_raise": 1944, "min_raise": 20, "players": [{"avatar_url": null, "is_pro": false, "name": "player_1", "public_profile_slug": null, "seat": 0, "stack": 4874}, {"avatar_url": null, "is_pro": false, "name": "player_5", "public_profile_slug": null, "seat": 1, "stack": 1860}, {"avatar_url": null, "is_pro": false, "name": "player_3", "public_profile_slug": null, "seat": 2, "stack": 1990}, {"avatar_url": null, "is_pro": false, "name": "hero_bot", "public_profile_slug": null, "seat": 3, "stack": 1944}, {"avatar_url": null, "is_pro": false, "name": "player_4", "public_profile_slug": null, "seat": 4, "stack": 955}, {"avatar_url": null, "is_pro": false, "name": "player_2", "public_profile_slug": null, "seat": 5, "stack": 2948}], "pot": 178, "seat": 3, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10070, "ts": "2026-10-13T05:46:41.369088+00:00", "turn_token": "a4f70380-530a-40f3-bf55-e1051e90f8fe", "type": "your_turn", "valid_actions": [{"action": "fold", "amount": null, "max": null, "min": null}, {"action": "check", "amount": null, "max": null, "min": null}, {"action": "raise", "amount": null, "max": 1944, "min": 20}, {"action": "all_in", "amount": 1944, "max": null, "min": null}]}} +{"dir": "out", "msg": {"action": "raise", "amount": 117, "client_action_id": "plu-1-2", "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "turn_token": "a4f70380-530a-40f3-bf55-e1051e90f8fe", "type": "action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": ["5s", "3s", "3h"], "dealer_seat": 1, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 59, "hero": {"hole_cards": ["7s", "7c"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "check"}, {"action": "raise", "max": 1944, "min": 20}, {"action": "all_in", "amount": 1944}]}, "max_raise_to": 1944, "min_raise_to": 20, "pot": 178, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4874, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1944, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 955, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:a284193a67ba4ae028a48b11f5ffa2e02522bfec9140bfdd1f3c350662c16884", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10071, "ts": "2026-10-13T05:46:41.369426+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"client_action_id": "plu-1-2", "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 61, "status": "accepted", "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10073, "ts": "2026-10-13T05:46:41.524221+00:00", "type": "action_ack"}} +{"dir": "in", "msg": {"action": "raise", "action_id": "plu-1-2", "amount": 117, "amount_mode": "to_total", "contribution_delta": 117, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 62, "name": "hero_bot", "player_stack_after": 1827, "player_stack_before": 1944, "pot": 295, "pot_after": 295, "pot_before": 178, "reason": null, "seat": 3, "stack": 1827, "stack_after": 1827, "stack_before": 1944, "state_hash": null, "stream": "event", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10074, "to_call_before": null, "ts": "2026-10-13T05:46:41.527809+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 4, "big_blind": 20, "board": ["5s", "3s", "3h"], "dealer_seat": 1, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 63, "hero": {"hole_cards": ["7s", "7c"], "seat": 3}, "pot": 295, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4874, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 117, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1827, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 955, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:b5301c0304dd2149b1b088792eaabe723532a30057fe1f41c048127d958d2208", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10075, "ts": "2026-10-13T05:46:41.528867+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "call", "action_id": "488e7f36-98ba-4797-843a-2e6fa2bbed5d", "amount": null, "amount_mode": "incremental", "contribution_delta": 117, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 68, "name": "player_4", "player_stack_after": 838, "player_stack_before": 955, "pot": 412, "pot_after": 412, "pot_before": 295, "reason": null, "seat": 4, "stack": 838, "stack_after": 838, "stack_before": 955, "state_hash": null, "stream": "event", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10080, "to_call_before": 117, "ts": "2026-10-13T05:46:44.544331+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": ["5s", "3s", "3h"], "dealer_seat": 1, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 69, "hero": {"hole_cards": ["7s", "7c"], "seat": 3}, "pot": 412, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4874, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 117, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1827, "status": "active"}, {"bet": 117, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 838, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:41f5bce9e95486c736adedc43018d5cf543b07e5625655cf5fba0f28e61462fe", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10081, "ts": "2026-10-13T05:46:44.545139+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "call", "action_id": "7aa17ec1-96ba-4980-b385-f59b3a8d6d9f", "amount": null, "amount_mode": "incremental", "contribution_delta": 117, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 74, "name": "player_1", "player_stack_after": 4757, "player_stack_before": 4874, "pot": 529, "pot_after": 529, "pot_before": 412, "reason": null, "seat": 0, "stack": 4757, "stack_after": 4757, "stack_before": 4874, "state_hash": null, "stream": "event", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10086, "to_call_before": 117, "ts": "2026-10-13T05:46:47.866409+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": ["5s", "3s", "3h"], "dealer_seat": 1, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 75, "hero": {"hole_cards": ["7s", "7c"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "check"}, {"action": "raise", "max": 1827, "min": 20}, {"action": "all_in", "amount": 1827}]}, "max_raise_to": 1827, "min_raise_to": 20, "pot": 529, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4757, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1827, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 838, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:fbfbd3262a3646af9288b238db6616c2b04b0a11e3f9c02956a6ff7975a9eb15", "stream": "state", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10087, "ts": "2026-10-13T05:46:47.867715+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"cards": ["5s", "3s", "3h", "As"], "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 76, "state_hash": null, "stream": "event", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10088, "ts": "2026-10-13T05:46:50.873406+00:00", "type": "community_cards"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": ["5s", "3s", "3h", "As"], "dealer_seat": 1, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 77, "hero": {"hole_cards": ["7s", "7c"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "check"}, {"action": "raise", "max": 1827, "min": 20}, {"action": "all_in", "amount": 1827}]}, "max_raise_to": 1827, "min_raise_to": 20, "pot": 529, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4757, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1827, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 838, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:5dce8119befaca88c91aa51da182bbfb7696bed6d7ff3f2fd5228a8540480a81", "stream": "state", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10089, "ts": "2026-10-13T05:46:50.874590+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"community_cards": ["5s", "3s", "3h", "As"], "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 78, "max_raise": 1827, "min_raise": 20, "players": [{"avatar_url": null, "is_pro": false, "name": "player_1", "public_profile_slug": null, "seat": 0, "stack": 4757}, {"avatar_url": null, "is_pro": false, "name": "player_5", "public_profile_slug": null, "seat": 1, "stack": 1860}, {"avatar_url": null, "is_pro": false, "name": "player_3", "public_profile_slug": null, "seat": 2, "stack": 1990}, {"avatar_url": null, "is_pro": false, "name": "hero_bot", "public_profile_slug": null, "seat": 3, "stack": 1827}, {"avatar_url": null, "is_pro": false, "name": "player_4", "public_profile_slug": null, "seat": 4, "stack": 838}, {"avatar_url": null, "is_pro": false, "name": "player_2", "public_profile_slug": null, "seat": 5, "stack": 2948}], "pot": 529, "seat": 3, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10090, "ts": "2026-10-13T05:46:50.879601+00:00", "turn_token": "b14937b0-1142-419f-a94b-6f4eeedfc2d6", "type": "your_turn", "valid_actions": [{"action": "fold", "amount": null, "max": null, "min": null}, {"action": "check", "amount": null, "max": null, "min": null}, {"action": "raise", "amount": null, "max": 1827, "min": 20}, {"action": "all_in", "amount": 1827, "max": null, "min": null}]}} +{"dir": "out", "msg": {"action": "raise", "amount": 349, "client_action_id": "plu-1-3", "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "turn_token": "b14937b0-1142-419f-a94b-6f4eeedfc2d6", "type": "action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": ["5s", "3s", "3h", "As"], "dealer_seat": 1, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 79, "hero": {"hole_cards": ["7s", "7c"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "check"}, {"action": "raise", "max": 1827, "min": 20}, {"action": "all_in", "amount": 1827}]}, "max_raise_to": 1827, "min_raise_to": 20, "pot": 529, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4757, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1827, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 838, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:5dce8119befaca88c91aa51da182bbfb7696bed6d7ff3f2fd5228a8540480a81", "stream": "state", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10091, "ts": "2026-10-13T05:46:50.880187+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"client_action_id": "plu-1-3", "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 81, "status": "accepted", "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10093, "ts": "2026-10-13T05:46:51.038399+00:00", "type": "action_ack"}} +{"dir": "in", "msg": {"action": "raise", "action_id": "plu-1-3", "amount": 349, "amount_mode": "to_total", "contribution_delta": 349, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 82, "name": "hero_bot", "player_stack_after": 1478, "player_stack_before": 1827, "pot": 878, "pot_after": 878, "pot_before": 529, "reason": null, "seat": 3, "stack": 1478, "stack_after": 1478, "stack_before": 1827, "state_hash": null, "stream": "event", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10094, "to_call_before": null, "ts": "2026-10-13T05:46:51.040748+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 4, "big_blind": 20, "board": ["5s", "3s", "3h", "As"], "dealer_seat": 1, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 83, "hero": {"hole_cards": ["7s", "7c"], "seat": 3}, "pot": 878, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4757, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 349, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1478, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 838, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:49cf03162eba00533b50a7cea7d7165556aca35b1c73abf08fe0acbc311e1fc1", "stream": "state", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10095, "ts": "2026-10-13T05:46:51.041573+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "raise", "action_id": "bc836f1c-2feb-468f-bb11-67b549f2ef53", "amount": 698, "amount_mode": "to_total", "contribution_delta": 698, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 88, "name": "player_4", "player_stack_after": 140, "player_stack_before": 838, "pot": 1576, "pot_after": 1576, "pot_before": 878, "reason": null, "seat": 4, "stack": 140, "stack_after": 140, "stack_before": 838, "state_hash": null, "stream": "event", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10100, "to_call_before": 349, "ts": "2026-10-13T05:46:54.050711+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": ["5s", "3s", "3h", "As"], "dealer_seat": 1, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 89, "hero": {"hole_cards": ["7s", "7c"], "seat": 3}, "pot": 1576, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4757, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 349, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1478, "status": "active"}, {"bet": 698, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 140, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:c0825a9c3f13e05c8ab332d16266b466ba07b90e2396f901f5b1ee8e40795f27", "stream": "state", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10101, "ts": "2026-10-13T05:46:54.051818+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "call", "action_id": "934a5879-4633-4486-8c57-b559e877df50", "amount": null, "amount_mode": "incremental", "contribution_delta": 698, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 94, "name": "player_1", "player_stack_after": 4059, "player_stack_before": 4757, "pot": 2274, "pot_after": 2274, "pot_before": 1576, "reason": null, "seat": 0, "stack": 4059, "stack_after": 4059, "stack_before": 4757, "state_hash": null, "stream": "event", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10106, "to_call_before": 698, "ts": "2026-10-13T05:46:57.308941+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": ["5s", "3s", "3h", "As"], "dealer_seat": 1, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 95, "hero": {"hole_cards": ["7s", "7c"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 349}, {"action": "raise", "max": 1827, "min": 1047}, {"action": "all_in", "amount": 1827}]}, "max_raise_to": 1827, "min_raise_to": 1047, "pot": 2274, "seats": [{"bet": 698, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4059, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 349, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1478, "status": "active"}, {"bet": 698, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 140, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:30b85cd075f555a9ec43b5c119f80cdc28dff3f5e0acf36f4c5c25f5644dfe32", "stream": "state", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10107, "to_call": 349, "ts": "2026-10-13T05:46:57.309798+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"community_cards": ["5s", "3s", "3h", "As"], "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 96, "max_raise": 1827, "min_raise": 1047, "players": [{"avatar_url": null, "is_pro": false, "name": "player_1", "public_profile_slug": null, "seat": 0, "stack": 4059}, {"avatar_url": null, "is_pro": false, "name": "player_5", "public_profile_slug": null, "seat": 1, "stack": 1860}, {"avatar_url": null, "is_pro": false, "name": "player_3", "public_profile_slug": null, "seat": 2, "stack": 1990}, {"avatar_url": null, "is_pro": false, "name": "hero_bot", "public_profile_slug": null, "seat": 3, "stack": 1478}, {"avatar_url": null, "is_pro": false, "name": "player_4", "public_profile_slug": null, "seat": 4, "stack": 140}, {"avatar_url": null, "is_pro": false, "name": "player_2", "public_profile_slug": null, "seat": 5, "stack": 2948}], "pot": 2274, "seat": 3, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10108, "ts": "2026-10-13T05:47:00.313273+00:00", "turn_token": "559f9958-37f5-49e7-821c-c989fb554508", "type": "your_turn", "valid_actions": [{"action": "fold", "amount": null, "max": null, "min": null}, {"action": "call", "amount": 349, "max": null, "min": null}, {"action": "raise", "amount": null, "max": 1827, "min": 1047}, {"action": "all_in", "amount": 1827, "max": null, "min": null}]}} +{"dir": "out", "msg": {"action": "call", "client_action_id": "plu-1-4", "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "turn_token": "559f9958-37f5-49e7-821c-c989fb554508", "type": "action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": ["5s", "3s", "3h", "As"], "dealer_seat": 1, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 97, "hero": {"hole_cards": ["7s", "7c"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 349}, {"action": "raise", "max": 1827, "min": 1047}, {"action": "all_in", "amount": 1827}]}, "max_raise_to": 1827, "min_raise_to": 1047, "pot": 2274, "seats": [{"bet": 698, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4059, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 349, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1478, "status": "active"}, {"bet": 698, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 140, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:30b85cd075f555a9ec43b5c119f80cdc28dff3f5e0acf36f4c5c25f5644dfe32", "stream": "state", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10109, "to_call": 349, "ts": "2026-10-13T05:47:00.313760+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"client_action_id": "plu-1-4", "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 99, "status": "accepted", "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10111, "ts": "2026-10-13T05:47:00.471443+00:00", "type": "action_ack"}} +{"dir": "in", "msg": {"action": "call", "action_id": "plu-1-4", "amount": null, "amount_mode": "incremental", "contribution_delta": 349, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 100, "name": "hero_bot", "player_stack_after": 1129, "player_stack_before": 1478, "pot": 2623, "pot_after": 2623, "pot_before": 2274, "reason": null, "seat": 3, "stack": 1129, "stack_after": 1129, "stack_before": 1478, "state_hash": null, "stream": "event", "street": "river", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10112, "to_call_before": 349, "ts": "2026-10-13T05:47:00.475045+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": ["5s", "3s", "3h", "As"], "dealer_seat": 1, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 101, "hero": {"hole_cards": ["7s", "7c"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "check"}, {"action": "raise", "max": 1129, "min": 20}, {"action": "all_in", "amount": 1129}]}, "max_raise_to": 1129, "min_raise_to": 20, "pot": 2623, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4059, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1129, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 140, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:5b789e6ae4277267070b3567b1cea6e0d017b295cd1d59861c53c1714d172a78", "stream": "state", "street": "river", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10113, "ts": "2026-10-13T05:47:00.475966+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"cards": ["5s", "3s", "3h", "As", "4h"], "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 102, "state_hash": null, "stream": "event", "street": "river", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10114, "ts": "2026-10-13T05:47:03.478823+00:00", "type": "community_cards"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": ["5s", "3s", "3h", "As", "4h"], "dealer_seat": 1, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 103, "hero": {"hole_cards": ["7s", "7c"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "check"}, {"action": "raise", "max": 1129, "min": 20}, {"action": "all_in", "amount": 1129}]}, "max_raise_to": 1129, "min_raise_to": 20, "pot": 2623, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4059, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1129, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 140, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:943344b31c7e54b42ecf21a0a9aa141401ee2f10f17754560bf0ba78cc09139c", "stream": "state", "street": "river", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10115, "ts": "2026-10-13T05:47:03.479808+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"community_cards": ["5s", "3s", "3h", "As", "4h"], "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 104, "max_raise": 1129, "min_raise": 20, "players": [{"avatar_url": null, "is_pro": false, "name": "player_1", "public_profile_slug": null, "seat": 0, "stack": 4059}, {"avatar_url": null, "is_pro": false, "name": "player_5", "public_profile_slug": null, "seat": 1, "stack": 1860}, {"avatar_url": null, "is_pro": false, "name": "player_3", "public_profile_slug": null, "seat": 2, "stack": 1990}, {"avatar_url": null, "is_pro": false, "name": "hero_bot", "public_profile_slug": null, "seat": 3, "stack": 1129}, {"avatar_url": null, "is_pro": false, "name": "player_4", "public_profile_slug": null, "seat": 4, "stack": 140}, {"avatar_url": null, "is_pro": false, "name": "player_2", "public_profile_slug": null, "seat": 5, "stack": 2948}], "pot": 2623, "seat": 3, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10116, "ts": "2026-10-13T05:47:03.482881+00:00", "turn_token": "ab5b2ebc-3e76-4736-bd5d-2a22aa63878a", "type": "your_turn", "valid_actions": [{"action": "fold", "amount": null, "max": null, "min": null}, {"action": "check", "amount": null, "max": null, "min": null}, {"action": "raise", "amount": null, "max": 1129, "min": 20}, {"action": "all_in", "amount": 1129, "max": null, "min": null}]}} +{"dir": "out", "msg": {"action": "check", "client_action_id": "plu-1-5", "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "turn_token": "ab5b2ebc-3e76-4736-bd5d-2a22aa63878a", "type": "action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": ["5s", "3s", "3h", "As", "4h"], "dealer_seat": 1, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 105, "hero": {"hole_cards": ["7s", "7c"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "check"}, {"action": "raise", "max": 1129, "min": 20}, {"action": "all_in", "amount": 1129}]}, "max_raise_to": 1129, "min_raise_to": 20, "pot": 2623, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4059, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1129, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 140, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:943344b31c7e54b42ecf21a0a9aa141401ee2f10f17754560bf0ba78cc09139c", "stream": "state", "street": "river", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10117, "ts": "2026-10-13T05:47:03.483214+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"client_action_id": "plu-1-5", "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 107, "status": "accepted", "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10119, "ts": "2026-10-13T05:47:03.640552+00:00", "type": "action_ack"}} +{"dir": "in", "msg": {"action": "check", "action_id": "plu-1-5", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 108, "name": "hero_bot", "player_stack_after": 1129, "player_stack_before": 1129, "pot": 2623, "pot_after": 2623, "pot_before": 2623, "reason": null, "seat": 3, "stack": 1129, "stack_after": 1129, "stack_before": 1129, "state_hash": null, "stream": "event", "street": "river", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10120, "to_call_before": null, "ts": "2026-10-13T05:47:03.644376+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 4, "big_blind": 20, "board": ["5s", "3s", "3h", "As", "4h"], "dealer_seat": 1, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 109, "hero": {"hole_cards": ["7s", "7c"], "seat": 3}, "pot": 2623, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4059, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1129, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 140, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:487a0d568d38d95cc5d1907ee1fc848b1edf5401da9bb22f64e6b862e1a19aa0", "stream": "state", "street": "river", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10121, "ts": "2026-10-13T05:47:03.645285+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "check", "action_id": "bb6fc745-5ad4-4225-8e83-5711a462e9ac", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 114, "name": "player_4", "player_stack_after": 140, "player_stack_before": 140, "pot": 2623, "pot_after": 2623, "pot_before": 2623, "reason": null, "seat": 4, "stack": 140, "stack_after": 140, "stack_before": 140, "state_hash": null, "stream": "event", "street": "river", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10126, "to_call_before": null, "ts": "2026-10-13T05:47:06.653467+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": ["5s", "3s", "3h", "As", "4h"], "dealer_seat": 1, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 115, "hero": {"hole_cards": ["7s", "7c"], "seat": 3}, "pot": 2623, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 4059, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1129, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 140, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:4d763c775bb581873bd5e8c1df1a43608f0bfcad8ee62688860be1f4d962b44c", "stream": "state", "street": "river", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10127, "ts": "2026-10-13T05:47:06.654451+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "check", "action_id": "8312f2b9-d887-405c-b56f-963347a33f30", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 120, "name": "player_1", "player_stack_after": 4059, "player_stack_before": 4059, "pot": 2623, "pot_after": 2623, "pot_before": 2623, "reason": null, "seat": 0, "stack": 4059, "stack_after": 4059, "stack_before": 4059, "state_hash": null, "stream": "event", "street": "showdown", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10132, "to_call_before": null, "ts": "2026-10-13T05:47:09.934936+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"big_blind": 20, "board": ["5s", "3s", "3h", "As", "4h"], "dealer_seat": 1, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 121, "hero": {"hole_cards": ["7s", "7c"], "seat": 3}, "pot": 0, "seats": [{"bet": 0, "in_hand": false, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6682, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1129, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 140, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "in_hand": false, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:449ee1821245ff68a6704c1d54344f304b870268796ade73cd88619891dc05d3", "stream": "state", "street": "idle", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10133, "ts": "2026-10-13T05:47:09.936424+00:00", "type": "table_state", "waiting_details": {"active_players": 6, "away_players": 0, "connected_players": 6, "disconnected_players": 0, "eligible_players": 6, "min_required": 2, "player_count": 6}, "waiting_reason": "awaiting_hand_start"}} +{"dir": "in", "msg": {"actions": [{"action": "raise", "amount": 56, "seat": 4, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 5, "street": "preflop"}, {"action": "call", "amount": null, "seat": 0, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 1, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 2, "street": "preflop"}, {"action": "call", "amount": null, "seat": 3, "street": "preflop"}, {"action": "raise", "amount": 117, "seat": 3, "street": "flop"}, {"action": "call", "amount": null, "seat": 4, "street": "flop"}, {"action": "call", "amount": null, "seat": 0, "street": "flop"}, {"action": "raise", "amount": 349, "seat": 3, "street": "turn"}, {"action": "raise", "amount": 698, "seat": 4, "street": "turn"}, {"action": "call", "amount": null, "seat": 0, "street": "turn"}, {"action": "call", "amount": null, "seat": 3, "street": "turn"}, {"action": "check", "amount": null, "seat": 3, "street": "river"}, {"action": "check", "amount": null, "seat": 4, "street": "river"}, {"action": "check", "amount": null, "seat": 0, "street": "river"}], "final_stacks": {"0": 6682, "1": 1860, "2": 1990, "3": 1129, "4": 140, "5": 2948}, "hand_id": "5994b2df-9302-42c8-bfd6-1777ccd5fa39", "hand_seq": 122, "outcome_kind": "win", "payouts": [{"amount": 2623, "seat": 0}], "pot": 1752, "pot_kind": "transferable", "shown_cards": {"0": ["Ah", "Jc"], "3": ["7s", "7c"], "4": ["Td", "Kd"]}, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10134, "total_pot": 2623, "transferable_pot": 1752, "ts": "2026-10-13T05:47:10.015807+00:00", "type": "hand_result", "winners": [{"amount": 1752, "hand_description": "Two pair", "name": "player_1", "seat": 0, "stack": 6682}]}} +{"dir": "in", "msg": {"blinds": {"big_blind": 20, "small_blind": 10}, "dealer_seat": 2, "hand_id": "cfab8369-65ce-45d3-856b-8a8542f788a9", "hand_seq": 4, "seat": 3, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10138, "ts": "2026-10-13T05:47:15.075291+00:00", "type": "hand_start"}} +{"dir": "in", "msg": {"cards": ["6s", "Ad"], "hand_id": "cfab8369-65ce-45d3-856b-8a8542f788a9", "hand_seq": 7, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10141, "ts": "2026-10-13T05:47:15.085062+00:00", "type": "hole_cards"}} +{"dir": "in", "msg": {"actor_seat": 5, "big_blind": 20, "board": [], "dealer_seat": 2, "hand_id": "cfab8369-65ce-45d3-856b-8a8542f788a9", "hand_seq": 8, "hero": {"hole_cards": ["6s", "Ad"], "seat": 3}, "pot": 30, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6682, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1119, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 120, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:41441b86d414a5629ff08ca08c09bdb1b1ec5d52d439e6ddad6f81dc1bcb02c4", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10142, "ts": "2026-10-13T05:47:15.085591+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "5b3c5630-ba27-4003-a957-7bd982ff2f49", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "cfab8369-65ce-45d3-856b-8a8542f788a9", "hand_seq": 24, "name": "player_2", "player_stack_after": 2948, "player_stack_before": 2948, "pot": 30, "pot_after": 30, "pot_before": 30, "reason": null, "seat": 5, "stack": 2948, "stack_after": 2948, "stack_before": 2948, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10158, "to_call_before": 20, "ts": "2026-10-13T05:47:18.369100+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": [], "dealer_seat": 2, "hand_id": "cfab8369-65ce-45d3-856b-8a8542f788a9", "hand_seq": 25, "hero": {"hole_cards": ["6s", "Ad"], "seat": 3}, "pot": 30, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6682, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1119, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 120, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:953f78b889b181b3288774d7947d1cf516e84645832c53d128765150191048ea", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10159, "ts": "2026-10-13T05:47:18.369857+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "call", "action_id": "37ca0602-58f0-454d-a25d-6b99a09e8c9c", "amount": null, "amount_mode": "incremental", "contribution_delta": 20, "hand_id": "cfab8369-65ce-45d3-856b-8a8542f788a9", "hand_seq": 30, "name": "player_1", "player_stack_after": 6662, "player_stack_before": 6682, "pot": 50, "pot_after": 50, "pot_before": 30, "reason": null, "seat": 0, "stack": 6662, "stack_after": 6662, "stack_before": 6682, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10164, "to_call_before": 20, "ts": "2026-10-13T05:47:21.643505+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 1, "big_blind": 20, "board": [], "dealer_seat": 2, "hand_id": "cfab8369-65ce-45d3-856b-8a8542f788a9", "hand_seq": 31, "hero": {"hole_cards": ["6s", "Ad"], "seat": 3}, "pot": 50, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6662, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1860, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1119, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 120, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:04447c2c953258d3edadcee8c4335c1fac163bcdff25433609122ed95a015fcf", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10165, "ts": "2026-10-13T05:47:21.644387+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "raise", "action_id": "53c169d6-5524-4105-a222-15da7a406165", "amount": 90, "amount_mode": "to_total", "contribution_delta": 90, "hand_id": "cfab8369-65ce-45d3-856b-8a8542f788a9", "hand_seq": 36, "name": "player_5", "player_stack_after": 1770, "player_stack_before": 1860, "pot": 140, "pot_after": 140, "pot_before": 50, "reason": null, "seat": 1, "stack": 1770, "stack_after": 1770, "stack_before": 1860, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10170, "to_call_before": 20, "ts": "2026-10-13T05:47:24.924901+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 2, "big_blind": 20, "board": [], "dealer_seat": 2, "hand_id": "cfab8369-65ce-45d3-856b-8a8542f788a9", "hand_seq": 37, "hero": {"hole_cards": ["6s", "Ad"], "seat": 3}, "pot": 140, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6662, "status": "active"}, {"bet": 90, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1770, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1119, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 120, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:afef4ac20f397ead083f26a94e187d8a55d5d5a966c2f58ef9fcb2f2f3b65969", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10171, "ts": "2026-10-13T05:47:24.926564+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "oc-62be0de60081-51", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "cfab8369-65ce-45d3-856b-8a8542f788a9", "hand_seq": 42, "name": "player_3", "player_stack_after": 1990, "player_stack_before": 1990, "pot": 140, "pot_after": 140, "pot_before": 140, "reason": null, "seat": 2, "stack": 1990, "stack_after": 1990, "stack_before": 1990, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10176, "to_call_before": 90, "ts": "2026-10-13T05:47:28.027196+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": [], "dealer_seat": 2, "hand_id": "cfab8369-65ce-45d3-856b-8a8542f788a9", "hand_seq": 43, "hero": {"hole_cards": ["6s", "Ad"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 80}, {"action": "raise", "max": 1129, "min": 160}, {"action": "all_in", "amount": 1129}]}, "max_raise_to": 1129, "min_raise_to": 160, "pot": 140, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6662, "status": "active"}, {"bet": 90, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1770, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1119, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 120, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:0d5f0e8af69431716339e690543f4241cc300bcccf49b7a31080d986b0fafbb1", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10177, "to_call": 80, "ts": "2026-10-13T05:47:28.028205+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"community_cards": [], "hand_id": "cfab8369-65ce-45d3-856b-8a8542f788a9", "hand_seq": 44, "max_raise": 1129, "min_raise": 160, "players": [{"avatar_url": null, "is_pro": false, "name": "player_1", "public_profile_slug": null, "seat": 0, "stack": 6662}, {"avatar_url": null, "is_pro": false, "name": "player_5", "public_profile_slug": null, "seat": 1, "stack": 1770}, {"avatar_url": null, "is_pro": false, "name": "player_3", "public_profile_slug": null, "seat": 2, "stack": 1990}, {"avatar_url": null, "is_pro": false, "name": "hero_bot", "public_profile_slug": null, "seat": 3, "stack": 1119}, {"avatar_url": null, "is_pro": false, "name": "player_4", "public_profile_slug": null, "seat": 4, "stack": 120}, {"avatar_url": null, "is_pro": false, "name": "player_2", "public_profile_slug": null, "seat": 5, "stack": 2948}], "pot": 140, "seat": 3, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10178, "ts": "2026-10-13T05:47:31.031827+00:00", "turn_token": "dd7cee0c-4940-46fe-84d0-13b81bdbe077", "type": "your_turn", "valid_actions": [{"action": "fold", "amount": null, "max": null, "min": null}, {"action": "call", "amount": 80, "max": null, "min": null}, {"action": "raise", "amount": null, "max": 1129, "min": 160}, {"action": "all_in", "amount": 1129, "max": null, "min": null}]}} +{"dir": "out", "msg": {"action": "fold", "client_action_id": "plu-2-6", "hand_id": "cfab8369-65ce-45d3-856b-8a8542f788a9", "turn_token": "dd7cee0c-4940-46fe-84d0-13b81bdbe077", "type": "action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": [], "dealer_seat": 2, "hand_id": "cfab8369-65ce-45d3-856b-8a8542f788a9", "hand_seq": 45, "hero": {"hole_cards": ["6s", "Ad"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 80}, {"action": "raise", "max": 1129, "min": 160}, {"action": "all_in", "amount": 1129}]}, "max_raise_to": 1129, "min_raise_to": 160, "pot": 140, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6662, "status": "active"}, {"bet": 90, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1770, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1119, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 120, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:0d5f0e8af69431716339e690543f4241cc300bcccf49b7a31080d986b0fafbb1", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10179, "to_call": 80, "ts": "2026-10-13T05:47:31.032633+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"client_action_id": "plu-2-6", "hand_id": "cfab8369-65ce-45d3-856b-8a8542f788a9", "hand_seq": 47, "status": "accepted", "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10181, "ts": "2026-10-13T05:47:31.187880+00:00", "type": "action_ack"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "plu-2-6", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "cfab8369-65ce-45d3-856b-8a8542f788a9", "hand_seq": 48, "name": "hero_bot", "player_stack_after": 1119, "player_stack_before": 1119, "pot": 140, "pot_after": 140, "pot_before": 140, "reason": null, "seat": 3, "stack": 1119, "stack_after": 1119, "stack_before": 1119, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10182, "to_call_before": 80, "ts": "2026-10-13T05:47:31.192706+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 4, "big_blind": 20, "board": [], "dealer_seat": 2, "hand_id": "cfab8369-65ce-45d3-856b-8a8542f788a9", "hand_seq": 49, "hero": {"hole_cards": ["6s", "Ad"], "seat": 3}, "pot": 140, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6662, "status": "active"}, {"bet": 90, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1770, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 10, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1119, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 120, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:0fb9acb9afbbe2d9cc1baf23d59892e6d7f9f5486208e5c0342587082af1327d", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10183, "ts": "2026-10-13T05:47:31.194100+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "9bb18469-edd6-438e-bff8-ea5953e008e8", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "cfab8369-65ce-45d3-856b-8a8542f788a9", "hand_seq": 54, "name": "player_4", "player_stack_after": 120, "player_stack_before": 120, "pot": 140, "pot_after": 140, "pot_before": 140, "reason": null, "seat": 4, "stack": 120, "stack_after": 120, "stack_before": 120, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10188, "to_call_before": 70, "ts": "2026-10-13T05:47:34.653639+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": [], "dealer_seat": 2, "hand_id": "cfab8369-65ce-45d3-856b-8a8542f788a9", "hand_seq": 55, "hero": {"hole_cards": ["6s", "Ad"], "seat": 3}, "pot": 140, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6662, "status": "active"}, {"bet": 90, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1770, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 10, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1119, "status": "active"}, {"bet": 20, "folded": true, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 120, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:d9ec3ca97b4318d8d19ac6df35470bbafcb2da4807954ffcf6d0d2fc031c49c6", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10189, "ts": "2026-10-13T05:47:34.654291+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "call", "action_id": "08a5c915-5c54-41ef-b301-0fe5a27b6838", "amount": null, "amount_mode": "incremental", "contribution_delta": 70, "hand_id": "cfab8369-65ce-45d3-856b-8a8542f788a9", "hand_seq": 60, "name": "player_1", "player_stack_after": 6592, "player_stack_before": 6662, "pot": 210, "pot_after": 210, "pot_before": 140, "reason": null, "seat": 0, "stack": 6592, "stack_after": 6592, "stack_before": 6662, "state_hash": null, "stream": "event", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10194, "to_call_before": 70, "ts": "2026-10-13T05:47:38.186679+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": [], "dealer_seat": 2, "hand_id": "cfab8369-65ce-45d3-856b-8a8542f788a9", "hand_seq": 61, "hero": {"hole_cards": ["6s", "Ad"], "seat": 3}, "pot": 210, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6592, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1770, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1119, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 120, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:d78cfc086efec45974c989c0911f72f3dffeebef6dd44b5ca5e57fca90debeb0", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10195, "ts": "2026-10-13T05:47:38.187757+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"cards": ["9h", "8c", "Qc"], "hand_id": "cfab8369-65ce-45d3-856b-8a8542f788a9", "hand_seq": 62, "state_hash": null, "stream": "event", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10196, "ts": "2026-10-13T05:47:41.191627+00:00", "type": "community_cards"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": ["9h", "8c", "Qc"], "dealer_seat": 2, "hand_id": "cfab8369-65ce-45d3-856b-8a8542f788a9", "hand_seq": 63, "hero": {"hole_cards": ["6s", "Ad"], "seat": 3}, "pot": 210, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6592, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1770, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1119, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 120, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:92a7c10b80a5396b4b5415c87f3b1a1fd03fb3bf60da243d5d016b2a67b1ca52", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10197, "ts": "2026-10-13T05:47:41.192365+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "raise", "action_id": "8a7454fe-f360-459a-919b-ed118bfc506b", "amount": 210, "amount_mode": "to_total", "contribution_delta": 210, "hand_id": "cfab8369-65ce-45d3-856b-8a8542f788a9", "hand_seq": 68, "name": "player_1", "player_stack_after": 6382, "player_stack_before": 6592, "pot": 420, "pot_after": 420, "pot_before": 210, "reason": null, "seat": 0, "stack": 6382, "stack_after": 6382, "stack_before": 6592, "state_hash": null, "stream": "event", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10202, "to_call_before": null, "ts": "2026-10-13T05:47:41.534981+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 1, "big_blind": 20, "board": ["9h", "8c", "Qc"], "dealer_seat": 2, "hand_id": "cfab8369-65ce-45d3-856b-8a8542f788a9", "hand_seq": 69, "hero": {"hole_cards": ["6s", "Ad"], "seat": 3}, "pot": 420, "seats": [{"bet": 210, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6382, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1770, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1119, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 120, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:e8acc028b00f7ef0ae12674aa6663581bb6d2cdf8f70a834454e27473e118fe7", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10203, "ts": "2026-10-13T05:47:41.535919+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "e83176a9-e263-411c-8eec-b68caded5a99", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "cfab8369-65ce-45d3-856b-8a8542f788a9", "hand_seq": 74, "name": "player_5", "player_stack_after": 1770, "player_stack_before": 1770, "pot": 420, "pot_after": 420, "pot_before": 420, "reason": null, "seat": 1, "stack": 1770, "stack_after": 1770, "stack_before": 1770, "state_hash": null, "stream": "event", "street": "showdown", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10208, "to_call_before": 210, "ts": "2026-10-13T05:47:44.817332+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"big_blind": 20, "board": ["9h", "8c", "Qc"], "dealer_seat": 2, "hand_id": "cfab8369-65ce-45d3-856b-8a8542f788a9", "hand_seq": 75, "hero": {"hole_cards": ["6s", "Ad"], "seat": 3}, "pot": 0, "seats": [{"bet": 0, "in_hand": false, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6802, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1770, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1119, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 120, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "in_hand": false, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2948, "status": "active"}], "small_blind": 10, "state_hash": "sha256:36ea89b7c76d7068d31326b08a9f76177d3d8fd056d610d3544fdda6377a8be1", "stream": "state", "street": "idle", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10209, "ts": "2026-10-13T05:47:44.818140+00:00", "type": "table_state", "waiting_details": {"active_players": 6, "away_players": 0, "connected_players": 6, "disconnected_players": 0, "eligible_players": 6, "min_required": 2, "player_count": 6}, "waiting_reason": "awaiting_hand_start"}} +{"dir": "in", "msg": {"actions": [{"action": "fold", "amount": null, "seat": 5, "street": "preflop"}, {"action": "call", "amount": null, "seat": 0, "street": "preflop"}, {"action": "raise", "amount": 90, "seat": 1, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 2, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 3, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 4, "street": "preflop"}, {"action": "call", "amount": null, "seat": 0, "street": "preflop"}, {"action": "raise", "amount": 210, "seat": 0, "street": "flop"}, {"action": "fold", "amount": null, "seat": 1, "street": "flop"}], "final_stacks": {"0": 6802, "1": 1770, "2": 1990, "3": 1119, "4": 120, "5": 2948}, "hand_id": "cfab8369-65ce-45d3-856b-8a8542f788a9", "hand_seq": 76, "outcome_kind": "win", "payouts": [{"amount": 210, "seat": 0}], "pot": 120, "pot_kind": "transferable", "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10210, "total_pot": 210, "transferable_pot": 120, "ts": "2026-10-13T05:47:44.889680+00:00", "type": "hand_result", "winners": [{"amount": 120, "hand_description": null, "name": "player_1", "seat": 0, "stack": 6802}]}} +{"dir": "in", "msg": {"blinds": {"big_blind": 20, "small_blind": 10}, "dealer_seat": 3, "hand_id": "dca7c37f-bd76-4794-ba9a-cc63f7b22375", "hand_seq": 4, "seat": 3, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10214, "ts": "2026-10-13T05:47:49.922264+00:00", "type": "hand_start"}} +{"dir": "in", "msg": {"cards": ["Kc", "Qc"], "hand_id": "dca7c37f-bd76-4794-ba9a-cc63f7b22375", "hand_seq": 17, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10227, "ts": "2026-10-13T05:47:49.932750+00:00", "type": "hole_cards"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": [], "dealer_seat": 3, "hand_id": "dca7c37f-bd76-4794-ba9a-cc63f7b22375", "hand_seq": 18, "hero": {"hole_cards": ["Kc", "Qc"], "seat": 3}, "pot": 30, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6802, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1770, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1119, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 110, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2928, "status": "active"}], "small_blind": 10, "state_hash": "sha256:f6cb23081b49e54dd02de95c6e84f262d75b3ec73d0bf7c0a3f62a9daef08f17", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10228, "ts": "2026-10-13T05:47:49.932900+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "call", "action_id": "921180ce-c809-4f1f-b8e7-c85c84b89e58", "amount": null, "amount_mode": "incremental", "contribution_delta": 20, "hand_id": "dca7c37f-bd76-4794-ba9a-cc63f7b22375", "hand_seq": 24, "name": "player_1", "player_stack_after": 6782, "player_stack_before": 6802, "pot": 50, "pot_after": 50, "pot_before": 30, "reason": null, "seat": 0, "stack": 6782, "stack_after": 6782, "stack_before": 6802, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10234, "to_call_before": 20, "ts": "2026-10-13T05:47:53.324644+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 1, "big_blind": 20, "board": [], "dealer_seat": 3, "hand_id": "dca7c37f-bd76-4794-ba9a-cc63f7b22375", "hand_seq": 25, "hero": {"hole_cards": ["Kc", "Qc"], "seat": 3}, "pot": 50, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6782, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1770, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1119, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 110, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2928, "status": "active"}], "small_blind": 10, "state_hash": "sha256:4c80bb8f44a0dbb68d607ae585c11247e8345d7ab029b93975172d1fbf18d3a3", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10235, "ts": "2026-10-13T05:47:53.325560+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "raise", "action_id": "1bac0a81-0ac0-4a0f-8140-ff43126ac4da", "amount": 90, "amount_mode": "to_total", "contribution_delta": 90, "hand_id": "dca7c37f-bd76-4794-ba9a-cc63f7b22375", "hand_seq": 30, "name": "player_5", "player_stack_after": 1680, "player_stack_before": 1770, "pot": 140, "pot_after": 140, "pot_before": 50, "reason": null, "seat": 1, "stack": 1680, "stack_after": 1680, "stack_before": 1770, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10240, "to_call_before": 20, "ts": "2026-10-13T05:47:56.612730+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 2, "big_blind": 20, "board": [], "dealer_seat": 3, "hand_id": "dca7c37f-bd76-4794-ba9a-cc63f7b22375", "hand_seq": 31, "hero": {"hole_cards": ["Kc", "Qc"], "seat": 3}, "pot": 140, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6782, "status": "active"}, {"bet": 90, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1680, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1119, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 110, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2928, "status": "active"}], "small_blind": 10, "state_hash": "sha256:69cc6fff684e3eedd94426631389eea25a3af044355f1e65d1c6ba292f02e0d1", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10241, "ts": "2026-10-13T05:47:56.613603+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "oc-32227395d7c8-52", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "dca7c37f-bd76-4794-ba9a-cc63f7b22375", "hand_seq": 36, "name": "player_3", "player_stack_after": 1990, "player_stack_before": 1990, "pot": 140, "pot_after": 140, "pot_before": 140, "reason": null, "seat": 2, "stack": 1990, "stack_after": 1990, "stack_before": 1990, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10246, "to_call_before": 90, "ts": "2026-10-13T05:47:59.707745+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": [], "dealer_seat": 3, "hand_id": "dca7c37f-bd76-4794-ba9a-cc63f7b22375", "hand_seq": 37, "hero": {"hole_cards": ["Kc", "Qc"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 90}, {"action": "raise", "max": 1119, "min": 160}, {"action": "all_in", "amount": 1119}]}, "max_raise_to": 1119, "min_raise_to": 160, "pot": 140, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6782, "status": "active"}, {"bet": 90, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1680, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1119, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 110, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2928, "status": "active"}], "small_blind": 10, "state_hash": "sha256:e7a54097074c71e3e2a044929b8b1704901d1888af9717743244c6f7800c6d2a", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10247, "to_call": 90, "ts": "2026-10-13T05:47:59.708727+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"community_cards": [], "hand_id": "dca7c37f-bd76-4794-ba9a-cc63f7b22375", "hand_seq": 38, "max_raise": 1119, "min_raise": 160, "players": [{"avatar_url": null, "is_pro": false, "name": "player_1", "public_profile_slug": null, "seat": 0, "stack": 6782}, {"avatar_url": null, "is_pro": false, "name": "player_5", "public_profile_slug": null, "seat": 1, "stack": 1680}, {"avatar_url": null, "is_pro": false, "name": "player_3", "public_profile_slug": null, "seat": 2, "stack": 1990}, {"avatar_url": null, "is_pro": false, "name": "hero_bot", "public_profile_slug": null, "seat": 3, "stack": 1119}, {"avatar_url": null, "is_pro": false, "name": "player_4", "public_profile_slug": null, "seat": 4, "stack": 110}, {"avatar_url": null, "is_pro": false, "name": "player_2", "public_profile_slug": null, "seat": 5, "stack": 2928}], "pot": 140, "seat": 3, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10248, "ts": "2026-10-13T05:48:02.712175+00:00", "turn_token": "ecdb0f51-f3fa-413c-9ffb-17a9ecaac085", "type": "your_turn", "valid_actions": [{"action": "fold", "amount": null, "max": null, "min": null}, {"action": "call", "amount": 90, "max": null, "min": null}, {"action": "raise", "amount": null, "max": 1119, "min": 160}, {"action": "all_in", "amount": 1119, "max": null, "min": null}]}} +{"dir": "out", "msg": {"action": "raise", "amount": 270, "client_action_id": "plu-3-7", "hand_id": "dca7c37f-bd76-4794-ba9a-cc63f7b22375", "turn_token": "ecdb0f51-f3fa-413c-9ffb-17a9ecaac085", "type": "action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": [], "dealer_seat": 3, "hand_id": "dca7c37f-bd76-4794-ba9a-cc63f7b22375", "hand_seq": 39, "hero": {"hole_cards": ["Kc", "Qc"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 90}, {"action": "raise", "max": 1119, "min": 160}, {"action": "all_in", "amount": 1119}]}, "max_raise_to": 1119, "min_raise_to": 160, "pot": 140, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6782, "status": "active"}, {"bet": 90, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1680, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1119, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 110, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2928, "status": "active"}], "small_blind": 10, "state_hash": "sha256:e7a54097074c71e3e2a044929b8b1704901d1888af9717743244c6f7800c6d2a", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10249, "to_call": 90, "ts": "2026-10-13T05:48:02.712670+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"client_action_id": "plu-3-7", "hand_id": "dca7c37f-bd76-4794-ba9a-cc63f7b22375", "hand_seq": 41, "status": "accepted", "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10251, "ts": "2026-10-13T05:48:02.868728+00:00", "type": "action_ack"}} +{"dir": "in", "msg": {"action": "raise", "action_id": "plu-3-7", "amount": 270, "amount_mode": "to_total", "contribution_delta": 270, "hand_id": "dca7c37f-bd76-4794-ba9a-cc63f7b22375", "hand_seq": 42, "name": "hero_bot", "player_stack_after": 849, "player_stack_before": 1119, "pot": 410, "pot_after": 410, "pot_before": 140, "reason": null, "seat": 3, "stack": 849, "stack_after": 849, "stack_before": 1119, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10252, "to_call_before": 90, "ts": "2026-10-13T05:48:02.872007+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 4, "big_blind": 20, "board": [], "dealer_seat": 3, "hand_id": "dca7c37f-bd76-4794-ba9a-cc63f7b22375", "hand_seq": 43, "hero": {"hole_cards": ["Kc", "Qc"], "seat": 3}, "pot": 410, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6782, "status": "active"}, {"bet": 90, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1680, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 270, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 849, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 110, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2928, "status": "active"}], "small_blind": 10, "state_hash": "sha256:d5c7d5cb3ece6ce64553699b80ce061d515125d39eefcc32ddf48b1de40e34ba", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10253, "ts": "2026-10-13T05:48:02.872779+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "1f02bcee-331d-4e97-8411-03dfabd6d928", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "dca7c37f-bd76-4794-ba9a-cc63f7b22375", "hand_seq": 48, "name": "player_4", "player_stack_after": 110, "player_stack_before": 110, "pot": 410, "pot_after": 410, "pot_before": 410, "reason": null, "seat": 4, "stack": 110, "stack_after": 110, "stack_before": 110, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10258, "to_call_before": 110, "ts": "2026-10-13T05:48:05.880584+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 5, "big_blind": 20, "board": [], "dealer_seat": 3, "hand_id": "dca7c37f-bd76-4794-ba9a-cc63f7b22375", "hand_seq": 49, "hero": {"hole_cards": ["Kc", "Qc"], "seat": 3}, "pot": 410, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6782, "status": "active"}, {"bet": 90, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1680, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 270, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 849, "status": "active"}, {"bet": 10, "folded": true, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 110, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2928, "status": "active"}], "small_blind": 10, "state_hash": "sha256:2e92aa0f3ab6e00d0dcb881192a2f1ad37fa5e058d335a879f0874168d57fa36", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10259, "ts": "2026-10-13T05:48:05.881355+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "ae2cbfcd-cd89-4848-99b8-8baff6344178", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "dca7c37f-bd76-4794-ba9a-cc63f7b22375", "hand_seq": 54, "name": "player_2", "player_stack_after": 2928, "player_stack_before": 2928, "pot": 410, "pot_after": 410, "pot_before": 410, "reason": null, "seat": 5, "stack": 2928, "stack_after": 2928, "stack_before": 2928, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10264, "to_call_before": 250, "ts": "2026-10-13T05:48:09.139267+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": [], "dealer_seat": 3, "hand_id": "dca7c37f-bd76-4794-ba9a-cc63f7b22375", "hand_seq": 55, "hero": {"hole_cards": ["Kc", "Qc"], "seat": 3}, "pot": 410, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6782, "status": "active"}, {"bet": 90, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1680, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 270, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 849, "status": "active"}, {"bet": 10, "folded": true, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 110, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 20, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2928, "status": "active"}], "small_blind": 10, "state_hash": "sha256:8526b063f192d27fadefe4ac83aba235a3c7169e45371f57ea24cdfab8a5b0a7", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10265, "ts": "2026-10-13T05:48:09.140013+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "38fbcb30-7c3a-47e1-ae55-a6e9fbd304d6", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "dca7c37f-bd76-4794-ba9a-cc63f7b22375", "hand_seq": 60, "name": "player_1", "player_stack_after": 6782, "player_stack_before": 6782, "pot": 410, "pot_after": 410, "pot_before": 410, "reason": null, "seat": 0, "stack": 6782, "stack_after": 6782, "stack_before": 6782, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10270, "to_call_before": 250, "ts": "2026-10-13T05:48:12.476354+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 1, "big_blind": 20, "board": [], "dealer_seat": 3, "hand_id": "dca7c37f-bd76-4794-ba9a-cc63f7b22375", "hand_seq": 61, "hero": {"hole_cards": ["Kc", "Qc"], "seat": 3}, "pot": 410, "seats": [{"bet": 20, "folded": true, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6782, "status": "active"}, {"bet": 90, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1680, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 270, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 849, "status": "active"}, {"bet": 10, "folded": true, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 110, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 20, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2928, "status": "active"}], "small_blind": 10, "state_hash": "sha256:f10a42c28363f0eba2b6db17382eb513d1fe05eb6b1270f515e0955617e56ca2", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10271, "ts": "2026-10-13T05:48:12.477226+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "d0f84e24-0d3d-49dd-8e7e-6fba1f5b8fbd", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "dca7c37f-bd76-4794-ba9a-cc63f7b22375", "hand_seq": 66, "name": "player_5", "player_stack_after": 1680, "player_stack_before": 1680, "pot": 410, "pot_after": 410, "pot_before": 410, "reason": null, "seat": 1, "stack": 1680, "stack_after": 1680, "stack_before": 1680, "state_hash": null, "stream": "event", "street": "showdown", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10276, "to_call_before": 180, "ts": "2026-10-13T05:48:15.760089+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"big_blind": 20, "board": [], "dealer_seat": 3, "hand_id": "dca7c37f-bd76-4794-ba9a-cc63f7b22375", "hand_seq": 67, "hero": {"hole_cards": ["Kc", "Qc"], "seat": 3}, "pot": 0, "seats": [{"bet": 0, "in_hand": false, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6782, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1680, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 110, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "in_hand": false, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2928, "status": "active"}], "small_blind": 10, "state_hash": "sha256:a19e470e10f68f0c234127a8b6ba5dac7aa55394a4170c04ad1c74e1549be087", "stream": "state", "street": "idle", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10277, "ts": "2026-10-13T05:48:15.761100+00:00", "type": "table_state", "waiting_details": {"active_players": 6, "away_players": 0, "connected_players": 6, "disconnected_players": 0, "eligible_players": 6, "min_required": 2, "player_count": 6}, "waiting_reason": "awaiting_hand_start"}} +{"dir": "in", "msg": {"actions": [{"action": "call", "amount": null, "seat": 0, "street": "preflop"}, {"action": "raise", "amount": 90, "seat": 1, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 2, "street": "preflop"}, {"action": "raise", "amount": 270, "seat": 3, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 4, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 5, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 0, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 1, "street": "preflop"}], "final_stacks": {"0": 6782, "1": 1680, "2": 1990, "3": 1259, "4": 110, "5": 2928}, "hand_id": "dca7c37f-bd76-4794-ba9a-cc63f7b22375", "hand_seq": 68, "outcome_kind": "win", "payouts": [{"amount": 230, "seat": 3}], "pot": 140, "pot_kind": "transferable", "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10278, "total_pot": 230, "transferable_pot": 140, "ts": "2026-10-13T05:48:15.837972+00:00", "type": "hand_result", "winners": [{"amount": 140, "hand_description": null, "name": "hero_bot", "seat": 3, "stack": 1259}]}} +{"dir": "in", "msg": {"blinds": {"big_blind": 20, "small_blind": 10}, "dealer_seat": 4, "hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "hand_seq": 4, "seat": 3, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10282, "ts": "2026-10-13T05:48:20.872941+00:00", "type": "hand_start"}} +{"dir": "in", "msg": {"cards": ["8c", "3h"], "hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "hand_seq": 15, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10293, "ts": "2026-10-13T05:48:20.886719+00:00", "type": "hole_cards"}} +{"dir": "in", "msg": {"actor_seat": 1, "big_blind": 20, "board": [], "dealer_seat": 4, "hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "hand_seq": 16, "hero": {"hole_cards": ["8c", "3h"], "seat": 3}, "pot": 30, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6762, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1680, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 110, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:7f405537034a8f325d5bb66343694c419f90d199331699f6b8daec8555f57657", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10294, "ts": "2026-10-13T05:48:20.887015+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "0d9c9782-6cdf-427f-b377-b72679ddf5d0", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "hand_seq": 24, "name": "player_5", "player_stack_after": 1680, "player_stack_before": 1680, "pot": 30, "pot_after": 30, "pot_before": 30, "reason": null, "seat": 1, "stack": 1680, "stack_after": 1680, "stack_before": 1680, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10302, "to_call_before": 20, "ts": "2026-10-13T05:48:24.179542+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 2, "big_blind": 20, "board": [], "dealer_seat": 4, "hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "hand_seq": 25, "hero": {"hole_cards": ["8c", "3h"], "seat": 3}, "pot": 30, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6762, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1680, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1990, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 110, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:aeb2a87fb0620405f39b54912bf4691468725d2ae1819ccde9f030e32e833681", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10303, "ts": "2026-10-13T05:48:24.180603+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "raise", "action_id": "oc-ee0ea2cffa83-53", "amount": 50, "amount_mode": "to_total", "contribution_delta": 50, "hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "hand_seq": 30, "name": "player_3", "player_stack_after": 1940, "player_stack_before": 1990, "pot": 80, "pot_after": 80, "pot_before": 30, "reason": null, "seat": 2, "stack": 1940, "stack_after": 1940, "stack_before": 1990, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10308, "to_call_before": 20, "ts": "2026-10-13T05:48:27.264732+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": [], "dealer_seat": 4, "hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "hand_seq": 31, "hero": {"hole_cards": ["8c", "3h"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 50}, {"action": "raise", "max": 1259, "min": 80}, {"action": "all_in", "amount": 1259}]}, "max_raise_to": 1259, "min_raise_to": 80, "pot": 80, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6762, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1680, "status": "active"}, {"bet": 50, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1940, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 110, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:602716cae789639f193fb971cbf1ad737c8b33d3b2a54f477a6822be74910f51", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10309, "to_call": 50, "ts": "2026-10-13T05:48:27.265610+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"community_cards": [], "hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "hand_seq": 32, "max_raise": 1259, "min_raise": 80, "players": [{"avatar_url": null, "is_pro": false, "name": "player_1", "public_profile_slug": null, "seat": 0, "stack": 6762}, {"avatar_url": null, "is_pro": false, "name": "player_5", "public_profile_slug": null, "seat": 1, "stack": 1680}, {"avatar_url": null, "is_pro": false, "name": "player_3", "public_profile_slug": null, "seat": 2, "stack": 1940}, {"avatar_url": null, "is_pro": false, "name": "hero_bot", "public_profile_slug": null, "seat": 3, "stack": 1259}, {"avatar_url": null, "is_pro": false, "name": "player_4", "public_profile_slug": null, "seat": 4, "stack": 110}, {"avatar_url": null, "is_pro": false, "name": "player_2", "public_profile_slug": null, "seat": 5, "stack": 2918}], "pot": 80, "seat": 3, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10310, "ts": "2026-10-13T05:48:30.268453+00:00", "turn_token": "38aa220a-9736-469e-8495-fce505365029", "type": "your_turn", "valid_actions": [{"action": "fold", "amount": null, "max": null, "min": null}, {"action": "call", "amount": 50, "max": null, "min": null}, {"action": "raise", "amount": null, "max": 1259, "min": 80}, {"action": "all_in", "amount": 1259, "max": null, "min": null}]}} +{"dir": "out", "msg": {"action": "fold", "client_action_id": "plu-4-8", "hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "turn_token": "38aa220a-9736-469e-8495-fce505365029", "type": "action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": [], "dealer_seat": 4, "hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "hand_seq": 33, "hero": {"hole_cards": ["8c", "3h"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 50}, {"action": "raise", "max": 1259, "min": 80}, {"action": "all_in", "amount": 1259}]}, "max_raise_to": 1259, "min_raise_to": 80, "pot": 80, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6762, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1680, "status": "active"}, {"bet": 50, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1940, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 110, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:602716cae789639f193fb971cbf1ad737c8b33d3b2a54f477a6822be74910f51", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10311, "to_call": 50, "ts": "2026-10-13T05:48:30.268943+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"client_action_id": "plu-4-8", "hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "hand_seq": 35, "status": "accepted", "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10313, "ts": "2026-10-13T05:48:30.424024+00:00", "type": "action_ack"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "plu-4-8", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "hand_seq": 36, "name": "hero_bot", "player_stack_after": 1259, "player_stack_before": 1259, "pot": 80, "pot_after": 80, "pot_before": 80, "reason": null, "seat": 3, "stack": 1259, "stack_after": 1259, "stack_before": 1259, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10314, "to_call_before": 50, "ts": "2026-10-13T05:48:30.428799+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 4, "big_blind": 20, "board": [], "dealer_seat": 4, "hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "hand_seq": 37, "hero": {"hole_cards": ["8c", "3h"], "seat": 3}, "pot": 80, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6762, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1680, "status": "active"}, {"bet": 50, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1940, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 110, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:a7b97b4bde81bcb775f13bf68bb84b2f11a59143089c46062fccfd6106ef09d2", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10315, "ts": "2026-10-13T05:48:30.430189+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "raise", "action_id": "83e4b775-cdad-420f-831c-e0c1d2c2f0bc", "amount": 110, "amount_mode": "to_total", "contribution_delta": 110, "hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "hand_seq": 42, "name": "player_4", "player_stack_after": 0, "player_stack_before": 110, "pot": 190, "pot_after": 190, "pot_before": 80, "reason": null, "seat": 4, "stack": 0, "stack_after": 0, "stack_before": 110, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10320, "to_call_before": 50, "ts": "2026-10-13T05:48:35.034505+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 5, "big_blind": 20, "board": [], "dealer_seat": 4, "hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "hand_seq": 43, "hero": {"hole_cards": ["8c", "3h"], "seat": 3}, "pot": 190, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6762, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1680, "status": "active"}, {"bet": 50, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1940, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 110, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 0, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:3f134b0cd191f92fe70ddeeec95700847f76faaa2727e79f58ec6955d66694cb", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10321, "ts": "2026-10-13T05:48:35.035215+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "84fa8964-f963-4266-a77a-60bbe850a9dc", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "hand_seq": 48, "name": "player_2", "player_stack_after": 2918, "player_stack_before": 2918, "pot": 190, "pot_after": 190, "pot_before": 190, "reason": null, "seat": 5, "stack": 2918, "stack_after": 2918, "stack_before": 2918, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10326, "to_call_before": 100, "ts": "2026-10-13T05:48:38.334948+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": [], "dealer_seat": 4, "hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "hand_seq": 49, "hero": {"hole_cards": ["8c", "3h"], "seat": 3}, "pot": 190, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6762, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1680, "status": "active"}, {"bet": 50, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1940, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 110, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 0, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 10, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:779bff4ee68829cb5207f6f308162724774045e8a7a5b03cd9fb8ee70ba25342", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10327, "ts": "2026-10-13T05:48:38.335940+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "raise", "action_id": "f916e12a-c38a-4967-ac69-416b4f693d35", "amount": 253, "amount_mode": "to_total", "contribution_delta": 233, "hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "hand_seq": 54, "name": "player_1", "player_stack_after": 6529, "player_stack_before": 6762, "pot": 423, "pot_after": 423, "pot_before": 190, "reason": null, "seat": 0, "stack": 6529, "stack_after": 6529, "stack_before": 6762, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10332, "to_call_before": 90, "ts": "2026-10-13T05:48:41.719357+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 2, "big_blind": 20, "board": [], "dealer_seat": 4, "hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "hand_seq": 55, "hero": {"hole_cards": ["8c", "3h"], "seat": 3}, "pot": 423, "seats": [{"bet": 253, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6529, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1680, "status": "active"}, {"bet": 50, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 1940, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 110, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 0, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 10, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:df75016f703ab9cf6c9aab5af4af905ed40a3e5e5f58c71e2e122bc035a254b4", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10333, "ts": "2026-10-13T05:48:41.720005+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "all_in", "action_id": "oc-7789d7537709-54", "amount": null, "amount_mode": "to_total", "contribution_delta": 0, "hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "hand_seq": 60, "name": "player_3", "player_stack_after": 1940, "player_stack_before": 1940, "pot": 423, "pot_after": 423, "pot_before": 423, "reason": null, "seat": 2, "stack": 1940, "stack_after": 1940, "stack_before": 1940, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10338, "to_call_before": 203, "ts": "2026-10-13T05:48:44.800540+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": [], "dealer_seat": 4, "hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "hand_seq": 61, "hero": {"hole_cards": ["8c", "3h"], "seat": 3}, "pot": 2363, "seats": [{"bet": 253, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6529, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1680, "status": "active"}, {"bet": 1990, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 0, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 110, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 0, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 10, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:0baa6ed23a4e7d33b38064dd35613992ee76014b0048eb3c1d080b1556295e8f", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10339, "ts": "2026-10-13T05:48:44.801369+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "bfb9a726-fbbf-4be9-9434-6c5f0fa2350a", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "hand_seq": 66, "name": "player_1", "player_stack_after": 6529, "player_stack_before": 6529, "pot": 2363, "pot_after": 2363, "pot_before": 2363, "reason": null, "seat": 0, "stack": 6529, "stack_after": 6529, "stack_before": 6529, "state_hash": null, "stream": "event", "street": "showdown", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10344, "to_call_before": 1737, "ts": "2026-10-13T05:48:48.071959+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"big_blind": 20, "board": [], "dealer_seat": 4, "hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "hand_seq": 67, "hero": {"hole_cards": ["8c", "3h"], "seat": 3}, "pot": 0, "seats": [{"bet": 0, "in_hand": false, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6529, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1680, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2363, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 0, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "in_hand": false, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:30d0276e455b5845d3472f71881be5cdb120dd53a73fe67a55979adb053e01c8", "stream": "state", "street": "idle", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10345, "ts": "2026-10-13T05:48:48.072715+00:00", "type": "table_state", "waiting_details": {"active_players": 6, "away_players": 0, "connected_players": 6, "disconnected_players": 0, "eligible_players": 5, "min_required": 2, "player_count": 6}, "waiting_reason": "awaiting_hand_start"}} +{"dir": "in", "msg": {"cards": ["Jd", "7c", "9s"], "hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "hand_seq": 68, "state_hash": null, "stream": "event", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10346, "ts": "2026-10-13T05:48:48.075898+00:00", "type": "community_cards"}} +{"dir": "in", "msg": {"cards": ["Jd", "7c", "9s", "6h"], "hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "hand_seq": 69, "state_hash": null, "stream": "event", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10347, "ts": "2026-10-13T05:48:48.076411+00:00", "type": "community_cards"}} +{"dir": "in", "msg": {"cards": ["Jd", "7c", "9s", "6h", "8d"], "hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "hand_seq": 70, "state_hash": null, "stream": "event", "street": "river", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10348, "ts": "2026-10-13T05:48:48.076831+00:00", "type": "community_cards"}} +{"dir": "in", "msg": {"big_blind": 20, "board": ["Jd", "7c", "9s", "6h", "8d"], "dealer_seat": 4, "hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "hand_seq": 71, "hero": {"hole_cards": ["8c", "3h"], "seat": 3}, "pot": 0, "seats": [{"bet": 0, "in_hand": false, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6529, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1680, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2363, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 0, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "in_hand": false, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:cb86cf216863ebc8a4624940168fae7a0cbb779cf952bb0d32c44b90e3cd4074", "stream": "state", "street": "idle", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10349, "ts": "2026-10-13T05:48:48.077277+00:00", "type": "table_state", "waiting_details": {"active_players": 6, "away_players": 0, "connected_players": 6, "disconnected_players": 0, "eligible_players": 5, "min_required": 2, "player_count": 6}, "waiting_reason": "awaiting_hand_start"}} +{"dir": "in", "msg": {"actions": [{"action": "fold", "amount": null, "seat": 1, "street": "preflop"}, {"action": "raise", "amount": 50, "seat": 2, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 3, "street": "preflop"}, {"action": "raise", "amount": 110, "seat": 4, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 5, "street": "preflop"}, {"action": "raise", "amount": 253, "seat": 0, "street": "preflop"}, {"action": "all_in", "amount": null, "seat": 2, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 0, "street": "preflop"}], "final_stacks": {"0": 6529, "1": 1680, "2": 2363, "3": 1259, "4": 0, "5": 2918}, "hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "hand_seq": 72, "outcome_kind": "win", "payouts": [{"amount": 626, "seat": 2}], "pot": 373, "pot_kind": "transferable", "shown_cards": {"2": ["Ah", "Ac"], "4": ["7h", "Ks"]}, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10350, "total_pot": 626, "transferable_pot": 373, "ts": "2026-10-13T05:48:48.154699+00:00", "type": "hand_result", "winners": [{"amount": 373, "hand_description": "One pair", "name": "player_3", "seat": 2, "stack": 2363}]}} +{"dir": "in", "msg": {"hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "hand_seq": 75, "name": "player_4", "reason": "busted", "seat": 4, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10353, "ts": "2026-10-13T05:48:48.244389+00:00", "type": "player_left"}} +{"dir": "in", "msg": {"avatar": null, "avatar_url": null, "hand_id": "7d462ea8-53be-4c50-81ee-6dcb3939468b", "hand_seq": 78, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1800, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10356, "ts": "2026-10-13T05:48:49.271865+00:00", "type": "player_joined"}} +{"dir": "in", "msg": {"blinds": {"big_blind": 20, "small_blind": 10}, "dealer_seat": 5, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 4, "seat": 3, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10360, "ts": "2026-10-13T05:48:49.299738+00:00", "type": "hand_start"}} +{"dir": "in", "msg": {"cards": ["3h", "3d"], "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 13, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10369, "ts": "2026-10-13T05:48:49.312980+00:00", "type": "hole_cards"}} +{"dir": "in", "msg": {"actor_seat": 2, "big_blind": 20, "board": [], "dealer_seat": 5, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 14, "hero": {"hole_cards": ["3h", "3d"], "seat": 3}, "pot": 30, "seats": [{"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6519, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1660, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2363, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1800, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:0fd23b561277a2cd5a04a088decf22014f975184b8313649e5a14f4dc4d1567d", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10370, "ts": "2026-10-13T05:48:49.313138+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "raise", "action_id": "oc-ae063210772b-55", "amount": 50, "amount_mode": "to_total", "contribution_delta": 50, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 24, "name": "player_3", "player_stack_after": 2313, "player_stack_before": 2363, "pot": 80, "pot_after": 80, "pot_before": 30, "reason": null, "seat": 2, "stack": 2313, "stack_after": 2313, "stack_before": 2363, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10380, "to_call_before": 20, "ts": "2026-10-13T05:48:52.403359+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": [], "dealer_seat": 5, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 25, "hero": {"hole_cards": ["3h", "3d"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 50}, {"action": "raise", "max": 1259, "min": 80}, {"action": "all_in", "amount": 1259}]}, "max_raise_to": 1259, "min_raise_to": 80, "pot": 80, "seats": [{"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6519, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1660, "status": "active"}, {"bet": 50, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2313, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1800, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:8dea3ef8db1c96a1a72b28f9db2a3b01c9bcd7434c590edd20ff19cbecd18cde", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10381, "to_call": 50, "ts": "2026-10-13T05:48:52.404883+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"community_cards": [], "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 26, "max_raise": 1259, "min_raise": 80, "players": [{"avatar_url": null, "is_pro": false, "name": "player_1", "public_profile_slug": null, "seat": 0, "stack": 6519}, {"avatar_url": null, "is_pro": false, "name": "player_5", "public_profile_slug": null, "seat": 1, "stack": 1660}, {"avatar_url": null, "is_pro": false, "name": "player_3", "public_profile_slug": null, "seat": 2, "stack": 2313}, {"avatar_url": null, "is_pro": false, "name": "hero_bot", "public_profile_slug": null, "seat": 3, "stack": 1259}, {"avatar_url": null, "is_pro": false, "name": "player_4", "public_profile_slug": null, "seat": 4, "stack": 1800}, {"avatar_url": null, "is_pro": false, "name": "player_2", "public_profile_slug": null, "seat": 5, "stack": 2918}], "pot": 80, "seat": 3, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10382, "ts": "2026-10-13T05:48:55.410258+00:00", "turn_token": "15628f57-173a-4752-916d-c2789e769a69", "type": "your_turn", "valid_actions": [{"action": "fold", "amount": null, "max": null, "min": null}, {"action": "call", "amount": 50, "max": null, "min": null}, {"action": "raise", "amount": null, "max": 1259, "min": 80}, {"action": "all_in", "amount": 1259, "max": null, "min": null}]}} +{"dir": "out", "msg": {"action": "fold", "client_action_id": "plu-5-9", "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "turn_token": "15628f57-173a-4752-916d-c2789e769a69", "type": "action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": [], "dealer_seat": 5, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 27, "hero": {"hole_cards": ["3h", "3d"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 50}, {"action": "raise", "max": 1259, "min": 80}, {"action": "all_in", "amount": 1259}]}, "max_raise_to": 1259, "min_raise_to": 80, "pot": 80, "seats": [{"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6519, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1660, "status": "active"}, {"bet": 50, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2313, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1800, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:8dea3ef8db1c96a1a72b28f9db2a3b01c9bcd7434c590edd20ff19cbecd18cde", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10383, "to_call": 50, "ts": "2026-10-13T05:48:55.410608+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"client_action_id": "plu-5-9", "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 29, "status": "accepted", "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10385, "ts": "2026-10-13T05:48:55.565629+00:00", "type": "action_ack"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "plu-5-9", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 30, "name": "hero_bot", "player_stack_after": 1259, "player_stack_before": 1259, "pot": 80, "pot_after": 80, "pot_before": 80, "reason": null, "seat": 3, "stack": 1259, "stack_after": 1259, "stack_before": 1259, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10386, "to_call_before": 50, "ts": "2026-10-13T05:48:55.568374+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 4, "big_blind": 20, "board": [], "dealer_seat": 5, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 31, "hero": {"hole_cards": ["3h", "3d"], "seat": 3}, "pot": 80, "seats": [{"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6519, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1660, "status": "active"}, {"bet": 50, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2313, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1800, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:7671561c16ea54a08d6185d839ea9e6e7c6bfb3fa8bf706b3eede73c4fa485af", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10387, "ts": "2026-10-13T05:48:55.569048+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "call", "action_id": "74802a2c-ff57-4558-a888-dd2ef6e1f7a0", "amount": null, "amount_mode": "incremental", "contribution_delta": 50, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 36, "name": "player_4", "player_stack_after": 1750, "player_stack_before": 1800, "pot": 130, "pot_after": 130, "pot_before": 80, "reason": null, "seat": 4, "stack": 1750, "stack_after": 1750, "stack_before": 1800, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10392, "to_call_before": 50, "ts": "2026-10-13T05:48:58.577417+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 5, "big_blind": 20, "board": [], "dealer_seat": 5, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 37, "hero": {"hole_cards": ["3h", "3d"], "seat": 3}, "pot": 130, "seats": [{"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6519, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1660, "status": "active"}, {"bet": 50, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2313, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 50, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1750, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:ce781f49ed4095aae39ee6a861c473447215e3decd08c7f02ccee64a83d3ef8f", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10393, "ts": "2026-10-13T05:48:58.578526+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "89b6435b-6d8f-49c1-9f20-643b9cf48388", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 42, "name": "player_2", "player_stack_after": 2918, "player_stack_before": 2918, "pot": 130, "pot_after": 130, "pot_before": 130, "reason": null, "seat": 5, "stack": 2918, "stack_after": 2918, "stack_before": 2918, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10398, "to_call_before": 50, "ts": "2026-10-13T05:49:01.834131+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": [], "dealer_seat": 5, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 43, "hero": {"hole_cards": ["3h", "3d"], "seat": 3}, "pot": 130, "seats": [{"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6519, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1660, "status": "active"}, {"bet": 50, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2313, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 50, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1750, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:1e2887c4879973a2ec211da1b7b71f78cb3b83dd310b17331101deb74c051f9e", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10399, "ts": "2026-10-13T05:49:01.835029+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "call", "action_id": "5807241a-0ff0-4258-a162-9a9162ff2bd9", "amount": null, "amount_mode": "incremental", "contribution_delta": 40, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 48, "name": "player_1", "player_stack_after": 6479, "player_stack_before": 6519, "pot": 170, "pot_after": 170, "pot_before": 130, "reason": null, "seat": 0, "stack": 6479, "stack_after": 6479, "stack_before": 6519, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10404, "to_call_before": 40, "ts": "2026-10-13T05:49:05.246577+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 1, "big_blind": 20, "board": [], "dealer_seat": 5, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 49, "hero": {"hole_cards": ["3h", "3d"], "seat": 3}, "pot": 170, "seats": [{"bet": 50, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6479, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1660, "status": "active"}, {"bet": 50, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2313, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 50, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1750, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:24261bd7060f01095bf77728f1e2ec38cfd3684275e4c5f50e77fec581c75438", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10405, "ts": "2026-10-13T05:49:05.247338+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "raise", "action_id": "113eaf7a-f605-4933-ae3e-6416eee34283", "amount": 180, "amount_mode": "to_total", "contribution_delta": 160, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 54, "name": "player_5", "player_stack_after": 1500, "player_stack_before": 1660, "pot": 330, "pot_after": 330, "pot_before": 170, "reason": null, "seat": 1, "stack": 1500, "stack_after": 1500, "stack_before": 1660, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10410, "to_call_before": 30, "ts": "2026-10-13T05:49:08.522282+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 2, "big_blind": 20, "board": [], "dealer_seat": 5, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 55, "hero": {"hole_cards": ["3h", "3d"], "seat": 3}, "pot": 330, "seats": [{"bet": 50, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6479, "status": "active"}, {"bet": 180, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1500, "status": "active"}, {"bet": 50, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2313, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 50, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1750, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:c844e6c5ec91994ce48a5637dca06752254a67cce35e991ae06d00f6843d8b89", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10411, "ts": "2026-10-13T05:49:08.523215+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "oc-b3e7820d2b69-56", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 60, "name": "player_3", "player_stack_after": 2313, "player_stack_before": 2313, "pot": 330, "pot_after": 330, "pot_before": 330, "reason": null, "seat": 2, "stack": 2313, "stack_after": 2313, "stack_before": 2313, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10416, "to_call_before": 130, "ts": "2026-10-13T05:49:11.608213+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 4, "big_blind": 20, "board": [], "dealer_seat": 5, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 61, "hero": {"hole_cards": ["3h", "3d"], "seat": 3}, "pot": 330, "seats": [{"bet": 50, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6479, "status": "active"}, {"bet": 180, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1500, "status": "active"}, {"bet": 50, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2313, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 50, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1750, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:abfb89c2d3a74fec6a8ceed5c91a8fa3554030ffce6a36902ddc7908c8759f90", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10417, "ts": "2026-10-13T05:49:11.609274+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "call", "action_id": "89c45fc1-4d38-4e8e-bd98-252a51fc775b", "amount": null, "amount_mode": "incremental", "contribution_delta": 130, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 66, "name": "player_4", "player_stack_after": 1620, "player_stack_before": 1750, "pot": 460, "pot_after": 460, "pot_before": 330, "reason": null, "seat": 4, "stack": 1620, "stack_after": 1620, "stack_before": 1750, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10422, "to_call_before": 130, "ts": "2026-10-13T05:49:14.616828+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": [], "dealer_seat": 5, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 67, "hero": {"hole_cards": ["3h", "3d"], "seat": 3}, "pot": 460, "seats": [{"bet": 50, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6479, "status": "active"}, {"bet": 180, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1500, "status": "active"}, {"bet": 50, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2313, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 180, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1620, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:85f4bb2e591813eb37d566c489077b13b9d998db5534b94a96cb5103928309be", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10423, "ts": "2026-10-13T05:49:14.617577+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "502e4e48-1804-442c-890a-0e9b9364e626", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 72, "name": "player_1", "player_stack_after": 6479, "player_stack_before": 6479, "pot": 460, "pot_after": 460, "pot_before": 460, "reason": null, "seat": 0, "stack": 6479, "stack_after": 6479, "stack_before": 6479, "state_hash": null, "stream": "event", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10428, "to_call_before": 130, "ts": "2026-10-13T05:49:17.939451+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 1, "big_blind": 20, "board": [], "dealer_seat": 5, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 73, "hero": {"hole_cards": ["3h", "3d"], "seat": 3}, "pot": 460, "seats": [{"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6479, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1500, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2313, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1620, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:f2ed96ba7a0bc1d0570441d5297981e3559a7d016a46c6e8f6583764c241d545", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10429, "ts": "2026-10-13T05:49:17.940084+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"cards": ["5d", "2s", "3s"], "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 74, "state_hash": null, "stream": "event", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10430, "ts": "2026-10-13T05:49:20.942875+00:00", "type": "community_cards"}} +{"dir": "in", "msg": {"actor_seat": 1, "big_blind": 20, "board": ["5d", "2s", "3s"], "dealer_seat": 5, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 75, "hero": {"hole_cards": ["3h", "3d"], "seat": 3}, "pot": 460, "seats": [{"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6479, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1500, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2313, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1620, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:b1275c716d6926ed00598addd70343893db9d5b8b6da5f19fdd9f86d8abd1fb2", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10431, "ts": "2026-10-13T05:49:20.944338+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "raise", "action_id": "ea664d27-01b4-45cb-9667-ea4f2c61c924", "amount": 338, "amount_mode": "to_total", "contribution_delta": 338, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 80, "name": "player_5", "player_stack_after": 1162, "player_stack_before": 1500, "pot": 798, "pot_after": 798, "pot_before": 460, "reason": null, "seat": 1, "stack": 1162, "stack_after": 1162, "stack_before": 1500, "state_hash": null, "stream": "event", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10436, "to_call_before": null, "ts": "2026-10-13T05:49:21.227836+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 4, "big_blind": 20, "board": ["5d", "2s", "3s"], "dealer_seat": 5, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 81, "hero": {"hole_cards": ["3h", "3d"], "seat": 3}, "pot": 798, "seats": [{"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6479, "status": "active"}, {"bet": 338, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1162, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2313, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1620, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:4044e9e0b5122e2eecfe03a9eb5c6f6276dd1926f420f1e96757863268779ddd", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10437, "ts": "2026-10-13T05:49:21.229469+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "call", "action_id": "1429f422-68e3-42ec-9dcf-a666b15e87fd", "amount": null, "amount_mode": "incremental", "contribution_delta": 338, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 86, "name": "player_4", "player_stack_after": 1282, "player_stack_before": 1620, "pot": 1136, "pot_after": 1136, "pot_before": 798, "reason": null, "seat": 4, "stack": 1282, "stack_after": 1282, "stack_before": 1620, "state_hash": null, "stream": "event", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10442, "to_call_before": 338, "ts": "2026-10-13T05:49:24.250071+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 1, "big_blind": 20, "board": ["5d", "2s", "3s"], "dealer_seat": 5, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 87, "hero": {"hole_cards": ["3h", "3d"], "seat": 3}, "pot": 1136, "seats": [{"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6479, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1162, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2313, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1282, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:bbd42e4b20db3a9569b12230b2f82161cd1a86cfd793b3aa160d4e95f82b58de", "stream": "state", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10443, "ts": "2026-10-13T05:49:24.252316+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"cards": ["5d", "2s", "3s", "7c"], "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 88, "state_hash": null, "stream": "event", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10444, "ts": "2026-10-13T05:49:27.260176+00:00", "type": "community_cards"}} +{"dir": "in", "msg": {"actor_seat": 1, "big_blind": 20, "board": ["5d", "2s", "3s", "7c"], "dealer_seat": 5, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 89, "hero": {"hole_cards": ["3h", "3d"], "seat": 3}, "pot": 1136, "seats": [{"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6479, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 1162, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2313, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1282, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:2da15ddfd9de2fdc6ea82e0db76b0429cdf094c2604e5f6f998962a182e3f6b4", "stream": "state", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10445, "ts": "2026-10-13T05:49:27.260943+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "all_in", "action_id": "4ef294c3-c5c5-4ac6-804d-ae2a05ec75cc", "amount": null, "amount_mode": "to_total", "contribution_delta": 0, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 94, "name": "player_5", "player_stack_after": 1162, "player_stack_before": 1162, "pot": 1136, "pot_after": 1136, "pot_before": 1136, "reason": null, "seat": 1, "stack": 1162, "stack_after": 1162, "stack_before": 1162, "state_hash": null, "stream": "event", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10450, "to_call_before": null, "ts": "2026-10-13T05:49:27.543621+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 4, "big_blind": 20, "board": ["5d", "2s", "3s", "7c"], "dealer_seat": 5, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 95, "hero": {"hole_cards": ["3h", "3d"], "seat": 3}, "pot": 2298, "seats": [{"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6479, "status": "active"}, {"bet": 1162, "folded": false, "in_hand": true, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 0, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2313, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 1282, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:481385fe3594419611bb09085401c8b5ff4f42be399ee1ee6eb5b81560ba2ea6", "stream": "state", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10451, "ts": "2026-10-13T05:49:27.544477+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "call", "action_id": "cfcb945e-5b0b-4b6b-8e7e-1b3655439635", "amount": null, "amount_mode": "incremental", "contribution_delta": 1162, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 100, "name": "player_4", "player_stack_after": 120, "player_stack_before": 1282, "pot": 3460, "pot_after": 3460, "pot_before": 2298, "reason": null, "seat": 4, "stack": 120, "stack_after": 120, "stack_before": 1282, "state_hash": null, "stream": "event", "street": "showdown", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10456, "to_call_before": 1162, "ts": "2026-10-13T05:49:30.555433+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"big_blind": 20, "board": ["5d", "2s", "3s", "7c"], "dealer_seat": 5, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 101, "hero": {"hole_cards": ["3h", "3d"], "seat": 3}, "pot": 0, "seats": [{"bet": 0, "in_hand": false, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6479, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 0, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2313, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 3580, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "in_hand": false, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:881622f002f354520ac75a6f6266d01bbf4b418a96f384f6be11f477e64884d4", "stream": "state", "street": "idle", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10457, "ts": "2026-10-13T05:49:30.556377+00:00", "type": "table_state", "waiting_details": {"active_players": 6, "away_players": 0, "connected_players": 6, "disconnected_players": 0, "eligible_players": 5, "min_required": 2, "player_count": 6}, "waiting_reason": "awaiting_hand_start"}} +{"dir": "in", "msg": {"cards": ["5d", "2s", "3s", "7c", "Qh"], "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 102, "state_hash": null, "stream": "event", "street": "river", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10458, "ts": "2026-10-13T05:49:30.560299+00:00", "type": "community_cards"}} +{"dir": "in", "msg": {"big_blind": 20, "board": ["5d", "2s", "3s", "7c", "Qh"], "dealer_seat": 5, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 103, "hero": {"hole_cards": ["3h", "3d"], "seat": 3}, "pot": 0, "seats": [{"bet": 0, "in_hand": false, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6479, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_5", "public_profile_slug": "player_5", "seat": 1, "stack": 0, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2313, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_4", "public_profile_slug": "player_4", "seat": 4, "stack": 3580, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "in_hand": false, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:a7ea9edb7edd95d8abde2178ecfa9bdaad784547d50dbf44a8ffaf9c5b77a703", "stream": "state", "street": "idle", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10459, "ts": "2026-10-13T05:49:30.560890+00:00", "type": "table_state", "waiting_details": {"active_players": 6, "away_players": 0, "connected_players": 6, "disconnected_players": 0, "eligible_players": 5, "min_required": 2, "player_count": 6}, "waiting_reason": "awaiting_hand_start"}} +{"dir": "in", "msg": {"actions": [{"action": "raise", "amount": 50, "seat": 2, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 3, "street": "preflop"}, {"action": "call", "amount": null, "seat": 4, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 5, "street": "preflop"}, {"action": "call", "amount": null, "seat": 0, "street": "preflop"}, {"action": "raise", "amount": 180, "seat": 1, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 2, "street": "preflop"}, {"action": "call", "amount": null, "seat": 4, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 0, "street": "preflop"}, {"action": "raise", "amount": 338, "seat": 1, "street": "flop"}, {"action": "call", "amount": null, "seat": 4, "street": "flop"}, {"action": "all_in", "amount": null, "seat": 1, "street": "turn"}, {"action": "call", "amount": null, "seat": 4, "street": "turn"}], "final_stacks": {"0": 6479, "1": 0, "2": 2313, "3": 1259, "4": 3580, "5": 2918}, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 104, "outcome_kind": "win", "payouts": [{"amount": 3460, "seat": 4}], "pot": 1780, "pot_kind": "transferable", "shown_cards": {"1": ["Ad", "9h"], "4": ["6c", "6h"]}, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10460, "total_pot": 3460, "transferable_pot": 1780, "ts": "2026-10-13T05:49:30.608269+00:00", "type": "hand_result", "winners": [{"amount": 1780, "hand_description": "One pair", "name": "player_4", "seat": 4, "stack": 3580}]}} +{"dir": "in", "msg": {"hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 107, "name": "player_5", "reason": "busted", "seat": 1, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10463, "ts": "2026-10-13T05:49:30.656212+00:00", "type": "player_left"}} +{"dir": "in", "msg": {"hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 109, "name": "player_4", "reason": "left", "seat": 4, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10465, "ts": "2026-10-13T05:49:30.679357+00:00", "type": "player_left"}} +{"dir": "in", "msg": {"avatar": null, "avatar_url": null, "hand_id": "0bd55035-f7ac-43dc-992b-f33d01e27bf5", "hand_seq": 112, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2986, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10468, "ts": "2026-10-13T05:49:32.919675+00:00", "type": "player_joined"}} +{"dir": "in", "msg": {"blinds": {"big_blind": 20, "small_blind": 10}, "dealer_seat": 0, "hand_id": "153bc60e-0a6b-4691-b52c-93f35126db40", "hand_seq": 4, "seat": 3, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10472, "ts": "2026-10-13T05:49:32.947474+00:00", "type": "hand_start"}} +{"dir": "in", "msg": {"cards": ["Kh", "Td"], "hand_id": "153bc60e-0a6b-4691-b52c-93f35126db40", "hand_seq": 10, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10478, "ts": "2026-10-13T05:49:32.954808+00:00", "type": "hole_cards"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": [], "dealer_seat": 0, "hand_id": "153bc60e-0a6b-4691-b52c-93f35126db40", "hand_seq": 11, "hero": {"hole_cards": ["Kh", "Td"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 20}, {"action": "raise", "max": 1259, "min": 40}, {"action": "all_in", "amount": 1259}]}, "max_raise_to": 1259, "min_raise_to": 40, "pot": 30, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6479, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2976, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2293, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 0, "is_pro": false, "seat": 4, "stack": 0, "status": "empty"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:ae9fdf0cceca03a485d8831f786a889e70b0306413718c3a00d3880834345de8", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10479, "to_call": 20, "ts": "2026-10-13T05:49:32.955160+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"community_cards": [], "hand_id": "153bc60e-0a6b-4691-b52c-93f35126db40", "hand_seq": 17, "max_raise": 1259, "min_raise": 40, "players": [{"avatar_url": null, "is_pro": false, "name": "player_1", "public_profile_slug": null, "seat": 0, "stack": 6479}, {"avatar_url": null, "is_pro": false, "name": "player_6", "public_profile_slug": null, "seat": 1, "stack": 2976}, {"avatar_url": null, "is_pro": false, "name": "player_3", "public_profile_slug": null, "seat": 2, "stack": 2293}, {"avatar_url": null, "is_pro": false, "name": "hero_bot", "public_profile_slug": null, "seat": 3, "stack": 1259}, {"avatar_url": null, "is_pro": false, "name": "player_2", "public_profile_slug": null, "seat": 5, "stack": 2918}], "pot": 30, "seat": 3, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10485, "ts": "2026-10-13T05:49:35.956984+00:00", "turn_token": "d00a63a5-1153-423c-8703-1f46b62b6241", "type": "your_turn", "valid_actions": [{"action": "fold", "amount": null, "max": null, "min": null}, {"action": "call", "amount": 20, "max": null, "min": null}, {"action": "raise", "amount": null, "max": 1259, "min": 40}, {"action": "all_in", "amount": 1259, "max": null, "min": null}]}} +{"dir": "out", "msg": {"action": "raise", "amount": 60, "client_action_id": "plu-6-10", "hand_id": "153bc60e-0a6b-4691-b52c-93f35126db40", "turn_token": "d00a63a5-1153-423c-8703-1f46b62b6241", "type": "action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": [], "dealer_seat": 0, "hand_id": "153bc60e-0a6b-4691-b52c-93f35126db40", "hand_seq": 18, "hero": {"hole_cards": ["Kh", "Td"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 20}, {"action": "raise", "max": 1259, "min": 40}, {"action": "all_in", "amount": 1259}]}, "max_raise_to": 1259, "min_raise_to": 40, "pot": 30, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6479, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2976, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2293, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1259, "status": "active"}, {"bet": 0, "is_pro": false, "seat": 4, "stack": 0, "status": "empty"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:ae9fdf0cceca03a485d8831f786a889e70b0306413718c3a00d3880834345de8", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10486, "to_call": 20, "ts": "2026-10-13T05:49:35.957521+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"client_action_id": "plu-6-10", "hand_id": "153bc60e-0a6b-4691-b52c-93f35126db40", "hand_seq": 20, "status": "accepted", "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10488, "ts": "2026-10-13T05:49:36.119614+00:00", "type": "action_ack"}} +{"dir": "in", "msg": {"action": "raise", "action_id": "plu-6-10", "amount": 60, "amount_mode": "to_total", "contribution_delta": 60, "hand_id": "153bc60e-0a6b-4691-b52c-93f35126db40", "hand_seq": 21, "name": "hero_bot", "player_stack_after": 1199, "player_stack_before": 1259, "pot": 90, "pot_after": 90, "pot_before": 30, "reason": null, "seat": 3, "stack": 1199, "stack_after": 1199, "stack_before": 1259, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10489, "to_call_before": 20, "ts": "2026-10-13T05:49:36.122404+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 5, "big_blind": 20, "board": [], "dealer_seat": 0, "hand_id": "153bc60e-0a6b-4691-b52c-93f35126db40", "hand_seq": 22, "hero": {"hole_cards": ["Kh", "Td"], "seat": 3}, "pot": 90, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6479, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2976, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2293, "status": "active"}, {"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1199, "status": "active"}, {"bet": 0, "is_pro": false, "seat": 4, "stack": 0, "status": "empty"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:dd25a618bb0cd844d40710438fd546857aa1fb973df7958c3500bc25c2e53ec2", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10490, "ts": "2026-10-13T05:49:36.123152+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "4c2d1944-50cf-49cb-8805-0030c76e2253", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "153bc60e-0a6b-4691-b52c-93f35126db40", "hand_seq": 27, "name": "player_2", "player_stack_after": 2918, "player_stack_before": 2918, "pot": 90, "pot_after": 90, "pot_before": 90, "reason": null, "seat": 5, "stack": 2918, "stack_after": 2918, "stack_before": 2918, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10495, "to_call_before": 60, "ts": "2026-10-13T05:49:39.395473+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": [], "dealer_seat": 0, "hand_id": "153bc60e-0a6b-4691-b52c-93f35126db40", "hand_seq": 28, "hero": {"hole_cards": ["Kh", "Td"], "seat": 3}, "pot": 90, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6479, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2976, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2293, "status": "active"}, {"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1199, "status": "active"}, {"bet": 0, "is_pro": false, "seat": 4, "stack": 0, "status": "empty"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:2c656a2abe64d1b0c91471361769c5033336d0279dbb3ad37feeae0e01c45bc4", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10496, "ts": "2026-10-13T05:49:39.396873+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "call", "action_id": "9d839ffb-7ff6-4ea3-b798-7e1744978866", "amount": null, "amount_mode": "incremental", "contribution_delta": 60, "hand_id": "153bc60e-0a6b-4691-b52c-93f35126db40", "hand_seq": 33, "name": "player_1", "player_stack_after": 6419, "player_stack_before": 6479, "pot": 150, "pot_after": 150, "pot_before": 90, "reason": null, "seat": 0, "stack": 6419, "stack_after": 6419, "stack_before": 6479, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10501, "to_call_before": 60, "ts": "2026-10-13T05:49:42.693291+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 1, "big_blind": 20, "board": [], "dealer_seat": 0, "hand_id": "153bc60e-0a6b-4691-b52c-93f35126db40", "hand_seq": 34, "hero": {"hole_cards": ["Kh", "Td"], "seat": 3}, "pot": 150, "seats": [{"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6419, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2976, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2293, "status": "active"}, {"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1199, "status": "active"}, {"bet": 0, "is_pro": false, "seat": 4, "stack": 0, "status": "empty"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:6f78c347a90c0a2108bc95661da4055fbca970eb94501d4b74e156cf32ada9c1", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10502, "ts": "2026-10-13T05:49:42.694641+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "raise", "action_id": "95a139fd-8bc9-436e-8299-a75d076e8206", "amount": 280, "amount_mode": "to_total", "contribution_delta": 270, "hand_id": "153bc60e-0a6b-4691-b52c-93f35126db40", "hand_seq": 39, "name": "player_6", "player_stack_after": 2706, "player_stack_before": 2976, "pot": 420, "pot_after": 420, "pot_before": 150, "reason": null, "seat": 1, "stack": 2706, "stack_after": 2706, "stack_before": 2976, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10507, "to_call_before": 50, "ts": "2026-10-13T05:49:47.853594+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 2, "big_blind": 20, "board": [], "dealer_seat": 0, "hand_id": "153bc60e-0a6b-4691-b52c-93f35126db40", "hand_seq": 40, "hero": {"hole_cards": ["Kh", "Td"], "seat": 3}, "pot": 420, "seats": [{"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6419, "status": "active"}, {"bet": 280, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2706, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2293, "status": "active"}, {"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1199, "status": "active"}, {"bet": 0, "is_pro": false, "seat": 4, "stack": 0, "status": "empty"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:98fd3ac42d328238fd08892968aeabd8310798ba094fce24da44438cd2ce6b23", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10508, "ts": "2026-10-13T05:49:47.854320+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "oc-5482a09cad4f-57", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "153bc60e-0a6b-4691-b52c-93f35126db40", "hand_seq": 45, "name": "player_3", "player_stack_after": 2293, "player_stack_before": 2293, "pot": 420, "pot_after": 420, "pot_before": 420, "reason": null, "seat": 2, "stack": 2293, "stack_after": 2293, "stack_before": 2293, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10513, "to_call_before": 260, "ts": "2026-10-13T05:49:50.937905+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": [], "dealer_seat": 0, "hand_id": "153bc60e-0a6b-4691-b52c-93f35126db40", "hand_seq": 46, "hero": {"hole_cards": ["Kh", "Td"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 220}, {"action": "raise", "max": 1259, "min": 500}, {"action": "all_in", "amount": 1259}]}, "max_raise_to": 1259, "min_raise_to": 500, "pot": 420, "seats": [{"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6419, "status": "active"}, {"bet": 280, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2706, "status": "active"}, {"bet": 20, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2293, "status": "active"}, {"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1199, "status": "active"}, {"bet": 0, "is_pro": false, "seat": 4, "stack": 0, "status": "empty"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:6a055784b392c954528bbd80359a0b471209fa6997129914309d7e5262c9ebb1", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10514, "to_call": 220, "ts": "2026-10-13T05:49:50.938809+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"community_cards": [], "hand_id": "153bc60e-0a6b-4691-b52c-93f35126db40", "hand_seq": 47, "max_raise": 1259, "min_raise": 500, "players": [{"avatar_url": null, "is_pro": false, "name": "player_1", "public_profile_slug": null, "seat": 0, "stack": 6419}, {"avatar_url": null, "is_pro": false, "name": "player_6", "public_profile_slug": null, "seat": 1, "stack": 2706}, {"avatar_url": null, "is_pro": false, "name": "player_3", "public_profile_slug": null, "seat": 2, "stack": 2293}, {"avatar_url": null, "is_pro": false, "name": "hero_bot", "public_profile_slug": null, "seat": 3, "stack": 1199}, {"avatar_url": null, "is_pro": false, "name": "player_2", "public_profile_slug": null, "seat": 5, "stack": 2918}], "pot": 420, "seat": 3, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10515, "ts": "2026-10-13T05:49:53.946794+00:00", "turn_token": "0b4996f0-6c94-43b3-8bc0-8c2c9a89c619", "type": "your_turn", "valid_actions": [{"action": "fold", "amount": null, "max": null, "min": null}, {"action": "call", "amount": 220, "max": null, "min": null}, {"action": "raise", "amount": null, "max": 1259, "min": 500}, {"action": "all_in", "amount": 1259, "max": null, "min": null}]}} +{"dir": "out", "msg": {"action": "fold", "client_action_id": "plu-6-11", "hand_id": "153bc60e-0a6b-4691-b52c-93f35126db40", "turn_token": "0b4996f0-6c94-43b3-8bc0-8c2c9a89c619", "type": "action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": [], "dealer_seat": 0, "hand_id": "153bc60e-0a6b-4691-b52c-93f35126db40", "hand_seq": 48, "hero": {"hole_cards": ["Kh", "Td"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 220}, {"action": "raise", "max": 1259, "min": 500}, {"action": "all_in", "amount": 1259}]}, "max_raise_to": 1259, "min_raise_to": 500, "pot": 420, "seats": [{"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6419, "status": "active"}, {"bet": 280, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2706, "status": "active"}, {"bet": 20, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2293, "status": "active"}, {"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1199, "status": "active"}, {"bet": 0, "is_pro": false, "seat": 4, "stack": 0, "status": "empty"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:6a055784b392c954528bbd80359a0b471209fa6997129914309d7e5262c9ebb1", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10516, "to_call": 220, "ts": "2026-10-13T05:49:53.947209+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"client_action_id": "plu-6-11", "hand_id": "153bc60e-0a6b-4691-b52c-93f35126db40", "hand_seq": 50, "status": "accepted", "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10518, "ts": "2026-10-13T05:49:54.101512+00:00", "type": "action_ack"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "plu-6-11", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "153bc60e-0a6b-4691-b52c-93f35126db40", "hand_seq": 51, "name": "hero_bot", "player_stack_after": 1199, "player_stack_before": 1199, "pot": 420, "pot_after": 420, "pot_before": 420, "reason": null, "seat": 3, "stack": 1199, "stack_after": 1199, "stack_before": 1199, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10519, "to_call_before": 220, "ts": "2026-10-13T05:49:54.105140+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": [], "dealer_seat": 0, "hand_id": "153bc60e-0a6b-4691-b52c-93f35126db40", "hand_seq": 52, "hero": {"hole_cards": ["Kh", "Td"], "seat": 3}, "pot": 420, "seats": [{"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6419, "status": "active"}, {"bet": 280, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2706, "status": "active"}, {"bet": 20, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2293, "status": "active"}, {"bet": 60, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1199, "status": "active"}, {"bet": 0, "is_pro": false, "seat": 4, "stack": 0, "status": "empty"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:c604f9c8c7d82e00210b83ee360e16c740981ed376083576b7565112ef5e51c0", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10520, "ts": "2026-10-13T05:49:54.105784+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "af68a8c5-c29c-4dde-a38b-75ed0eb7eeb8", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "153bc60e-0a6b-4691-b52c-93f35126db40", "hand_seq": 57, "name": "player_1", "player_stack_after": 6419, "player_stack_before": 6419, "pot": 420, "pot_after": 420, "pot_before": 420, "reason": null, "seat": 0, "stack": 6419, "stack_after": 6419, "stack_before": 6419, "state_hash": null, "stream": "event", "street": "showdown", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10525, "to_call_before": 220, "ts": "2026-10-13T05:49:57.338570+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"big_blind": 20, "board": [], "dealer_seat": 0, "hand_id": "153bc60e-0a6b-4691-b52c-93f35126db40", "hand_seq": 58, "hero": {"hole_cards": ["Kh", "Td"], "seat": 3}, "pot": 0, "seats": [{"bet": 0, "in_hand": false, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6419, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 3126, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2293, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1199, "status": "active"}, {"bet": 0, "is_pro": false, "seat": 4, "stack": 0, "status": "empty"}, {"avatar_url": "/avatar.webp", "bet": 0, "in_hand": false, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:52e837fb9d359bf50c70e8508c73cf0f90810fad4e5c3c32bd9954d95b465159", "stream": "state", "street": "idle", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10526, "ts": "2026-10-13T05:49:57.339703+00:00", "type": "table_state", "waiting_details": {"active_players": 5, "away_players": 0, "connected_players": 5, "disconnected_players": 0, "eligible_players": 5, "min_required": 2, "player_count": 5}, "waiting_reason": "awaiting_hand_start"}} +{"dir": "in", "msg": {"actions": [{"action": "raise", "amount": 60, "seat": 3, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 5, "street": "preflop"}, {"action": "call", "amount": null, "seat": 0, "street": "preflop"}, {"action": "raise", "amount": 280, "seat": 1, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 2, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 3, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 0, "street": "preflop"}], "final_stacks": {"0": 6419, "1": 3126, "2": 2293, "3": 1199, "5": 2918}, "hand_id": "153bc60e-0a6b-4691-b52c-93f35126db40", "hand_seq": 59, "outcome_kind": "win", "payouts": [{"amount": 200, "seat": 1}], "pot": 140, "pot_kind": "transferable", "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10527, "total_pot": 200, "transferable_pot": 140, "ts": "2026-10-13T05:49:57.418422+00:00", "type": "hand_result", "winners": [{"amount": 140, "hand_description": null, "name": "player_6", "seat": 1, "stack": 3126}]}} +{"dir": "in", "msg": {"hand_id": "153bc60e-0a6b-4691-b52c-93f35126db40", "hand_seq": 61, "name": "player_6", "reason": "left", "seat": 1, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10529, "ts": "2026-10-13T05:49:57.564785+00:00", "type": "player_left"}} +{"dir": "in", "msg": {"avatar": null, "avatar_url": null, "hand_id": "153bc60e-0a6b-4691-b52c-93f35126db40", "hand_seq": 64, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2986, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10532, "ts": "2026-10-13T05:49:59.071745+00:00", "type": "player_joined"}} +{"dir": "in", "msg": {"blinds": {"big_blind": 20, "small_blind": 10}, "dealer_seat": 1, "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 4, "seat": 3, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10536, "ts": "2026-10-13T05:49:59.095182+00:00", "type": "hand_start"}} +{"dir": "in", "msg": {"cards": ["Ah", "7c"], "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 8, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10540, "ts": "2026-10-13T05:49:59.101502+00:00", "type": "hole_cards"}} +{"dir": "in", "msg": {"actor_seat": 5, "big_blind": 20, "board": [], "dealer_seat": 1, "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 9, "hero": {"hole_cards": ["Ah", "7c"], "seat": 3}, "pot": 30, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6419, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2986, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2283, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1179, "status": "active"}, {"bet": 0, "is_pro": false, "seat": 4, "stack": 0, "status": "empty"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:0d2ffa6f8cf3641f6a42dc464430a6270bf15d9f2324fb79b774df63643c8d7b", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10541, "ts": "2026-10-13T05:49:59.101701+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "ac543177-5901-4144-bfdb-0b6fb4d5f859", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 21, "name": "player_2", "player_stack_after": 2918, "player_stack_before": 2918, "pot": 30, "pot_after": 30, "pot_before": 30, "reason": null, "seat": 5, "stack": 2918, "stack_after": 2918, "stack_before": 2918, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10553, "to_call_before": 20, "ts": "2026-10-13T05:50:02.602107+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": [], "dealer_seat": 1, "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 22, "hero": {"hole_cards": ["Ah", "7c"], "seat": 3}, "pot": 30, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6419, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2986, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2283, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1179, "status": "active"}, {"bet": 0, "is_pro": false, "seat": 4, "stack": 0, "status": "empty"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:0e0c730542ba94def85e8960261a0ec6fcda07afc7b1528efefd53c0b8dc95b7", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10554, "ts": "2026-10-13T05:50:02.603181+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "call", "action_id": "0aeb5f6d-ae07-4540-97f4-8caf1e9ceddb", "amount": null, "amount_mode": "incremental", "contribution_delta": 20, "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 27, "name": "player_1", "player_stack_after": 6399, "player_stack_before": 6419, "pot": 50, "pot_after": 50, "pot_before": 30, "reason": null, "seat": 0, "stack": 6399, "stack_after": 6399, "stack_before": 6419, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10559, "to_call_before": 20, "ts": "2026-10-13T05:50:05.876839+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 1, "big_blind": 20, "board": [], "dealer_seat": 1, "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 28, "hero": {"hole_cards": ["Ah", "7c"], "seat": 3}, "pot": 50, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6399, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2986, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2283, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1179, "status": "active"}, {"bet": 0, "is_pro": false, "seat": 4, "stack": 0, "status": "empty"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:7213cae58eb7babe318e2c515984e86d70c339a15347b311d0daef9f7eac4bdc", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10560, "ts": "2026-10-13T05:50:05.877772+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "raise", "action_id": "30909320-c3d7-49a6-8b34-a84c406ed44d", "amount": 70, "amount_mode": "to_total", "contribution_delta": 70, "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 33, "name": "player_6", "player_stack_after": 2916, "player_stack_before": 2986, "pot": 120, "pot_after": 120, "pot_before": 50, "reason": null, "seat": 1, "stack": 2916, "stack_after": 2916, "stack_before": 2986, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10565, "to_call_before": 20, "ts": "2026-10-13T05:50:09.931866+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 2, "big_blind": 20, "board": [], "dealer_seat": 1, "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 34, "hero": {"hole_cards": ["Ah", "7c"], "seat": 3}, "pot": 120, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6399, "status": "active"}, {"bet": 70, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2916, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2283, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1179, "status": "active"}, {"bet": 0, "is_pro": false, "seat": 4, "stack": 0, "status": "empty"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:2445b57da4993703d1398e68764baefac544b958fb3c9a73cacdc248920efe26", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10566, "ts": "2026-10-13T05:50:09.932765+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "oc-ee4e1f18e80d-58", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 39, "name": "player_3", "player_stack_after": 2283, "player_stack_before": 2283, "pot": 120, "pot_after": 120, "pot_before": 120, "reason": null, "seat": 2, "stack": 2283, "stack_after": 2283, "stack_before": 2283, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10571, "to_call_before": 60, "ts": "2026-10-13T05:50:13.015389+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": [], "dealer_seat": 1, "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 40, "hero": {"hole_cards": ["Ah", "7c"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 50}, {"action": "raise", "max": 1199, "min": 120}, {"action": "all_in", "amount": 1199}]}, "max_raise_to": 1199, "min_raise_to": 120, "pot": 120, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6399, "status": "active"}, {"bet": 70, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2916, "status": "active"}, {"bet": 10, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2283, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1179, "status": "active"}, {"bet": 0, "is_pro": false, "seat": 4, "stack": 0, "status": "empty"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:038bdd1263b3527290038ca0d57799e5aad518e0e2679e0c70f664d9aa8c99b2", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10572, "to_call": 50, "ts": "2026-10-13T05:50:13.016548+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"community_cards": [], "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 41, "max_raise": 1199, "min_raise": 120, "players": [{"avatar_url": null, "is_pro": false, "name": "player_1", "public_profile_slug": null, "seat": 0, "stack": 6399}, {"avatar_url": null, "is_pro": false, "name": "player_6", "public_profile_slug": null, "seat": 1, "stack": 2916}, {"avatar_url": null, "is_pro": false, "name": "player_3", "public_profile_slug": null, "seat": 2, "stack": 2283}, {"avatar_url": null, "is_pro": false, "name": "hero_bot", "public_profile_slug": null, "seat": 3, "stack": 1179}, {"avatar_url": null, "is_pro": false, "name": "player_2", "public_profile_slug": null, "seat": 5, "stack": 2918}], "pot": 120, "seat": 3, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10573, "ts": "2026-10-13T05:50:16.019426+00:00", "turn_token": "c24635fa-41c0-4cbd-a734-647641b102d4", "type": "your_turn", "valid_actions": [{"action": "fold", "amount": null, "max": null, "min": null}, {"action": "call", "amount": 50, "max": null, "min": null}, {"action": "raise", "amount": null, "max": 1199, "min": 120}, {"action": "all_in", "amount": 1199, "max": null, "min": null}]}} +{"dir": "out", "msg": {"action": "fold", "client_action_id": "plu-7-12", "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "turn_token": "c24635fa-41c0-4cbd-a734-647641b102d4", "type": "action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": [], "dealer_seat": 1, "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 42, "hero": {"hole_cards": ["Ah", "7c"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 50}, {"action": "raise", "max": 1199, "min": 120}, {"action": "all_in", "amount": 1199}]}, "max_raise_to": 1199, "min_raise_to": 120, "pot": 120, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6399, "status": "active"}, {"bet": 70, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2916, "status": "active"}, {"bet": 10, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2283, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1179, "status": "active"}, {"bet": 0, "is_pro": false, "seat": 4, "stack": 0, "status": "empty"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:038bdd1263b3527290038ca0d57799e5aad518e0e2679e0c70f664d9aa8c99b2", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10574, "to_call": 50, "ts": "2026-10-13T05:50:16.019912+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"client_action_id": "plu-7-12", "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 44, "status": "accepted", "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10576, "ts": "2026-10-13T05:50:16.174291+00:00", "type": "action_ack"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "plu-7-12", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 45, "name": "hero_bot", "player_stack_after": 1179, "player_stack_before": 1179, "pot": 120, "pot_after": 120, "pot_before": 120, "reason": null, "seat": 3, "stack": 1179, "stack_after": 1179, "stack_before": 1179, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10577, "to_call_before": 50, "ts": "2026-10-13T05:50:16.177191+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": [], "dealer_seat": 1, "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 46, "hero": {"hole_cards": ["Ah", "7c"], "seat": 3}, "pot": 120, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6399, "status": "active"}, {"bet": 70, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2916, "status": "active"}, {"bet": 10, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2283, "status": "active"}, {"bet": 20, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1179, "status": "active"}, {"bet": 0, "is_pro": false, "seat": 4, "stack": 0, "status": "empty"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:99204272dad2e45c1a82b2c4ed71d17f8d2970f3c4c3a77acf34edc9cec878ca", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10578, "ts": "2026-10-13T05:50:16.177827+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "call", "action_id": "0732d579-61df-43cb-909b-affb46ed73e7", "amount": null, "amount_mode": "incremental", "contribution_delta": 50, "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 51, "name": "player_1", "player_stack_after": 6349, "player_stack_before": 6399, "pot": 170, "pot_after": 170, "pot_before": 120, "reason": null, "seat": 0, "stack": 6349, "stack_after": 6349, "stack_before": 6399, "state_hash": null, "stream": "event", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10583, "to_call_before": 50, "ts": "2026-10-13T05:50:19.413654+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": [], "dealer_seat": 1, "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 52, "hero": {"hole_cards": ["Ah", "7c"], "seat": 3}, "pot": 170, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6349, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2916, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2283, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1179, "status": "active"}, {"bet": 0, "is_pro": false, "seat": 4, "stack": 0, "status": "empty"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:7dd33fec88e063a1dfcf36bfe7265216b47cab65208087099434bb0eacf2bf04", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10584, "ts": "2026-10-13T05:50:19.415685+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"cards": ["Qc", "7d", "Td"], "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 53, "state_hash": null, "stream": "event", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10585, "ts": "2026-10-13T05:50:22.454445+00:00", "type": "community_cards"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": ["Qc", "7d", "Td"], "dealer_seat": 1, "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 54, "hero": {"hole_cards": ["Ah", "7c"], "seat": 3}, "pot": 170, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6349, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2916, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2283, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1179, "status": "active"}, {"bet": 0, "is_pro": false, "seat": 4, "stack": 0, "status": "empty"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:ef1bd3ef12c4e931ca2083091cbec816a9b3d9968c336a0bde9e7b550743de67", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10586, "ts": "2026-10-13T05:50:22.455171+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "raise", "action_id": "590968aa-f3a9-4ad5-826c-578fe442d350", "amount": 56, "amount_mode": "to_total", "contribution_delta": 56, "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 59, "name": "player_1", "player_stack_after": 6293, "player_stack_before": 6349, "pot": 226, "pot_after": 226, "pot_before": 170, "reason": null, "seat": 0, "stack": 6293, "stack_after": 6293, "stack_before": 6349, "state_hash": null, "stream": "event", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10591, "to_call_before": null, "ts": "2026-10-13T05:50:22.960139+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 1, "big_blind": 20, "board": ["Qc", "7d", "Td"], "dealer_seat": 1, "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 60, "hero": {"hole_cards": ["Ah", "7c"], "seat": 3}, "pot": 226, "seats": [{"bet": 56, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6293, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2916, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2283, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1179, "status": "active"}, {"bet": 0, "is_pro": false, "seat": 4, "stack": 0, "status": "empty"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:2617c85c5f62a680770727e447f9e761add7eef6fdad19176dadd198d9b0ae7b", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10592, "ts": "2026-10-13T05:50:22.981702+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "call", "action_id": "3a006904-8f06-4bd1-8161-4925c4d7824e", "amount": null, "amount_mode": "incremental", "contribution_delta": 56, "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 65, "name": "player_6", "player_stack_after": 2860, "player_stack_before": 2916, "pot": 282, "pot_after": 282, "pot_before": 226, "reason": null, "seat": 1, "stack": 2860, "stack_after": 2860, "stack_before": 2916, "state_hash": null, "stream": "event", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10597, "to_call_before": 56, "ts": "2026-10-13T05:50:26.662522+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": ["Qc", "7d", "Td"], "dealer_seat": 1, "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 66, "hero": {"hole_cards": ["Ah", "7c"], "seat": 3}, "pot": 282, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6293, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2860, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2283, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1179, "status": "active"}, {"bet": 0, "is_pro": false, "seat": 4, "stack": 0, "status": "empty"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:04562feafea1ba0002cda04f55949316a8c47e6e88f6796c8be5b36a3d974cfc", "stream": "state", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10598, "ts": "2026-10-13T05:50:26.663544+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"cards": ["Qc", "7d", "Td", "9h"], "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 67, "state_hash": null, "stream": "event", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10599, "ts": "2026-10-13T05:50:29.666272+00:00", "type": "community_cards"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": ["Qc", "7d", "Td", "9h"], "dealer_seat": 1, "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 68, "hero": {"hole_cards": ["Ah", "7c"], "seat": 3}, "pot": 282, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6293, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2860, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2283, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1179, "status": "active"}, {"bet": 0, "is_pro": false, "seat": 4, "stack": 0, "status": "empty"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:4fe506e658b14645d8a67809c45b8e8cd1f2209c3f7c9e7c1218f6afbcc984a3", "stream": "state", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10600, "ts": "2026-10-13T05:50:29.667830+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "raise", "action_id": "69c04e0e-5882-47e0-b50b-fb4fa70ea708", "amount": 282, "amount_mode": "to_total", "contribution_delta": 282, "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 73, "name": "player_1", "player_stack_after": 6011, "player_stack_before": 6293, "pot": 564, "pot_after": 564, "pot_before": 282, "reason": null, "seat": 0, "stack": 6011, "stack_after": 6011, "stack_before": 6293, "state_hash": null, "stream": "event", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10605, "to_call_before": null, "ts": "2026-10-13T05:50:29.939149+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 1, "big_blind": 20, "board": ["Qc", "7d", "Td", "9h"], "dealer_seat": 1, "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 74, "hero": {"hole_cards": ["Ah", "7c"], "seat": 3}, "pot": 564, "seats": [{"bet": 282, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6011, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2860, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2283, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1179, "status": "active"}, {"bet": 0, "is_pro": false, "seat": 4, "stack": 0, "status": "empty"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:55744b32e5141f53c2e8173954cf1f07c2a12c1cfc08a6f6ba8fc71090be7e5a", "stream": "state", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10606, "ts": "2026-10-13T05:50:29.940055+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "00fb00ef-6389-4f41-8ddf-c16daccc051d", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 79, "name": "player_6", "player_stack_after": 2860, "player_stack_before": 2860, "pot": 564, "pot_after": 564, "pot_before": 564, "reason": null, "seat": 1, "stack": 2860, "stack_after": 2860, "stack_before": 2860, "state_hash": null, "stream": "event", "street": "showdown", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10611, "to_call_before": 282, "ts": "2026-10-13T05:50:34.163954+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"big_blind": 20, "board": ["Qc", "7d", "Td", "9h"], "dealer_seat": 1, "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 80, "hero": {"hole_cards": ["Ah", "7c"], "seat": 3}, "pot": 0, "seats": [{"bet": 0, "in_hand": false, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6575, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2860, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2283, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1179, "status": "active"}, {"bet": 0, "is_pro": false, "seat": 4, "stack": 0, "status": "empty"}, {"avatar_url": "/avatar.webp", "bet": 0, "in_hand": false, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:b6336d07c35b0109bbb11ed24e199e9ebe470b1e09bfc7d2bdedccef441d235c", "stream": "state", "street": "idle", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10612, "ts": "2026-10-13T05:50:34.164805+00:00", "type": "table_state", "waiting_details": {"active_players": 5, "away_players": 0, "connected_players": 5, "disconnected_players": 0, "eligible_players": 5, "min_required": 2, "player_count": 5}, "waiting_reason": "awaiting_hand_start"}} +{"dir": "in", "msg": {"actions": [{"action": "fold", "amount": null, "seat": 5, "street": "preflop"}, {"action": "call", "amount": null, "seat": 0, "street": "preflop"}, {"action": "raise", "amount": 70, "seat": 1, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 2, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 3, "street": "preflop"}, {"action": "call", "amount": null, "seat": 0, "street": "preflop"}, {"action": "raise", "amount": 56, "seat": 0, "street": "flop"}, {"action": "call", "amount": null, "seat": 1, "street": "flop"}, {"action": "raise", "amount": 282, "seat": 0, "street": "turn"}, {"action": "fold", "amount": null, "seat": 1, "street": "turn"}], "final_stacks": {"0": 6575, "1": 2860, "2": 2283, "3": 1179, "5": 2918}, "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 81, "outcome_kind": "win", "payouts": [{"amount": 282, "seat": 0}], "pot": 156, "pot_kind": "transferable", "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10613, "total_pot": 282, "transferable_pot": 156, "ts": "2026-10-13T05:50:34.222092+00:00", "type": "hand_result", "winners": [{"amount": 156, "hand_description": null, "name": "player_1", "seat": 0, "stack": 6575}]}} +{"dir": "in", "msg": {"avatar": null, "avatar_url": null, "hand_id": "615d19f3-5ce3-497f-b2ac-b1f7f51903eb", "hand_seq": 84, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1500, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10616, "ts": "2026-10-13T05:50:39.213204+00:00", "type": "player_joined"}} +{"dir": "in", "msg": {"blinds": {"big_blind": 20, "small_blind": 10}, "dealer_seat": 2, "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 4, "seat": 3, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10620, "ts": "2026-10-13T05:50:39.232971+00:00", "type": "hand_start"}} +{"dir": "in", "msg": {"cards": ["8c", "8s"], "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 7, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10623, "ts": "2026-10-13T05:50:39.238940+00:00", "type": "hole_cards"}} +{"dir": "in", "msg": {"actor_seat": 5, "big_blind": 20, "board": [], "dealer_seat": 2, "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 8, "hero": {"hole_cards": ["8c", "8s"], "seat": 3}, "pot": 30, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6575, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2860, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2283, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1169, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1480, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2918, "status": "active"}], "small_blind": 10, "state_hash": "sha256:9af3f96a53d96b4c7718a750fcf2f176de214ba064325f7a2027a0eb596c0a29", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10624, "ts": "2026-10-13T05:50:39.239179+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "raise", "action_id": "584770c6-0533-48a5-8caa-3f1b514212b8", "amount": 60, "amount_mode": "to_total", "contribution_delta": 60, "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 24, "name": "player_2", "player_stack_after": 2858, "player_stack_before": 2918, "pot": 90, "pot_after": 90, "pot_before": 30, "reason": null, "seat": 5, "stack": 2858, "stack_after": 2858, "stack_before": 2918, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10640, "to_call_before": 20, "ts": "2026-10-13T05:50:42.542254+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": [], "dealer_seat": 2, "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 25, "hero": {"hole_cards": ["8c", "8s"], "seat": 3}, "pot": 90, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6575, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2860, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2283, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1169, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1480, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2858, "status": "active"}], "small_blind": 10, "state_hash": "sha256:ae5836f603d418247d09bef94ff4ee29c2530550a61b24ae91f691a66d0d457a", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10641, "ts": "2026-10-13T05:50:42.543518+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "call", "action_id": "f0d3a5d1-6510-44f7-92a2-b8a91fec72be", "amount": null, "amount_mode": "incremental", "contribution_delta": 60, "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 30, "name": "player_1", "player_stack_after": 6515, "player_stack_before": 6575, "pot": 150, "pot_after": 150, "pot_before": 90, "reason": null, "seat": 0, "stack": 6515, "stack_after": 6515, "stack_before": 6575, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10646, "to_call_before": 60, "ts": "2026-10-13T05:50:45.946207+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 1, "big_blind": 20, "board": [], "dealer_seat": 2, "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 31, "hero": {"hole_cards": ["8c", "8s"], "seat": 3}, "pot": 150, "seats": [{"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6515, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2860, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2283, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1169, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1480, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2858, "status": "active"}], "small_blind": 10, "state_hash": "sha256:cce7c3680ca8b3f5caf3fa6a768a80df70762fb43ebca020b6687a63f94334a8", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10647, "ts": "2026-10-13T05:50:45.946982+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "6d744746-870c-4820-9167-4f94212ea947", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 36, "name": "player_6", "player_stack_after": 2860, "player_stack_before": 2860, "pot": 150, "pot_after": 150, "pot_before": 150, "reason": null, "seat": 1, "stack": 2860, "stack_after": 2860, "stack_before": 2860, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10652, "to_call_before": 60, "ts": "2026-10-13T05:50:49.453045+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 2, "big_blind": 20, "board": [], "dealer_seat": 2, "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 37, "hero": {"hole_cards": ["8c", "8s"], "seat": 3}, "pot": 150, "seats": [{"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6515, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2860, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2283, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1169, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1480, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2858, "status": "active"}], "small_blind": 10, "state_hash": "sha256:87ec27865bf234bc8ea2e7bffc5537c3e2edac9fd2fe2245961549811b749e9f", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10653, "ts": "2026-10-13T05:50:49.454024+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "call", "action_id": "oc-bd6230ab9d87-59", "amount": null, "amount_mode": "incremental", "contribution_delta": 60, "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 42, "name": "player_3", "player_stack_after": 2223, "player_stack_before": 2283, "pot": 210, "pot_after": 210, "pot_before": 150, "reason": null, "seat": 2, "stack": 2223, "stack_after": 2223, "stack_before": 2283, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10658, "to_call_before": 60, "ts": "2026-10-13T05:50:52.590400+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": [], "dealer_seat": 2, "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 43, "hero": {"hole_cards": ["8c", "8s"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 50}, {"action": "raise", "max": 1179, "min": 100}, {"action": "all_in", "amount": 1179}]}, "max_raise_to": 1179, "min_raise_to": 100, "pot": 210, "seats": [{"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6515, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2860, "status": "active"}, {"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1169, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1480, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2858, "status": "active"}], "small_blind": 10, "state_hash": "sha256:0c730bb64abb2587cae80b34529bab180d84be53c7323bcfc39bdcec8522f9cc", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10659, "to_call": 50, "ts": "2026-10-13T05:50:52.608804+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"community_cards": [], "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 44, "max_raise": 1179, "min_raise": 100, "players": [{"avatar_url": null, "is_pro": false, "name": "player_1", "public_profile_slug": null, "seat": 0, "stack": 6515}, {"avatar_url": null, "is_pro": false, "name": "player_6", "public_profile_slug": null, "seat": 1, "stack": 2860}, {"avatar_url": null, "is_pro": false, "name": "player_3", "public_profile_slug": null, "seat": 2, "stack": 2223}, {"avatar_url": null, "is_pro": false, "name": "hero_bot", "public_profile_slug": null, "seat": 3, "stack": 1169}, {"avatar_url": null, "is_pro": false, "name": "player_7", "public_profile_slug": null, "seat": 4, "stack": 1480}, {"avatar_url": null, "is_pro": false, "name": "player_2", "public_profile_slug": null, "seat": 5, "stack": 2858}], "pot": 210, "seat": 3, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10660, "ts": "2026-10-13T05:50:55.633211+00:00", "turn_token": "50f655df-8407-4199-bbed-18f41431fefb", "type": "your_turn", "valid_actions": [{"action": "fold", "amount": null, "max": null, "min": null}, {"action": "call", "amount": 50, "max": null, "min": null}, {"action": "raise", "amount": null, "max": 1179, "min": 100}, {"action": "all_in", "amount": 1179, "max": null, "min": null}]}} +{"dir": "out", "msg": {"action": "raise", "amount": 180, "client_action_id": "plu-8-13", "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "turn_token": "50f655df-8407-4199-bbed-18f41431fefb", "type": "action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": [], "dealer_seat": 2, "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 45, "hero": {"hole_cards": ["8c", "8s"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 50}, {"action": "raise", "max": 1179, "min": 100}, {"action": "all_in", "amount": 1179}]}, "max_raise_to": 1179, "min_raise_to": 100, "pot": 210, "seats": [{"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6515, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2860, "status": "active"}, {"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 1169, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1480, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2858, "status": "active"}], "small_blind": 10, "state_hash": "sha256:0c730bb64abb2587cae80b34529bab180d84be53c7323bcfc39bdcec8522f9cc", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10661, "to_call": 50, "ts": "2026-10-13T05:50:55.633770+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"client_action_id": "plu-8-13", "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 47, "status": "accepted", "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10663, "ts": "2026-10-13T05:50:55.788200+00:00", "type": "action_ack"}} +{"dir": "in", "msg": {"action": "raise", "action_id": "plu-8-13", "amount": 180, "amount_mode": "to_total", "contribution_delta": 170, "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 48, "name": "hero_bot", "player_stack_after": 999, "player_stack_before": 1169, "pot": 380, "pot_after": 380, "pot_before": 210, "reason": null, "seat": 3, "stack": 999, "stack_after": 999, "stack_before": 1169, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10664, "to_call_before": 50, "ts": "2026-10-13T05:50:55.791334+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 4, "big_blind": 20, "board": [], "dealer_seat": 2, "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 49, "hero": {"hole_cards": ["8c", "8s"], "seat": 3}, "pot": 380, "seats": [{"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6515, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2860, "status": "active"}, {"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 180, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 999, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1480, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2858, "status": "active"}], "small_blind": 10, "state_hash": "sha256:ea65a1d8a7d209535912e2945fdfa87daa06a782c4a6e74bfb664658d1f7284e", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10665, "ts": "2026-10-13T05:50:55.792169+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "634858ea-11c9-4012-9af4-88b0aa2ffa29", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 54, "name": "player_7", "player_stack_after": 1480, "player_stack_before": 1480, "pot": 380, "pot_after": 380, "pot_before": 380, "reason": null, "seat": 4, "stack": 1480, "stack_after": 1480, "stack_before": 1480, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10670, "to_call_before": 160, "ts": "2026-10-13T05:50:58.800705+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 5, "big_blind": 20, "board": [], "dealer_seat": 2, "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 55, "hero": {"hole_cards": ["8c", "8s"], "seat": 3}, "pot": 380, "seats": [{"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6515, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2860, "status": "active"}, {"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 180, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 999, "status": "active"}, {"bet": 20, "folded": true, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1480, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 2858, "status": "active"}], "small_blind": 10, "state_hash": "sha256:e716a7a56acda7d0f79689c8b9f1883f50fb987886c33fbc40aa96e91302431d", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10671, "ts": "2026-10-13T05:50:58.801762+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "all_in", "action_id": "90fca31c-b135-48db-a4de-f2f38681e5c3", "amount": null, "amount_mode": "to_total", "contribution_delta": 0, "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 60, "name": "player_2", "player_stack_after": 2858, "player_stack_before": 2858, "pot": 380, "pot_after": 380, "pot_before": 380, "reason": null, "seat": 5, "stack": 2858, "stack_after": 2858, "stack_before": 2858, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10676, "to_call_before": 120, "ts": "2026-10-13T05:51:02.177667+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": [], "dealer_seat": 2, "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 61, "hero": {"hole_cards": ["8c", "8s"], "seat": 3}, "pot": 3238, "seats": [{"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6515, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2860, "status": "active"}, {"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 180, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 999, "status": "active"}, {"bet": 20, "folded": true, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1480, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 2918, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 0, "status": "active"}], "small_blind": 10, "state_hash": "sha256:4eed9866cc122e700f444d5544449a2aadfa935a5b2933105366a89f9cdbfc51", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10677, "ts": "2026-10-13T05:51:02.178707+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "0d0198cb-f766-4d6a-a13b-de8d63c53259", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 66, "name": "player_1", "player_stack_after": 6515, "player_stack_before": 6515, "pot": 3238, "pot_after": 3238, "pot_before": 3238, "reason": null, "seat": 0, "stack": 6515, "stack_after": 6515, "stack_before": 6515, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10682, "to_call_before": 2858, "ts": "2026-10-13T05:51:05.551828+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 2, "big_blind": 20, "board": [], "dealer_seat": 2, "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 67, "hero": {"hole_cards": ["8c", "8s"], "seat": 3}, "pot": 3238, "seats": [{"bet": 60, "folded": true, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6515, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2860, "status": "active"}, {"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 180, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 999, "status": "active"}, {"bet": 20, "folded": true, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1480, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 2918, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 0, "status": "active"}], "small_blind": 10, "state_hash": "sha256:206c02039cad3a1c202fd0c865f7bb0805b487bb466bf0039d1f5abf13dcc862", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10683, "ts": "2026-10-13T05:51:05.552810+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "oc-9fb91971a075-60", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 72, "name": "player_3", "player_stack_after": 2223, "player_stack_before": 2223, "pot": 3238, "pot_after": 3238, "pot_before": 3238, "reason": null, "seat": 2, "stack": 2223, "stack_after": 2223, "stack_before": 2223, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10688, "to_call_before": 2223, "ts": "2026-10-13T05:51:08.635828+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": [], "dealer_seat": 2, "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 73, "hero": {"hole_cards": ["8c", "8s"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 999}]}, "pot": 3238, "seats": [{"bet": 60, "folded": true, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6515, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2860, "status": "active"}, {"bet": 60, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 180, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 999, "status": "active"}, {"bet": 20, "folded": true, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1480, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 2918, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 0, "status": "active"}], "small_blind": 10, "state_hash": "sha256:756389422c217b07b532cccc167a61b3505e80d9ab3aa84615ccc9bcf4636e68", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10689, "to_call": 999, "ts": "2026-10-13T05:51:08.636913+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"community_cards": [], "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 74, "max_raise": null, "min_raise": null, "players": [{"avatar_url": null, "is_pro": false, "name": "player_1", "public_profile_slug": null, "seat": 0, "stack": 6515}, {"avatar_url": null, "is_pro": false, "name": "player_6", "public_profile_slug": null, "seat": 1, "stack": 2860}, {"avatar_url": null, "is_pro": false, "name": "player_3", "public_profile_slug": null, "seat": 2, "stack": 2223}, {"avatar_url": null, "is_pro": false, "name": "hero_bot", "public_profile_slug": null, "seat": 3, "stack": 999}, {"avatar_url": null, "is_pro": false, "name": "player_7", "public_profile_slug": null, "seat": 4, "stack": 1480}, {"avatar_url": null, "is_pro": false, "name": "player_2", "public_profile_slug": null, "seat": 5, "stack": 0}], "pot": 3238, "seat": 3, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10690, "ts": "2026-10-13T05:51:11.640614+00:00", "turn_token": "9a2fa753-6ab8-4aa5-bb54-9d9a6b94060b", "type": "your_turn", "valid_actions": [{"action": "fold", "amount": null, "max": null, "min": null}, {"action": "call", "amount": 999, "max": null, "min": null}]}} +{"dir": "out", "msg": {"action": "call", "client_action_id": "plu-8-14", "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "turn_token": "9a2fa753-6ab8-4aa5-bb54-9d9a6b94060b", "type": "action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": [], "dealer_seat": 2, "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 75, "hero": {"hole_cards": ["8c", "8s"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 999}]}, "pot": 3238, "seats": [{"bet": 60, "folded": true, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6515, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2860, "status": "active"}, {"bet": 60, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 180, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 999, "status": "active"}, {"bet": 20, "folded": true, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1480, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 2918, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 0, "status": "active"}], "small_blind": 10, "state_hash": "sha256:756389422c217b07b532cccc167a61b3505e80d9ab3aa84615ccc9bcf4636e68", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10691, "to_call": 999, "ts": "2026-10-13T05:51:11.641055+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"client_action_id": "plu-8-14", "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 77, "status": "accepted", "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10693, "ts": "2026-10-13T05:51:11.800061+00:00", "type": "action_ack"}} +{"dir": "in", "msg": {"action": "call", "action_id": "plu-8-14", "amount": null, "amount_mode": "incremental", "contribution_delta": 999, "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 78, "name": "hero_bot", "player_stack_after": 0, "player_stack_before": 999, "pot": 4237, "pot_after": 4237, "pot_before": 3238, "reason": null, "seat": 3, "stack": 0, "stack_after": 0, "stack_before": 999, "state_hash": null, "stream": "event", "street": "showdown", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10694, "to_call_before": 999, "ts": "2026-10-13T05:51:11.804836+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"big_blind": 20, "board": [], "dealer_seat": 2, "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 79, "hero": {"hole_cards": ["8c", "8s"], "seat": 3}, "pot": 0, "seats": [{"bet": 0, "in_hand": false, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6515, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2860, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2498, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1480, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "in_hand": false, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1739, "status": "active"}], "small_blind": 10, "state_hash": "sha256:14bee2e8c223a7c1174bc8734d7cdbe90f70a910334253e30d906edcf2b8cdd9", "stream": "state", "street": "idle", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10695, "ts": "2026-10-13T05:51:11.805787+00:00", "type": "table_state", "waiting_details": {"active_players": 6, "away_players": 0, "connected_players": 6, "disconnected_players": 0, "eligible_players": 6, "min_required": 2, "player_count": 6}, "waiting_reason": "awaiting_hand_start"}} +{"dir": "in", "msg": {"cards": ["2d", "7s", "7c"], "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 80, "state_hash": null, "stream": "event", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10696, "ts": "2026-10-13T05:51:11.810695+00:00", "type": "community_cards"}} +{"dir": "in", "msg": {"cards": ["2d", "7s", "7c", "8h"], "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 81, "state_hash": null, "stream": "event", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10697, "ts": "2026-10-13T05:51:11.811654+00:00", "type": "community_cards"}} +{"dir": "in", "msg": {"cards": ["2d", "7s", "7c", "8h", "2c"], "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 82, "state_hash": null, "stream": "event", "street": "river", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10698, "ts": "2026-10-13T05:51:11.812307+00:00", "type": "community_cards"}} +{"dir": "in", "msg": {"big_blind": 20, "board": ["2d", "7s", "7c", "8h", "2c"], "dealer_seat": 2, "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 83, "hero": {"hole_cards": ["8c", "8s"], "seat": 3}, "pot": 0, "seats": [{"bet": 0, "in_hand": false, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6515, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2860, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2498, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1480, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "in_hand": false, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1739, "status": "active"}], "small_blind": 10, "state_hash": "sha256:604e60e887d4dec097ffe0cec88c98f906089ef50c22fb9f853a35b1aedb483c", "stream": "state", "street": "idle", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10699, "ts": "2026-10-13T05:51:11.812825+00:00", "type": "table_state", "waiting_details": {"active_players": 6, "away_players": 0, "connected_players": 6, "disconnected_players": 0, "eligible_players": 6, "min_required": 2, "player_count": 6}, "waiting_reason": "awaiting_hand_start"}} +{"dir": "in", "msg": {"actions": [{"action": "raise", "amount": 60, "seat": 5, "street": "preflop"}, {"action": "call", "amount": null, "seat": 0, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 1, "street": "preflop"}, {"action": "call", "amount": null, "seat": 2, "street": "preflop"}, {"action": "raise", "amount": 180, "seat": 3, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 4, "street": "preflop"}, {"action": "all_in", "amount": null, "seat": 5, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 0, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 2, "street": "preflop"}, {"action": "call", "amount": null, "seat": 3, "street": "preflop"}], "final_stacks": {"0": 6515, "1": 2860, "2": 2223, "3": 2498, "4": 1480, "5": 1739}, "hand_id": "1b347d42-59dc-4d85-aa66-0b9bd396390a", "hand_seq": 84, "outcome_kind": "win", "payouts": [{"amount": 2498, "seat": 3}], "pot": 1319, "pot_kind": "transferable", "shown_cards": {"3": ["8c", "8s"], "5": ["Ad", "Ac"]}, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10700, "total_pot": 2498, "transferable_pot": 1319, "ts": "2026-10-13T05:51:11.877156+00:00", "type": "hand_result", "winners": [{"amount": 1319, "hand_description": "Full house", "name": "hero_bot", "seat": 3, "stack": 2498}]}} +{"dir": "in", "msg": {"blinds": {"big_blind": 20, "small_blind": 10}, "dealer_seat": 3, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 4, "seat": 3, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10704, "ts": "2026-10-13T05:51:16.918137+00:00", "type": "hand_start"}} +{"dir": "in", "msg": {"cards": ["4s", "Td"], "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 17, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10717, "ts": "2026-10-13T05:51:16.931445+00:00", "type": "hole_cards"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": [], "dealer_seat": 3, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 18, "hero": {"hole_cards": ["4s", "Td"], "seat": 3}, "pot": 30, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6515, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2860, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2498, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1470, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1719, "status": "active"}], "small_blind": 10, "state_hash": "sha256:65a5f5412f51f153a7764c0a545e5e493b4ef1285dabcbd8636dd90fb826424f", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10718, "ts": "2026-10-13T05:51:16.931684+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "call", "action_id": "f0f4a358-d311-4472-93d8-52d79f58cc4d", "amount": null, "amount_mode": "incremental", "contribution_delta": 20, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 24, "name": "player_1", "player_stack_after": 6495, "player_stack_before": 6515, "pot": 50, "pot_after": 50, "pot_before": 30, "reason": null, "seat": 0, "stack": 6495, "stack_after": 6495, "stack_before": 6515, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10724, "to_call_before": 20, "ts": "2026-10-13T05:51:20.427999+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 1, "big_blind": 20, "board": [], "dealer_seat": 3, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 25, "hero": {"hole_cards": ["4s", "Td"], "seat": 3}, "pot": 50, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6495, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2860, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2498, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1470, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1719, "status": "active"}], "small_blind": 10, "state_hash": "sha256:1b1159e6564df8794de72c3e8873c1758cc8851bdfdc12c02696f79c2edaffbd", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10725, "ts": "2026-10-13T05:51:20.429123+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "call", "action_id": "32956c8a-2589-4efb-aad5-21f6dbebeaf9", "amount": null, "amount_mode": "incremental", "contribution_delta": 20, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 30, "name": "player_6", "player_stack_after": 2840, "player_stack_before": 2860, "pot": 70, "pot_after": 70, "pot_before": 50, "reason": null, "seat": 1, "stack": 2840, "stack_after": 2840, "stack_before": 2860, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10730, "to_call_before": 20, "ts": "2026-10-13T05:51:24.646539+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 2, "big_blind": 20, "board": [], "dealer_seat": 3, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 31, "hero": {"hole_cards": ["4s", "Td"], "seat": 3}, "pot": 70, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6495, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2840, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2498, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1470, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1719, "status": "active"}], "small_blind": 10, "state_hash": "sha256:89a9789de15fe6a9299809ec7e92c2d5f31c1291c2f3be59f8059c909685e36b", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10731, "ts": "2026-10-13T05:51:24.648028+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "oc-a02b5d124744-61", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 36, "name": "player_3", "player_stack_after": 2223, "player_stack_before": 2223, "pot": 70, "pot_after": 70, "pot_before": 70, "reason": null, "seat": 2, "stack": 2223, "stack_after": 2223, "stack_before": 2223, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10736, "to_call_before": 20, "ts": "2026-10-13T05:51:27.735376+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": [], "dealer_seat": 3, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 37, "hero": {"hole_cards": ["4s", "Td"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 20}, {"action": "raise", "max": 2498, "min": 40}, {"action": "all_in", "amount": 2498}]}, "max_raise_to": 2498, "min_raise_to": 40, "pot": 70, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6495, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2840, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2498, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1470, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1719, "status": "active"}], "small_blind": 10, "state_hash": "sha256:ff3c5a6c5c45c89ad5ba534303b0fa696f79ebeb29d75e8b12dd204a5d2a7307", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10737, "to_call": 20, "ts": "2026-10-13T05:51:27.736158+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"community_cards": [], "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 38, "max_raise": 2498, "min_raise": 40, "players": [{"avatar_url": null, "is_pro": false, "name": "player_1", "public_profile_slug": null, "seat": 0, "stack": 6495}, {"avatar_url": null, "is_pro": false, "name": "player_6", "public_profile_slug": null, "seat": 1, "stack": 2840}, {"avatar_url": null, "is_pro": false, "name": "player_3", "public_profile_slug": null, "seat": 2, "stack": 2223}, {"avatar_url": null, "is_pro": false, "name": "hero_bot", "public_profile_slug": null, "seat": 3, "stack": 2498}, {"avatar_url": null, "is_pro": false, "name": "player_7", "public_profile_slug": null, "seat": 4, "stack": 1470}, {"avatar_url": null, "is_pro": false, "name": "player_2", "public_profile_slug": null, "seat": 5, "stack": 1719}], "pot": 70, "seat": 3, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10738, "ts": "2026-10-13T05:51:30.739615+00:00", "turn_token": "4149f6b8-c214-4195-b0ab-82fbb154a22a", "type": "your_turn", "valid_actions": [{"action": "fold", "amount": null, "max": null, "min": null}, {"action": "call", "amount": 20, "max": null, "min": null}, {"action": "raise", "amount": null, "max": 2498, "min": 40}, {"action": "all_in", "amount": 2498, "max": null, "min": null}]}} +{"dir": "out", "msg": {"action": "raise", "amount": 60, "client_action_id": "plu-9-15", "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "turn_token": "4149f6b8-c214-4195-b0ab-82fbb154a22a", "type": "action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": [], "dealer_seat": 3, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 39, "hero": {"hole_cards": ["4s", "Td"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 20}, {"action": "raise", "max": 2498, "min": 40}, {"action": "all_in", "amount": 2498}]}, "max_raise_to": 2498, "min_raise_to": 40, "pot": 70, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6495, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2840, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2498, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1470, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1719, "status": "active"}], "small_blind": 10, "state_hash": "sha256:ff3c5a6c5c45c89ad5ba534303b0fa696f79ebeb29d75e8b12dd204a5d2a7307", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10739, "to_call": 20, "ts": "2026-10-13T05:51:30.740182+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"client_action_id": "plu-9-15", "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 41, "status": "accepted", "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10741, "ts": "2026-10-13T05:51:30.895721+00:00", "type": "action_ack"}} +{"dir": "in", "msg": {"action": "raise", "action_id": "plu-9-15", "amount": 60, "amount_mode": "to_total", "contribution_delta": 60, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 42, "name": "hero_bot", "player_stack_after": 2438, "player_stack_before": 2498, "pot": 130, "pot_after": 130, "pot_before": 70, "reason": null, "seat": 3, "stack": 2438, "stack_after": 2438, "stack_before": 2498, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10742, "to_call_before": 20, "ts": "2026-10-13T05:51:30.899622+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 4, "big_blind": 20, "board": [], "dealer_seat": 3, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 43, "hero": {"hole_cards": ["4s", "Td"], "seat": 3}, "pot": 130, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6495, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2840, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2438, "status": "active"}, {"bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1470, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1719, "status": "active"}], "small_blind": 10, "state_hash": "sha256:64d40e5802554dec6ee8e1413c0968cb767fbf01bfb640821e29f7eb63a631ef", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10743, "ts": "2026-10-13T05:51:30.900865+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "f0de6b16-abca-4c03-9fff-42116c292e4e", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 48, "name": "player_7", "player_stack_after": 1470, "player_stack_before": 1470, "pot": 130, "pot_after": 130, "pot_before": 130, "reason": null, "seat": 4, "stack": 1470, "stack_after": 1470, "stack_before": 1470, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10748, "to_call_before": 50, "ts": "2026-10-13T05:51:33.912048+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 5, "big_blind": 20, "board": [], "dealer_seat": 3, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 49, "hero": {"hole_cards": ["4s", "Td"], "seat": 3}, "pot": 130, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6495, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2840, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2438, "status": "active"}, {"bet": 10, "folded": true, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1470, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1719, "status": "active"}], "small_blind": 10, "state_hash": "sha256:3e7594d175ab1e9c4e26110e61baf3ac801bc52f8db57519f2afd7a6ede271d2", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10749, "ts": "2026-10-13T05:51:33.912940+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "63703c7d-7a00-4f07-9771-7e612548b61c", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 54, "name": "player_2", "player_stack_after": 1719, "player_stack_before": 1719, "pot": 130, "pot_after": 130, "pot_before": 130, "reason": null, "seat": 5, "stack": 1719, "stack_after": 1719, "stack_before": 1719, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10754, "to_call_before": 40, "ts": "2026-10-13T05:51:37.176541+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": [], "dealer_seat": 3, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 55, "hero": {"hole_cards": ["4s", "Td"], "seat": 3}, "pot": 130, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6495, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2840, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2438, "status": "active"}, {"bet": 10, "folded": true, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1470, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 20, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1719, "status": "active"}], "small_blind": 10, "state_hash": "sha256:b731a169fbc449198f07c67cb7412446c868b3da314ab39311b0644425f36b81", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10755, "ts": "2026-10-13T05:51:37.178221+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "call", "action_id": "9615234c-6774-4951-ad0a-dfeb44f431cc", "amount": null, "amount_mode": "incremental", "contribution_delta": 40, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 60, "name": "player_1", "player_stack_after": 6455, "player_stack_before": 6495, "pot": 170, "pot_after": 170, "pot_before": 130, "reason": null, "seat": 0, "stack": 6455, "stack_after": 6455, "stack_before": 6495, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10760, "to_call_before": 40, "ts": "2026-10-13T05:51:41.080799+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 1, "big_blind": 20, "board": [], "dealer_seat": 3, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 61, "hero": {"hole_cards": ["4s", "Td"], "seat": 3}, "pot": 170, "seats": [{"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6455, "status": "active"}, {"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2840, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 60, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2438, "status": "active"}, {"bet": 10, "folded": true, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1470, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 20, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1719, "status": "active"}], "small_blind": 10, "state_hash": "sha256:cdcdade4cdbf991a58b170da03803535d718c06ad6cae30aa6ccad2f9aa57e57", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10761, "ts": "2026-10-13T05:51:41.082220+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "call", "action_id": "f4354e8d-c3e9-40e0-97e8-d6e5c5a20fb9", "amount": null, "amount_mode": "incremental", "contribution_delta": 40, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 66, "name": "player_6", "player_stack_after": 2800, "player_stack_before": 2840, "pot": 210, "pot_after": 210, "pot_before": 170, "reason": null, "seat": 1, "stack": 2800, "stack_after": 2800, "stack_before": 2840, "state_hash": null, "stream": "event", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10766, "to_call_before": 40, "ts": "2026-10-13T05:51:45.049750+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": [], "dealer_seat": 3, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 67, "hero": {"hole_cards": ["4s", "Td"], "seat": 3}, "pot": 210, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6455, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2800, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2438, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1470, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1719, "status": "active"}], "small_blind": 10, "state_hash": "sha256:e571df70cfdaef9fe8fe6c325fc6d57fb8451be1c35829496a5f67738883da68", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10767, "ts": "2026-10-13T05:51:45.050678+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"cards": ["Kc", "Js", "Tc"], "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 68, "state_hash": null, "stream": "event", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10768, "ts": "2026-10-13T05:51:48.060176+00:00", "type": "community_cards"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": ["Kc", "Js", "Tc"], "dealer_seat": 3, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 69, "hero": {"hole_cards": ["4s", "Td"], "seat": 3}, "pot": 210, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6455, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2800, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2438, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1470, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1719, "status": "active"}], "small_blind": 10, "state_hash": "sha256:b9c4f7f78771be43debba3fe9bf067a09a36012fbdf9c3c637f42b3284d41a03", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10769, "ts": "2026-10-13T05:51:48.062217+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "raise", "action_id": "1bf57c4c-c0a0-49a4-90fd-21d2ece2f954", "amount": 69, "amount_mode": "to_total", "contribution_delta": 69, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 74, "name": "player_1", "player_stack_after": 6386, "player_stack_before": 6455, "pot": 279, "pot_after": 279, "pot_before": 210, "reason": null, "seat": 0, "stack": 6386, "stack_after": 6386, "stack_before": 6455, "state_hash": null, "stream": "event", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10774, "to_call_before": null, "ts": "2026-10-13T05:51:48.485021+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 1, "big_blind": 20, "board": ["Kc", "Js", "Tc"], "dealer_seat": 3, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 75, "hero": {"hole_cards": ["4s", "Td"], "seat": 3}, "pot": 279, "seats": [{"bet": 69, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6386, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2800, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2438, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1470, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1719, "status": "active"}], "small_blind": 10, "state_hash": "sha256:b7e20de8e446fcb9efda03ebe79a35d161206b91a82f05bb9bf604ff9de79637", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10775, "ts": "2026-10-13T05:51:48.485747+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "2c5d2d7f-5164-4834-a10a-f8e2cbf092f4", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 80, "name": "player_6", "player_stack_after": 2800, "player_stack_before": 2800, "pot": 279, "pot_after": 279, "pot_before": 279, "reason": null, "seat": 1, "stack": 2800, "stack_after": 2800, "stack_before": 2800, "state_hash": null, "stream": "event", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10780, "to_call_before": 69, "ts": "2026-10-13T05:51:52.911766+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": ["Kc", "Js", "Tc"], "dealer_seat": 3, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 81, "hero": {"hole_cards": ["4s", "Td"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 69}, {"action": "raise", "max": 2438, "min": 138}, {"action": "all_in", "amount": 2438}]}, "max_raise_to": 2438, "min_raise_to": 138, "pot": 279, "seats": [{"bet": 69, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6386, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2800, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2438, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1470, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1719, "status": "active"}], "small_blind": 10, "state_hash": "sha256:2cfb27387ca79191044f63ddd5cd1a91c46ef6b786366be3366dce7aa6942e99", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10781, "to_call": 69, "ts": "2026-10-13T05:51:52.913096+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"community_cards": ["Kc", "Js", "Tc"], "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 82, "max_raise": 2438, "min_raise": 138, "players": [{"avatar_url": null, "is_pro": false, "name": "player_1", "public_profile_slug": null, "seat": 0, "stack": 6386}, {"avatar_url": null, "is_pro": false, "name": "player_6", "public_profile_slug": null, "seat": 1, "stack": 2800}, {"avatar_url": null, "is_pro": false, "name": "player_3", "public_profile_slug": null, "seat": 2, "stack": 2223}, {"avatar_url": null, "is_pro": false, "name": "hero_bot", "public_profile_slug": null, "seat": 3, "stack": 2438}, {"avatar_url": null, "is_pro": false, "name": "player_7", "public_profile_slug": null, "seat": 4, "stack": 1470}, {"avatar_url": null, "is_pro": false, "name": "player_2", "public_profile_slug": null, "seat": 5, "stack": 1719}], "pot": 279, "seat": 3, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10782, "ts": "2026-10-13T05:51:55.915843+00:00", "turn_token": "584c2ad3-403a-4cd7-bba3-7fa22c43ae22", "type": "your_turn", "valid_actions": [{"action": "fold", "amount": null, "max": null, "min": null}, {"action": "call", "amount": 69, "max": null, "min": null}, {"action": "raise", "amount": null, "max": 2438, "min": 138}, {"action": "all_in", "amount": 2438, "max": null, "min": null}]}} +{"dir": "out", "msg": {"action": "call", "client_action_id": "plu-9-16", "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "turn_token": "584c2ad3-403a-4cd7-bba3-7fa22c43ae22", "type": "action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": ["Kc", "Js", "Tc"], "dealer_seat": 3, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 83, "hero": {"hole_cards": ["4s", "Td"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 69}, {"action": "raise", "max": 2438, "min": 138}, {"action": "all_in", "amount": 2438}]}, "max_raise_to": 2438, "min_raise_to": 138, "pot": 279, "seats": [{"bet": 69, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6386, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2800, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2438, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1470, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1719, "status": "active"}], "small_blind": 10, "state_hash": "sha256:2cfb27387ca79191044f63ddd5cd1a91c46ef6b786366be3366dce7aa6942e99", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10783, "to_call": 69, "ts": "2026-10-13T05:51:55.916410+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"client_action_id": "plu-9-16", "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 85, "status": "accepted", "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10785, "ts": "2026-10-13T05:51:56.072335+00:00", "type": "action_ack"}} +{"dir": "in", "msg": {"action": "call", "action_id": "plu-9-16", "amount": null, "amount_mode": "incremental", "contribution_delta": 69, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 86, "name": "hero_bot", "player_stack_after": 2369, "player_stack_before": 2438, "pot": 348, "pot_after": 348, "pot_before": 279, "reason": null, "seat": 3, "stack": 2369, "stack_after": 2369, "stack_before": 2438, "state_hash": null, "stream": "event", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10786, "to_call_before": 69, "ts": "2026-10-13T05:51:56.075566+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": ["Kc", "Js", "Tc"], "dealer_seat": 3, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 87, "hero": {"hole_cards": ["4s", "Td"], "seat": 3}, "pot": 348, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6386, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2800, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2369, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1470, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1719, "status": "active"}], "small_blind": 10, "state_hash": "sha256:cbe504fb13d77aacaa6cf308a1ead251fbfdfb634b947054f7f2ea9c5e5081a0", "stream": "state", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10787, "ts": "2026-10-13T05:51:56.076352+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"cards": ["Kc", "Js", "Tc", "8d"], "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 88, "state_hash": null, "stream": "event", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10788, "ts": "2026-10-13T05:51:59.080171+00:00", "type": "community_cards"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": ["Kc", "Js", "Tc", "8d"], "dealer_seat": 3, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 89, "hero": {"hole_cards": ["4s", "Td"], "seat": 3}, "pot": 348, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6386, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2800, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2369, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1470, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1719, "status": "active"}], "small_blind": 10, "state_hash": "sha256:75a7e6d5a7c2fb6fd88b8503087885cb216f857f7e5ddebb222901ec9944c7bb", "stream": "state", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10789, "ts": "2026-10-13T05:51:59.080979+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "raise", "action_id": "710ae5f5-7afa-424e-98e8-8dbea8d5d696", "amount": 348, "amount_mode": "to_total", "contribution_delta": 348, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 94, "name": "player_1", "player_stack_after": 6038, "player_stack_before": 6386, "pot": 696, "pot_after": 696, "pot_before": 348, "reason": null, "seat": 0, "stack": 6038, "stack_after": 6038, "stack_before": 6386, "state_hash": null, "stream": "event", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10794, "to_call_before": null, "ts": "2026-10-13T05:51:59.510971+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": ["Kc", "Js", "Tc", "8d"], "dealer_seat": 3, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 95, "hero": {"hole_cards": ["4s", "Td"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 348}, {"action": "raise", "max": 2369, "min": 696}, {"action": "all_in", "amount": 2369}]}, "max_raise_to": 2369, "min_raise_to": 696, "pot": 696, "seats": [{"bet": 348, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6038, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2800, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2369, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1470, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1719, "status": "active"}], "small_blind": 10, "state_hash": "sha256:2b84c6f8c5915c1d753463435424025363cf790f280a1f6ee3dd1511b9a79744", "stream": "state", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10795, "to_call": 348, "ts": "2026-10-13T05:51:59.511832+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"community_cards": ["Kc", "Js", "Tc", "8d"], "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 96, "max_raise": 2369, "min_raise": 696, "players": [{"avatar_url": null, "is_pro": false, "name": "player_1", "public_profile_slug": null, "seat": 0, "stack": 6038}, {"avatar_url": null, "is_pro": false, "name": "player_6", "public_profile_slug": null, "seat": 1, "stack": 2800}, {"avatar_url": null, "is_pro": false, "name": "player_3", "public_profile_slug": null, "seat": 2, "stack": 2223}, {"avatar_url": null, "is_pro": false, "name": "hero_bot", "public_profile_slug": null, "seat": 3, "stack": 2369}, {"avatar_url": null, "is_pro": false, "name": "player_7", "public_profile_slug": null, "seat": 4, "stack": 1470}, {"avatar_url": null, "is_pro": false, "name": "player_2", "public_profile_slug": null, "seat": 5, "stack": 1719}], "pot": 696, "seat": 3, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10796, "ts": "2026-10-13T05:52:02.515058+00:00", "turn_token": "94b72e6b-e4fe-481a-80db-3f5e6c43ba5b", "type": "your_turn", "valid_actions": [{"action": "fold", "amount": null, "max": null, "min": null}, {"action": "call", "amount": 348, "max": null, "min": null}, {"action": "raise", "amount": null, "max": 2369, "min": 696}, {"action": "all_in", "amount": 2369, "max": null, "min": null}]}} +{"dir": "out", "msg": {"action": "call", "client_action_id": "plu-9-17", "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "turn_token": "94b72e6b-e4fe-481a-80db-3f5e6c43ba5b", "type": "action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": ["Kc", "Js", "Tc", "8d"], "dealer_seat": 3, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 97, "hero": {"hole_cards": ["4s", "Td"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 348}, {"action": "raise", "max": 2369, "min": 696}, {"action": "all_in", "amount": 2369}]}, "max_raise_to": 2369, "min_raise_to": 696, "pot": 696, "seats": [{"bet": 348, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6038, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2800, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2369, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1470, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1719, "status": "active"}], "small_blind": 10, "state_hash": "sha256:2b84c6f8c5915c1d753463435424025363cf790f280a1f6ee3dd1511b9a79744", "stream": "state", "street": "turn", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10797, "to_call": 348, "ts": "2026-10-13T05:52:02.515690+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"client_action_id": "plu-9-17", "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 99, "status": "accepted", "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10799, "ts": "2026-10-13T05:52:02.670548+00:00", "type": "action_ack"}} +{"dir": "in", "msg": {"action": "call", "action_id": "plu-9-17", "amount": null, "amount_mode": "incremental", "contribution_delta": 348, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 100, "name": "hero_bot", "player_stack_after": 2021, "player_stack_before": 2369, "pot": 1044, "pot_after": 1044, "pot_before": 696, "reason": null, "seat": 3, "stack": 2021, "stack_after": 2021, "stack_before": 2369, "state_hash": null, "stream": "event", "street": "river", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10800, "to_call_before": 348, "ts": "2026-10-13T05:52:02.673852+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": ["Kc", "Js", "Tc", "8d"], "dealer_seat": 3, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 101, "hero": {"hole_cards": ["4s", "Td"], "seat": 3}, "pot": 1044, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6038, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2800, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2021, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1470, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1719, "status": "active"}], "small_blind": 10, "state_hash": "sha256:40a01e8199c918577dae54a3ef25a00ed82f1ec48e9eecba791d4abc40b7817a", "stream": "state", "street": "river", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10801, "ts": "2026-10-13T05:52:02.674808+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"cards": ["Kc", "Js", "Tc", "8d", "9s"], "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 102, "state_hash": null, "stream": "event", "street": "river", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10802, "ts": "2026-10-13T05:52:05.679886+00:00", "type": "community_cards"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": ["Kc", "Js", "Tc", "8d", "9s"], "dealer_seat": 3, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 103, "hero": {"hole_cards": ["4s", "Td"], "seat": 3}, "pot": 1044, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6038, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2800, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2021, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1470, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1719, "status": "active"}], "small_blind": 10, "state_hash": "sha256:4cc2830ae165554c4f4771d330f2df1f9b67791c10f5da745909b301e6cf1578", "stream": "state", "street": "river", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10803, "ts": "2026-10-13T05:52:05.680798+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "check", "action_id": "1c8b35f1-2e16-4d29-aa59-ee5c18c3b35f", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 108, "name": "player_1", "player_stack_after": 6038, "player_stack_before": 6038, "pot": 1044, "pot_after": 1044, "pot_before": 1044, "reason": null, "seat": 0, "stack": 6038, "stack_after": 6038, "stack_before": 6038, "state_hash": null, "stream": "event", "street": "river", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10808, "to_call_before": null, "ts": "2026-10-13T05:52:06.150559+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": ["Kc", "Js", "Tc", "8d", "9s"], "dealer_seat": 3, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 109, "hero": {"hole_cards": ["4s", "Td"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "check"}, {"action": "raise", "max": 2021, "min": 20}, {"action": "all_in", "amount": 2021}]}, "max_raise_to": 2021, "min_raise_to": 20, "pot": 1044, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6038, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2800, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2021, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1470, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1719, "status": "active"}], "small_blind": 10, "state_hash": "sha256:d4b5cef4910effc05ead970b961444376e7f6d7b04ce02ffe6a094cec3accc36", "stream": "state", "street": "river", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10809, "ts": "2026-10-13T05:52:06.151546+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"community_cards": ["Kc", "Js", "Tc", "8d", "9s"], "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 110, "max_raise": 2021, "min_raise": 20, "players": [{"avatar_url": null, "is_pro": false, "name": "player_1", "public_profile_slug": null, "seat": 0, "stack": 6038}, {"avatar_url": null, "is_pro": false, "name": "player_6", "public_profile_slug": null, "seat": 1, "stack": 2800}, {"avatar_url": null, "is_pro": false, "name": "player_3", "public_profile_slug": null, "seat": 2, "stack": 2223}, {"avatar_url": null, "is_pro": false, "name": "hero_bot", "public_profile_slug": null, "seat": 3, "stack": 2021}, {"avatar_url": null, "is_pro": false, "name": "player_7", "public_profile_slug": null, "seat": 4, "stack": 1470}, {"avatar_url": null, "is_pro": false, "name": "player_2", "public_profile_slug": null, "seat": 5, "stack": 1719}], "pot": 1044, "seat": 3, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10810, "ts": "2026-10-13T05:52:09.155293+00:00", "turn_token": "4aaccc8e-0397-4456-a20b-a0dba2cbb513", "type": "your_turn", "valid_actions": [{"action": "fold", "amount": null, "max": null, "min": null}, {"action": "check", "amount": null, "max": null, "min": null}, {"action": "raise", "amount": null, "max": 2021, "min": 20}, {"action": "all_in", "amount": 2021, "max": null, "min": null}]}} +{"dir": "out", "msg": {"action": "check", "client_action_id": "plu-9-18", "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "turn_token": "4aaccc8e-0397-4456-a20b-a0dba2cbb513", "type": "action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": ["Kc", "Js", "Tc", "8d", "9s"], "dealer_seat": 3, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 111, "hero": {"hole_cards": ["4s", "Td"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "check"}, {"action": "raise", "max": 2021, "min": 20}, {"action": "all_in", "amount": 2021}]}, "max_raise_to": 2021, "min_raise_to": 20, "pot": 1044, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 6038, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2800, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2021, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1470, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1719, "status": "active"}], "small_blind": 10, "state_hash": "sha256:d4b5cef4910effc05ead970b961444376e7f6d7b04ce02ffe6a094cec3accc36", "stream": "state", "street": "river", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10811, "ts": "2026-10-13T05:52:09.155904+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"client_action_id": "plu-9-18", "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 113, "status": "accepted", "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10813, "ts": "2026-10-13T05:52:09.314389+00:00", "type": "action_ack"}} +{"dir": "in", "msg": {"action": "check", "action_id": "plu-9-18", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 114, "name": "hero_bot", "player_stack_after": 2021, "player_stack_before": 2021, "pot": 1044, "pot_after": 1044, "pot_before": 1044, "reason": null, "seat": 3, "stack": 2021, "stack_after": 2021, "stack_before": 2021, "state_hash": null, "stream": "event", "street": "showdown", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10814, "to_call_before": null, "ts": "2026-10-13T05:52:09.317952+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"big_blind": 20, "board": ["Kc", "Js", "Tc", "8d", "9s"], "dealer_seat": 3, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 115, "hero": {"hole_cards": ["4s", "Td"], "seat": 3}, "pot": 0, "seats": [{"bet": 0, "in_hand": false, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 7082, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2800, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2021, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1470, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "in_hand": false, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1719, "status": "active"}], "small_blind": 10, "state_hash": "sha256:3fc067f9e1ec58960750c45a4e6a93b8eaf196b1ab91aa135e54fb484f22aa9e", "stream": "state", "street": "idle", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10815, "ts": "2026-10-13T05:52:09.319088+00:00", "type": "table_state", "waiting_details": {"active_players": 6, "away_players": 0, "connected_players": 6, "disconnected_players": 0, "eligible_players": 6, "min_required": 2, "player_count": 6}, "waiting_reason": "awaiting_hand_start"}} +{"dir": "in", "msg": {"actions": [{"action": "call", "amount": null, "seat": 0, "street": "preflop"}, {"action": "call", "amount": null, "seat": 1, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 2, "street": "preflop"}, {"action": "raise", "amount": 60, "seat": 3, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 4, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 5, "street": "preflop"}, {"action": "call", "amount": null, "seat": 0, "street": "preflop"}, {"action": "call", "amount": null, "seat": 1, "street": "preflop"}, {"action": "raise", "amount": 69, "seat": 0, "street": "flop"}, {"action": "fold", "amount": null, "seat": 1, "street": "flop"}, {"action": "call", "amount": null, "seat": 3, "street": "flop"}, {"action": "raise", "amount": 348, "seat": 0, "street": "turn"}, {"action": "call", "amount": null, "seat": 3, "street": "turn"}, {"action": "check", "amount": null, "seat": 0, "street": "river"}, {"action": "check", "amount": null, "seat": 3, "street": "river"}], "final_stacks": {"0": 7082, "1": 2800, "2": 2223, "3": 2021, "4": 1470, "5": 1719}, "hand_id": "2b4c5c51-a972-4f9a-a6dc-5f08cf491b2e", "hand_seq": 116, "outcome_kind": "win", "payouts": [{"amount": 1044, "seat": 0}], "pot": 567, "pot_kind": "transferable", "shown_cards": {"0": ["Jh", "8h"], "3": ["4s", "Td"]}, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10816, "total_pot": 1044, "transferable_pot": 567, "ts": "2026-10-13T05:52:09.396334+00:00", "type": "hand_result", "winners": [{"amount": 567, "hand_description": "Two pair", "name": "player_1", "seat": 0, "stack": 7082}]}} +{"dir": "in", "msg": {"blinds": {"big_blind": 20, "small_blind": 10}, "dealer_seat": 4, "hand_id": "89df770b-950b-4cf8-a0f9-1f6b7565ae9a", "hand_seq": 4, "seat": 3, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10820, "ts": "2026-10-13T05:52:14.441158+00:00", "type": "hand_start"}} +{"dir": "in", "msg": {"cards": ["4s", "9s"], "hand_id": "89df770b-950b-4cf8-a0f9-1f6b7565ae9a", "hand_seq": 15, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10831, "ts": "2026-10-13T05:52:14.449527+00:00", "type": "hole_cards"}} +{"dir": "in", "msg": {"actor_seat": 1, "big_blind": 20, "board": [], "dealer_seat": 4, "hand_id": "89df770b-950b-4cf8-a0f9-1f6b7565ae9a", "hand_seq": 16, "hero": {"hole_cards": ["4s", "9s"], "seat": 3}, "pot": 30, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 7062, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2800, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2021, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1470, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1709, "status": "active"}], "small_blind": 10, "state_hash": "sha256:572ee306b3271755cfb7a494bc8ef7fa41c0c9e4904110df76dfd4ba203ec796", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10832, "ts": "2026-10-13T05:52:14.449698+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "cf20a881-bf68-4b68-bf22-00552f7a820d", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "89df770b-950b-4cf8-a0f9-1f6b7565ae9a", "hand_seq": 24, "name": "player_6", "player_stack_after": 2800, "player_stack_before": 2800, "pot": 30, "pot_after": 30, "pot_before": 30, "reason": null, "seat": 1, "stack": 2800, "stack_after": 2800, "stack_before": 2800, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10840, "to_call_before": 20, "ts": "2026-10-13T05:52:18.905557+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 2, "big_blind": 20, "board": [], "dealer_seat": 4, "hand_id": "89df770b-950b-4cf8-a0f9-1f6b7565ae9a", "hand_seq": 25, "hero": {"hole_cards": ["4s", "9s"], "seat": 3}, "pot": 30, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 7062, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2800, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2021, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1470, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1709, "status": "active"}], "small_blind": 10, "state_hash": "sha256:9e55113d2ab3518d759ac1531b542ef4dc1448f563248482f9c28c0c379badc2", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10841, "ts": "2026-10-13T05:52:18.906533+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "oc-5eb340ea2b6e-62", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "89df770b-950b-4cf8-a0f9-1f6b7565ae9a", "hand_seq": 30, "name": "player_3", "player_stack_after": 2223, "player_stack_before": 2223, "pot": 30, "pot_after": 30, "pot_before": 30, "reason": null, "seat": 2, "stack": 2223, "stack_after": 2223, "stack_before": 2223, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10846, "to_call_before": 20, "ts": "2026-10-13T05:52:21.989038+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": [], "dealer_seat": 4, "hand_id": "89df770b-950b-4cf8-a0f9-1f6b7565ae9a", "hand_seq": 31, "hero": {"hole_cards": ["4s", "9s"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 20}, {"action": "raise", "max": 2021, "min": 40}, {"action": "all_in", "amount": 2021}]}, "max_raise_to": 2021, "min_raise_to": 40, "pot": 30, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 7062, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2800, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2021, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1470, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1709, "status": "active"}], "small_blind": 10, "state_hash": "sha256:d1ae4becdf0bb510fa54d6fd39db6f468051450504c767588b1b12780b7e676c", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10847, "to_call": 20, "ts": "2026-10-13T05:52:21.989861+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"community_cards": [], "hand_id": "89df770b-950b-4cf8-a0f9-1f6b7565ae9a", "hand_seq": 32, "max_raise": 2021, "min_raise": 40, "players": [{"avatar_url": null, "is_pro": false, "name": "player_1", "public_profile_slug": null, "seat": 0, "stack": 7062}, {"avatar_url": null, "is_pro": false, "name": "player_6", "public_profile_slug": null, "seat": 1, "stack": 2800}, {"avatar_url": null, "is_pro": false, "name": "player_3", "public_profile_slug": null, "seat": 2, "stack": 2223}, {"avatar_url": null, "is_pro": false, "name": "hero_bot", "public_profile_slug": null, "seat": 3, "stack": 2021}, {"avatar_url": null, "is_pro": false, "name": "player_7", "public_profile_slug": null, "seat": 4, "stack": 1470}, {"avatar_url": null, "is_pro": false, "name": "player_2", "public_profile_slug": null, "seat": 5, "stack": 1709}], "pot": 30, "seat": 3, "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10848, "ts": "2026-10-13T05:52:24.992574+00:00", "turn_token": "76f414dc-6a0b-45cb-a127-43e4bd2702bd", "type": "your_turn", "valid_actions": [{"action": "fold", "amount": null, "max": null, "min": null}, {"action": "call", "amount": 20, "max": null, "min": null}, {"action": "raise", "amount": null, "max": 2021, "min": 40}, {"action": "all_in", "amount": 2021, "max": null, "min": null}]}} +{"dir": "out", "msg": {"action": "fold", "client_action_id": "plu-10-19", "hand_id": "89df770b-950b-4cf8-a0f9-1f6b7565ae9a", "turn_token": "76f414dc-6a0b-45cb-a127-43e4bd2702bd", "type": "action"}} +{"dir": "in", "msg": {"actor_seat": 3, "big_blind": 20, "board": [], "dealer_seat": 4, "hand_id": "89df770b-950b-4cf8-a0f9-1f6b7565ae9a", "hand_seq": 33, "hero": {"hole_cards": ["4s", "9s"], "seat": 3, "valid_actions": [{"action": "fold"}, {"action": "call", "amount": 20}, {"action": "raise", "max": 2021, "min": 40}, {"action": "all_in", "amount": 2021}]}, "max_raise_to": 2021, "min_raise_to": 40, "pot": 30, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 7062, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2800, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2021, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1470, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1709, "status": "active"}], "small_blind": 10, "state_hash": "sha256:d1ae4becdf0bb510fa54d6fd39db6f468051450504c767588b1b12780b7e676c", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10849, "to_call": 20, "ts": "2026-10-13T05:52:24.993093+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"client_action_id": "plu-10-19", "hand_id": "89df770b-950b-4cf8-a0f9-1f6b7565ae9a", "hand_seq": 35, "status": "accepted", "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10851, "ts": "2026-10-13T05:52:25.149170+00:00", "type": "action_ack"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "plu-10-19", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "89df770b-950b-4cf8-a0f9-1f6b7565ae9a", "hand_seq": 36, "name": "hero_bot", "player_stack_after": 2021, "player_stack_before": 2021, "pot": 30, "pot_after": 30, "pot_before": 30, "reason": null, "seat": 3, "stack": 2021, "stack_after": 2021, "stack_before": 2021, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10852, "to_call_before": 20, "ts": "2026-10-13T05:52:25.152408+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 4, "big_blind": 20, "board": [], "dealer_seat": 4, "hand_id": "89df770b-950b-4cf8-a0f9-1f6b7565ae9a", "hand_seq": 37, "hero": {"hole_cards": ["4s", "9s"], "seat": 3}, "pot": 30, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 7062, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2800, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2021, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1470, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1709, "status": "active"}], "small_blind": 10, "state_hash": "sha256:535e53ca7ec2ef98095a060d8b73f7955bc8901139b922333c0c26ee9b2e62ab", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10853, "ts": "2026-10-13T05:52:25.153137+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "raise", "action_id": "b33204ed-c943-4701-813a-c56cc72a38ee", "amount": 46, "amount_mode": "to_total", "contribution_delta": 46, "hand_id": "89df770b-950b-4cf8-a0f9-1f6b7565ae9a", "hand_seq": 42, "name": "player_7", "player_stack_after": 1424, "player_stack_before": 1470, "pot": 76, "pot_after": 76, "pot_before": 30, "reason": null, "seat": 4, "stack": 1424, "stack_after": 1424, "stack_before": 1470, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10858, "to_call_before": 20, "ts": "2026-10-13T05:52:28.161423+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 5, "big_blind": 20, "board": [], "dealer_seat": 4, "hand_id": "89df770b-950b-4cf8-a0f9-1f6b7565ae9a", "hand_seq": 43, "hero": {"hole_cards": ["4s", "9s"], "seat": 3}, "pot": 76, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 7062, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2800, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2021, "status": "active"}, {"bet": 46, "folded": false, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1424, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 10, "folded": false, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1709, "status": "active"}], "small_blind": 10, "state_hash": "sha256:29057310ef494f1346cb09b310d4c9fca7a5d81f7bdd0b04caeef9b112c56206", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10859, "ts": "2026-10-13T05:52:28.162132+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "117a684f-e0b0-4346-a448-8111368fec04", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "89df770b-950b-4cf8-a0f9-1f6b7565ae9a", "hand_seq": 48, "name": "player_2", "player_stack_after": 1709, "player_stack_before": 1709, "pot": 76, "pot_after": 76, "pot_before": 76, "reason": null, "seat": 5, "stack": 1709, "stack_after": 1709, "stack_before": 1709, "state_hash": null, "stream": "event", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10864, "to_call_before": 36, "ts": "2026-10-13T05:52:31.426678+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": [], "dealer_seat": 4, "hand_id": "89df770b-950b-4cf8-a0f9-1f6b7565ae9a", "hand_seq": 49, "hero": {"hole_cards": ["4s", "9s"], "seat": 3}, "pot": 76, "seats": [{"bet": 20, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 7062, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2800, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2021, "status": "active"}, {"bet": 46, "folded": false, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1424, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 10, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1709, "status": "active"}], "small_blind": 10, "state_hash": "sha256:f29f5bf4509dbc977a47a15044bba3f5805f45fe11d0445aa37527954818aa42", "stream": "state", "street": "preflop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10865, "ts": "2026-10-13T05:52:31.427563+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "call", "action_id": "57d07a06-f90a-4bd7-a29d-25fa32221549", "amount": null, "amount_mode": "incremental", "contribution_delta": 26, "hand_id": "89df770b-950b-4cf8-a0f9-1f6b7565ae9a", "hand_seq": 54, "name": "player_1", "player_stack_after": 7036, "player_stack_before": 7062, "pot": 102, "pot_after": 102, "pot_before": 76, "reason": null, "seat": 0, "stack": 7036, "stack_after": 7036, "stack_before": 7062, "state_hash": null, "stream": "event", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10870, "to_call_before": 26, "ts": "2026-10-13T05:52:34.651100+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": [], "dealer_seat": 4, "hand_id": "89df770b-950b-4cf8-a0f9-1f6b7565ae9a", "hand_seq": 55, "hero": {"hole_cards": ["4s", "9s"], "seat": 3}, "pot": 102, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 7036, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2800, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2021, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1424, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1709, "status": "active"}], "small_blind": 10, "state_hash": "sha256:47d82ddfd604581a1eea984f7fb26cd935901aef63cc34ed8a1ca9a260c59184", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10871, "ts": "2026-10-13T05:52:34.652749+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"cards": ["Jc", "8d", "5h"], "hand_id": "89df770b-950b-4cf8-a0f9-1f6b7565ae9a", "hand_seq": 56, "state_hash": null, "stream": "event", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10872, "ts": "2026-10-13T05:52:37.709561+00:00", "type": "community_cards"}} +{"dir": "in", "msg": {"actor_seat": 0, "big_blind": 20, "board": ["Jc", "8d", "5h"], "dealer_seat": 4, "hand_id": "89df770b-950b-4cf8-a0f9-1f6b7565ae9a", "hand_seq": 57, "hero": {"hole_cards": ["4s", "9s"], "seat": 3}, "pot": 102, "seats": [{"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 7036, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2800, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2021, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1424, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1709, "status": "active"}], "small_blind": 10, "state_hash": "sha256:2f63be2cb631493a68678914a36ae515b8b5c8aecec1f2b735b9b42b37e24f03", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10873, "ts": "2026-10-13T05:52:37.736891+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "raise", "action_id": "5758ccb2-ccb0-4cf0-a2d9-ad6453042da8", "amount": 34, "amount_mode": "to_total", "contribution_delta": 34, "hand_id": "89df770b-950b-4cf8-a0f9-1f6b7565ae9a", "hand_seq": 62, "name": "player_1", "player_stack_after": 7002, "player_stack_before": 7036, "pot": 136, "pot_after": 136, "pot_before": 102, "reason": null, "seat": 0, "stack": 7002, "stack_after": 7002, "stack_before": 7036, "state_hash": null, "stream": "event", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10878, "to_call_before": null, "ts": "2026-10-13T05:52:38.085699+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"actor_seat": 4, "big_blind": 20, "board": ["Jc", "8d", "5h"], "dealer_seat": 4, "hand_id": "89df770b-950b-4cf8-a0f9-1f6b7565ae9a", "hand_seq": 63, "hero": {"hole_cards": ["4s", "9s"], "seat": 3}, "pot": 136, "seats": [{"bet": 34, "folded": false, "in_hand": true, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 7002, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2800, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2021, "status": "active"}, {"bet": 0, "folded": false, "in_hand": true, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1424, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "folded": true, "in_hand": true, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1709, "status": "active"}], "small_blind": 10, "state_hash": "sha256:c90d14d0f8f72c09005cab59bd049cd7e1b193b16e0abc24d508bd9862c6230d", "stream": "state", "street": "flop", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10879, "ts": "2026-10-13T05:52:38.086556+00:00", "type": "table_state"}} +{"dir": "in", "msg": {"action": "fold", "action_id": "2b9617a3-87f2-4f6a-a71c-ec652c5962d2", "amount": null, "amount_mode": "incremental", "contribution_delta": 0, "hand_id": "89df770b-950b-4cf8-a0f9-1f6b7565ae9a", "hand_seq": 68, "name": "player_7", "player_stack_after": 1424, "player_stack_before": 1424, "pot": 136, "pot_after": 136, "pot_before": 136, "reason": null, "seat": 4, "stack": 1424, "stack_after": 1424, "stack_before": 1424, "state_hash": null, "stream": "event", "street": "showdown", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10884, "to_call_before": 34, "ts": "2026-10-13T05:52:41.095380+00:00", "type": "player_action"}} +{"dir": "in", "msg": {"big_blind": 20, "board": ["Jc", "8d", "5h"], "dealer_seat": 4, "hand_id": "89df770b-950b-4cf8-a0f9-1f6b7565ae9a", "hand_seq": 69, "hero": {"hole_cards": ["4s", "9s"], "seat": 3}, "pot": 0, "seats": [{"bet": 0, "in_hand": false, "is_pro": false, "name": "player_1", "public_profile_slug": "player_1", "seat": 0, "stack": 7138, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_6", "public_profile_slug": "player_6", "seat": 1, "stack": 2800, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_3", "public_profile_slug": "player_3", "seat": 2, "stack": 2223, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "hero_bot", "seat": 3, "stack": 2021, "status": "active"}, {"bet": 0, "in_hand": false, "is_pro": false, "name": "player_7", "public_profile_slug": "player_7", "seat": 4, "stack": 1424, "status": "active"}, {"avatar_url": "/avatar.webp", "bet": 0, "in_hand": false, "is_pro": false, "name": "player_2", "public_profile_slug": "player_2", "seat": 5, "stack": 1709, "status": "active"}], "small_blind": 10, "state_hash": "sha256:f0eb0524a9079e21ad115498a4c1aaa0c2686a2f97bd466586af172ec883349e", "stream": "state", "street": "idle", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10885, "ts": "2026-10-13T05:52:41.096063+00:00", "type": "table_state", "waiting_details": {"active_players": 6, "away_players": 0, "connected_players": 6, "disconnected_players": 0, "eligible_players": 6, "min_required": 2, "player_count": 6}, "waiting_reason": "awaiting_hand_start"}} +{"dir": "in", "msg": {"actions": [{"action": "fold", "amount": null, "seat": 1, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 2, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 3, "street": "preflop"}, {"action": "raise", "amount": 46, "seat": 4, "street": "preflop"}, {"action": "fold", "amount": null, "seat": 5, "street": "preflop"}, {"action": "call", "amount": null, "seat": 0, "street": "preflop"}, {"action": "raise", "amount": 34, "seat": 0, "street": "flop"}, {"action": "fold", "amount": null, "seat": 4, "street": "flop"}], "final_stacks": {"0": 7138, "1": 2800, "2": 2223, "3": 2021, "4": 1424, "5": 1709}, "hand_id": "89df770b-950b-4cf8-a0f9-1f6b7565ae9a", "hand_seq": 70, "outcome_kind": "win", "payouts": [{"amount": 102, "seat": 0}], "pot": 56, "pot_kind": "transferable", "state_hash": null, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10886, "total_pot": 102, "transferable_pot": 56, "ts": "2026-10-13T05:52:41.263337+00:00", "type": "hand_result", "winners": [{"amount": 56, "hand_description": null, "name": "player_1", "seat": 0, "stack": 7138}]}} +{"dir": "out", "msg": {"type": "leave_table"}} +{"dir": "in", "msg": {"hand_id": "89df770b-950b-4cf8-a0f9-1f6b7565ae9a", "hand_seq": 71, "name": "hero_bot", "reason": "left", "seat": 3, "stream": "event", "table_id": "79f638c2-02ab-474b-bf35-b63b0b2f9198", "table_seq": 10887, "ts": "2026-10-13T05:52:41.465204+00:00", "type": "player_left"}} diff --git a/arena/openpoker/tests/search_guard.rs b/arena/openpoker/tests/search_guard.rs new file mode 100644 index 00000000..2236652e --- /dev/null +++ b/arena/openpoker/tests/search_guard.rs @@ -0,0 +1,80 @@ +//! Search policy through the real session path on the offline mock table (no network). +//! Blueprint: a tiny 6-player toy blueprint trained in-process (`search::testkit`). + +use bench::builtin::builtin; +use bench::policy::PolicyFactory; +use nlhe::abstraction::BetSizing; +use openpoker::offline; +use openpoker::searchpol::{finish, SearchOpts}; +use openpoker::session::{HuMode, PolicySpec, Session, SessionConfig}; +use openpoker::trace::MemSink; +use search::bp::Blueprint; +use search::testkit::train_blueprint; +use std::sync::{Arc, OnceLock}; + +fn bp6() -> Blueprint { + static B: OnceLock = OnceLock::new(); + B.get_or_init(|| train_blueprint(6, BetSizing::tiny(), Arc::new(bench::bp::CoarseBucketer), 40_000, 9)).clone() +} + +fn run(opts: SearchOpts, hands: usize) -> (Session, MemSink, offline::OfflineResult, Arc) { + let g = Arc::new(finish(bp6(), &opts).unwrap()); + let sink = MemSink::default(); + let cfg = SessionConfig { buy_in: 2000, target_hands: hands, seed: 3, auto_rebuy: true, raw: false, sizing: "tiny".into(), buckets: "coarse".into(), max_stack_bb: 0.0 }; + let spec = PolicySpec { label: "search:test".into(), main: g.clone() as Arc, embed6: true, fallback: builtin("tag").unwrap(), hu: HuMode::Fallback }; + let mut s = Session::new(cfg, spec, Box::new(sink.clone())); + let r = offline::run(&mut s, hands, 77); + (s, sink, r, g) +} + +fn bad(sink: &MemSink) -> Vec { + sink.of_kind("anomaly") + .into_iter() + .filter(|a| { + matches!( + a["what"].as_str().unwrap_or(""), + "desync" | "replay_failed_will_rebuild" | "engine_server_mismatch" | "illegal_choice_replaced" | "profit_mismatch" | "your_turn_without_hand" + ) + }) + .collect() +} + +#[test] +fn offline_smoke_search_policy_plays_hundreds_of_hands() { + let o = SearchOpts { threads: 2, budget_ms: 30_000, sets: "iters=300".into(), search_buckets: None }; + let (s, sink, r, g) = run(o, 300); + assert_eq!(r.error, None); + assert_eq!(r.hands, 300); + assert_eq!(s.counters.hands_done, 300); + assert!(bad(&sink).is_empty(), "{:#?}", &bad(&sink)[..bad(&sink).len().min(3)]); + assert_eq!(s.counters.desync_hands, 0); + assert_eq!(s.counters.fallbacks, 0); + assert_eq!(s.counters.policy_fallbacks, 0, "no timeouts with a 30 s budget"); + assert!(g.searched() > 20, "search should have run, ran {}", g.searched()); + assert_eq!(g.timeouts() + g.panics(), 0); + let dec = sink.of_kind("decision"); + assert!(dec.iter().all(|d| d["issues"].as_array().unwrap().is_empty()), "engine/server must agree"); +} + +#[test] +fn tiny_budget_falls_back_to_blueprint_cleanly() { + // 1 ms hard budget with a search that would run for seconds (soft cap disabled via ms=). + let o = SearchOpts { threads: 2, budget_ms: 1, sets: "iters=400000,ms=600000".into(), search_buckets: None }; + let (s, sink, r, g) = run(o, 60); + assert_eq!(r.error, None, "session must keep answering every turn"); + assert_eq!(s.counters.hands_done, 60); + assert!(bad(&sink).is_empty(), "{:#?}", &bad(&sink)[..bad(&sink).len().min(3)]); + let dec = sink.of_kind("decision"); + let reasons: Vec = dec.iter().filter_map(|d| d["fallback_reason"].as_str().map(str::to_string)).collect(); + assert!(!reasons.is_empty(), "expected timeouts to be traced"); + assert!(reasons.iter().any(|r| r.starts_with("search_timeout>1ms")), "{reasons:?}"); + assert_eq!(s.counters.policy_fallbacks as usize, reasons.len()); + assert!(g.timeouts() >= 1); + // A fallback decision still carries a full, valid distribution and a sent action. + for d in dec.iter().filter(|d| !d["fallback_reason"].is_null()) { + assert!(!d["dist"].as_array().unwrap().is_empty()); + assert!(d["sent"].is_string()); + } + // Each decision, fallback or not, returned promptly (hard budget + session overhead). + assert!(dec.iter().all(|d| d["latency_us"].as_u64().unwrap() < 2_000_000), "decision exceeded 2 s"); +} diff --git a/arena/openpoker/tests/session_replay.rs b/arena/openpoker/tests/session_replay.rs new file mode 100644 index 00000000..7922c08d --- /dev/null +++ b/arena/openpoker/tests/session_replay.rs @@ -0,0 +1,827 @@ +//! Protocol parsing + replay on hand-crafted message sequences that follow +//! docs.openpoker.ai (no raw recordings existed in the old crate's benchmark JSONs; the live +//! smoke test writes a raw trace that `tests/fixtures/` can be extended with). + +use bench::builtin::builtin; +use bench::policy::{Dist, Player, PolicyFactory, View}; +use cards::Card; +use nlhe::{Action, GameConfig, State}; +use openpoker::analyze::{analyze, load_trace, HandRecord}; +use openpoker::session::{HuMode, PolicySpec, Session, SessionConfig}; +use openpoker::trace::MemSink; +use serde_json::{json, Value}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; + +// ------------------------------------------------------------------ mocks + +struct CallFactory { + observed: Arc, + shove: bool, +} +struct CallPlayer { + observed: Arc, + shove: bool, +} +impl PolicyFactory for CallFactory { + fn name(&self) -> String { + "mock-call".into() + } + fn new_player(&self, _seat: usize, _cfg: &GameConfig, _seed: u64) -> Box { + Box::new(CallPlayer { observed: self.observed.clone(), shove: self.shove }) + } +} +impl Player for CallPlayer { + fn observe(&mut self, _pre: &State, _seat: usize, _a: Action) { + self.observed.fetch_add(1, Ordering::SeqCst); + } + fn dist(&mut self, v: &View, _hole: [Card; 2]) -> Dist { + let l = v.state.legal(); + if self.shove && l.can_raise { + return Dist::pure(Action::RaiseTo(l.max_raise_to)); + } + Dist::pure(if l.can_check { Action::Check } else { Action::Call }) + } +} + +fn spec(embed6: bool, shove: bool) -> (PolicySpec, Arc) { + let obs = Arc::new(AtomicUsize::new(0)); + let s = PolicySpec { + label: "mock-call".into(), + main: Arc::new(CallFactory { observed: obs.clone(), shove }), + embed6, + fallback: builtin("tag").unwrap(), + hu: HuMode::Fallback, + }; + (s, obs) +} + +fn cfg(hands: usize, auto_rebuy: bool) -> SessionConfig { + SessionConfig { buy_in: 2000, target_hands: hands, seed: 5, auto_rebuy, raw: true, sizing: "tiny".into(), buckets: "coarse".into(), max_stack_bb: 0.0 } +} + +struct H { + s: Session, + sink: MemSink, +} +impl H { + fn new(spec: PolicySpec, hands: usize) -> H { + let sink = MemSink::default(); + H { s: Session::new(cfg(hands, true), spec, Box::new(sink.clone())), sink } + } + fn with_cap(spec: PolicySpec, hands: usize, cap_bb: f64) -> H { + let sink = MemSink::default(); + let mut c = cfg(hands, true); + c.max_stack_bb = cap_bb; + H { s: Session::new(c, spec, Box::new(sink.clone())), sink } + } + fn send(&mut self, m: Value) -> Vec { + self.s.on_message(&m) + } + fn bad_anomalies(&self) -> Vec { + self.sink + .of_kind("anomaly") + .into_iter() + .filter(|a| { + matches!( + a["what"].as_str().unwrap_or(""), + "desync" | "replay_failed_will_rebuild" | "engine_server_mismatch" | "illegal_choice_replaced" | "profit_mismatch" | "your_turn_without_hand" + ) + }) + .collect() + } + fn hands(&self) -> Vec { + let text: String = self.sink.records().iter().map(|r| r.to_string() + "\n").collect(); + load_trace(&text).0 + } +} + +fn pa(seat: usize, action: &str, amount: Option, street: &str, stack: i64, pot: i64) -> Value { + json!({"type":"player_action","seat":seat,"name":format!("bot{seat}"),"action":action,"amount":amount,"street":street,"stack":stack,"pot":pot}) +} + +fn players(stacks: [i64; 6], status: [&str; 6]) -> Value { + Value::Array((0..6).map(|i| json!({"seat": i, "name": format!("bot{i}"), "stack": stacks[i], "status": status[i]})).collect()) +} + +fn table_joined() -> Value { + json!({"type":"table_joined","table_id":"t1","seat":2,"players":(0..6).map(|i| json!({"seat":i,"name":format!("bot{i}"),"stack":2000})).collect::>()}) +} + +fn hand_start(id: &str) -> Value { + json!({"type":"hand_start","hand_id":id,"seat":2,"dealer_seat":0,"blinds":{"small_blind":10,"big_blind":20}}) +} + +fn your_turn(id: &str, tok: &str, valid: Value, pot: i64, board: &[&str], players: Value) -> Value { + json!({"type":"your_turn","hand_id":id,"turn_token":tok,"valid_actions":valid,"pot":pot,"community_cards":board,"players":players,"min_raise":null,"max_raise":null}) +} + +/// The canonical 6-max hand: hero BB seat 2 calls a HJ open, checks the flop, calls a turn bet. +/// Returns the action messages we sent. +fn play_canonical_hand(h: &mut H, id: &str) -> Vec { + let mut sent = Vec::new(); + h.send(hand_start(id)); + h.send(json!({"type":"hole_cards","cards":["Ah","Ad"]})); + h.send(pa(3, "fold", None, "preflop", 2000, 30)); + h.send(pa(4, "raise", Some(60), "preflop", 1940, 90)); + h.send(pa(5, "fold", None, "preflop", 2000, 90)); + h.send(pa(0, "fold", None, "preflop", 2000, 90)); + h.send(pa(1, "fold", None, "preflop", 1990, 90)); + let pl = players([2000, 1990, 1980, 2000, 1940, 2000], ["folded", "folded", "active", "folded", "active", "folded"]); + let out = h.send(your_turn( + id, + &format!("{id}-t1"), + json!([{"action":"fold"},{"action":"call","amount":40},{"action":"raise","min":100,"max":2000}]), + 90, + &[], + pl, + )); + assert_eq!(out.len(), 1, "one action per turn"); + assert_eq!(out[0]["action"], "call"); + sent.push(out[0].clone()); + h.send(json!({"type":"action_ack","client_action_id":out[0]["client_action_id"],"status":"accepted"})); + h.send(pa(2, "call", Some(40), "preflop", 1940, 130)); + h.send(json!({"type":"community_cards","cards":["2c","7d","9h"],"street":"flop"})); + let st = ["folded", "folded", "active", "folded", "active", "folded"]; + let pl_at = |cur: [i64; 6]| players(cur, st); + let pl2 = pl_at([2000, 1990, 1940, 2000, 1940, 2000]); + let out = h.send(your_turn( + id, + &format!("{id}-t2"), + json!([{"action":"check"},{"action":"raise","min":20,"max":1940}]), + 130, + &["2c", "7d", "9h"], + pl2.clone(), + )); + assert_eq!(out[0]["action"], "check"); + sent.push(out[0].clone()); + h.send(pa(2, "check", None, "flop", 1940, 130)); + h.send(pa(4, "check", None, "flop", 1940, 130)); + h.send(json!({"type":"community_cards","cards":["Qs"],"street":"turn"})); + let out = h.send(your_turn( + id, + &format!("{id}-t3"), + json!([{"action":"check"},{"action":"raise","min":20,"max":1940}]), + 130, + &["2c", "7d", "9h", "Qs"], + pl2.clone(), + )); + assert_eq!(out[0]["action"], "check"); + sent.push(out[0].clone()); + h.send(pa(2, "check", None, "turn", 1940, 130)); + h.send(pa(4, "raise", Some(100), "turn", 1840, 230)); + let out = h.send(your_turn( + id, + &format!("{id}-t4"), + json!([{"action":"fold"},{"action":"call","amount":100},{"action":"raise","min":200,"max":1940}]), + 230, + &["2c", "7d", "9h", "Qs"], + pl_at([2000, 1990, 1940, 2000, 1840, 2000]), + )); + assert_eq!(out[0]["action"], "call"); + sent.push(out[0].clone()); + // Echo of our call is NOT sent here: the session must synthesise it before the next event. + h.send(json!({"type":"community_cards","cards":["3d"],"street":"river"})); + let out = h.send(your_turn( + id, + &format!("{id}-t5"), + json!([{"action":"check"},{"action":"raise","min":20,"max":1840}]), + 330, + &["2c", "7d", "9h", "Qs", "3d"], + pl_at([2000, 1990, 1840, 2000, 1840, 2000]), + )); + assert_eq!(out[0]["action"], "check"); + sent.push(out[0].clone()); + h.send(pa(2, "check", None, "river", 1840, 330)); + h.send(pa(4, "check", None, "river", 1840, 330)); + let out = h.send(json!({ + "type":"hand_result","hand_id":id,"pot":330,"total_pot":330, + "winners":[{"seat":2,"name":"bot2","amount":170,"stack":2170,"hand_description":"Pair of Aces"}], + "payouts":[{"seat":2,"amount":330}], + "shown_cards":{"2":["Ah","Ad"],"4":["Ks","Kc"]}, + "final_stacks":{"0":2000,"1":1990,"2":2170,"3":2000,"4":1840,"5":2000} + })); + assert!(out.is_empty() || out[0]["type"] == "leave_table"); + sent +} + +// ------------------------------------------------------------------ tests + +#[test] +fn canonical_hand_replays_cleanly() { + let (sp, obs) = spec(false, false); + let mut h = H::new(sp, 100); + h.send(json!({"type":"connected","agent_id":"a","name":"me"})); + h.send(table_joined()); + play_canonical_hand(&mut h, "h1"); + assert!(h.bad_anomalies().is_empty(), "{:#?}", h.bad_anomalies()); + let hands = h.hands(); + assert_eq!(hands.len(), 1); + let r = &hands[0]; + assert_eq!(r.profit, Some(170)); + assert_eq!(r.profit_src, "final_stacks"); + assert_eq!(r.position, "BB"); + assert_eq!(r.n_players, 6); + assert_eq!(r.board.len(), 5); + assert_eq!(r.lock_len, Some(5)); + assert!(r.showdown && !r.desync); + assert_eq!(r.decisions, 5); + assert_eq!(r.fallbacks, 0); + assert_eq!(r.issues, 0, "engine and server must agree: {:#?}", h.sink.of_kind("decision").iter().map(|d| d["issues"].clone()).collect::>()); + let hero = r.players.iter().find(|p| p.seat == 2).unwrap(); + assert_eq!((hero.start_stack, hero.contrib), (Some(2000), Some(160))); + assert!(obs.load(Ordering::SeqCst) >= 5); + assert_eq!(h.s.counters.hands_done, 1); + assert_eq!(h.s.counters.acks, 1); + assert!(!h.sink.of_kind("raw").is_empty()); + let d = &h.sink.of_kind("decision")[0]; + assert_eq!(d["chosen"], "call"); + assert_eq!(d["sent"], "call"); + assert_eq!(d["dist"][0][0], "call"); +} + +#[test] +fn analyzer_runs_on_session_trace() { + let (sp, _) = spec(false, false); + let mut h = H::new(sp, 100); + h.send(table_joined()); + play_canonical_hand(&mut h, "h1"); + let text: String = h.sink.records().iter().map(|r| r.to_string() + "\n").collect(); + let (hands, sum) = load_trace(&text); + assert_eq!(hands.len(), 1); + assert_eq!(sum.decisions, 5); + let r = analyze(&hands, 100); + assert!((r.raw.mean_bb100 - 170.0 / 20.0 * 100.0).abs() < 1e-9); + assert_eq!(r.by_position[0].key, "BB"); + assert!(r.by_opponent.iter().any(|g| g.key == "bot4")); +} + +#[test] +fn target_hands_reached_sends_leave_table() { + let (sp, _) = spec(false, false); + let mut h = H::new(sp, 1); + h.send(table_joined()); + h.send(hand_start("h1")); + h.send(json!({"type":"hole_cards","cards":["7h","2d"]})); + let out = h.send(json!({"type":"hand_result","hand_id":"h1","winners":[],"final_stacks":{"2":1980}})); + assert!(h.s.done); + assert!(out.iter().any(|m| m["type"] == "leave_table")); +} + +#[test] +fn short_handed_blueprint_embedding_feeds_phantom_folds() { + // 4 players: seats 0 (BTN), 1 (SB), 2 (hero BB), 4 (UTG-equivalent). Dealer 0. + let (sp, obs) = spec(true, false); + let mut h = H::new(sp, 100); + h.send(json!({"type":"table_joined","table_id":"t","seat":2,"players":[ + {"seat":0,"stack":2000},{"seat":1,"stack":2000},{"seat":2,"stack":2000},{"seat":4,"stack":2000}]})); + h.send(hand_start("h1")); + h.send(json!({"type":"hole_cards","cards":["Kh","Kd"]})); + h.send(pa(4, "raise", Some(60), "preflop", 1940, 90)); + h.send(pa(0, "fold", None, "preflop", 2000, 90)); + h.send(pa(1, "fold", None, "preflop", 1990, 90)); + let pl = json!([ + {"seat":0,"stack":2000,"status":"folded"},{"seat":1,"stack":1990,"status":"folded"}, + {"seat":2,"stack":1980,"status":"active"},{"seat":4,"stack":1940,"status":"active"}, + {"seat":3,"stack":0,"status":"sitting_out"} + ]); + let out = h.send(your_turn( + "h1", + "tk", + json!([{"action":"fold"},{"action":"call","amount":40},{"action":"raise","min":100,"max":2000}]), + 90, + &[], + pl, + )); + assert_eq!(out[0]["action"], "call"); + assert!(h.bad_anomalies().is_empty(), "{:#?}", h.bad_anomalies()); + // 2 phantom folds (6-4) + the 3 real actions before the hero acts. + assert_eq!(obs.load(Ordering::SeqCst), 2 + 3); + let d = &h.sink.of_kind("decision")[0]; + assert_eq!(d["meta"]["n_players"], 4); + assert_eq!(d["meta"]["position"], "BB"); +} + +#[test] +fn heads_up_uses_fallback_policy_on_native_engine() { + let (sp, obs) = spec(true, false); + let mut h = H::new(sp, 100); + h.send(json!({"type":"table_joined","table_id":"t","seat":1,"players":[{"seat":0,"stack":2000},{"seat":1,"stack":2000}]})); + // Open Poker heads-up: dealer 0 is the BB, so hero (seat 1) is the SB and acts first. + h.send(json!({"type":"hand_start","hand_id":"hu","seat":1,"dealer_seat":0,"blinds":{"small_blind":10,"big_blind":20}})); + h.send(json!({"type":"hole_cards","cards":["Ah","Kd"]})); + let out = h.send(your_turn( + "hu", + "tk", + json!([{"action":"fold"},{"action":"call","amount":10},{"action":"raise","min":40,"max":2000},{"action":"all_in","amount":2000}]), + 30, + &[], + json!([{"seat":0,"stack":1980},{"seat":1,"stack":1990}]), + )); + assert_eq!(out.len(), 1); + assert!(h.bad_anomalies().is_empty(), "{:#?}", h.bad_anomalies()); + let d = &h.sink.of_kind("decision")[0]; + assert!(d["meta"]["policy"].as_str().unwrap().starts_with("fallback:")); + assert_eq!(d["meta"]["position"], "BTN/SB"); + assert_eq!(obs.load(Ordering::SeqCst), 0, "main policy must not see heads-up hands"); + assert!(d["issues"].as_array().unwrap().is_empty(), "{d}"); +} + +#[test] +fn all_in_runout_records_lock_and_hands_are_adjustable() { + // Hero shoves preflop with AA (mock shoves), villain (seat 4) calls all-in, board runs out. + let (sp, _) = spec(false, true); + let mut h = H::new(sp, 100); + h.send(table_joined()); + h.send(hand_start("allin")); + h.send(json!({"type":"hole_cards","cards":["Ah","Ad"]})); + h.send(pa(3, "fold", None, "preflop", 2000, 30)); + h.send(pa(4, "raise", Some(60), "preflop", 1940, 90)); + h.send(pa(5, "fold", None, "preflop", 2000, 90)); + h.send(pa(0, "fold", None, "preflop", 2000, 90)); + h.send(pa(1, "fold", None, "preflop", 1990, 90)); + let pl = players([2000, 1990, 1980, 2000, 1940, 2000], ["folded", "folded", "active", "folded", "active", "folded"]); + let out = h.send(your_turn( + "allin", + "tk1", + json!([{"action":"fold"},{"action":"call","amount":40},{"action":"raise","min":100,"max":2000}]), + 90, + &[], + pl, + )); + assert_eq!(out[0]["action"], "raise"); + assert_eq!(out[0]["amount"], 2000, "mock shoves: raise-to = stack + street bet"); + h.send(pa(2, "raise", Some(2000), "preflop", 0, 2070)); + h.send(pa(4, "call", None, "preflop", 0, 4010)); + h.send(json!({"type":"community_cards","cards":["2c","7d","9h"],"street":"flop"})); + h.send(json!({"type":"community_cards","cards":["Js"],"street":"turn"})); + h.send(json!({"type":"community_cards","cards":["3d"],"street":"river"})); + h.send(json!({ + "type":"hand_result","hand_id":"allin","winners":[{"seat":2,"amount":2010}],"payouts":[{"seat":2,"amount":4010}], + "shown_cards":[{"seat":2,"cards":["Ah","Ad"]},{"seat":4,"cards":["Ks","Kc"]}], + "final_stacks":[{"seat":2,"stack":4010},{"seat":4,"stack":0},{"seat":0,"stack":2000},{"seat":1,"stack":1990},{"seat":3,"stack":2000},{"seat":5,"stack":2000}] + })); + assert!(h.bad_anomalies().is_empty(), "{:#?}", h.bad_anomalies()); + let hands = h.hands(); + assert_eq!(hands.len(), 1); + let r = &hands[0]; + assert_eq!(r.lock_len, Some(0), "all-in before the flop"); + assert_eq!(r.profit, Some(2010)); + // AA vs KK all-in preflop: ~82% of a 4010 pot minus the 2000 invested. + let ev = openpoker::analyze::allin_ev(r, 40_000).expect("cards known -> adjustable"); + assert!(ev > 1100.0 && ev < 1500.0, "ev {ev}"); +} + +#[test] +fn duplicates_and_stale_sequence_numbers_are_ignored() { + let (sp, _) = spec(false, false); + let mut h = H::new(sp, 100); + h.send(table_joined()); + h.send(json!({"type":"player_joined","seat":3,"name":"x","stack":2000,"table_seq":10})); + let out = h.send(json!({"type":"player_left","seat":3,"table_seq":9})); + assert!(out.is_empty()); + h.send(hand_start("d1")); + h.send(json!({"type":"hole_cards","cards":["Ah","Ad"]})); + h.send(pa(3, "fold", None, "preflop", 2000, 30)); + h.send(pa(4, "raise", Some(60), "preflop", 1940, 90)); + h.send(pa(5, "fold", None, "preflop", 2000, 90)); + h.send(pa(0, "fold", None, "preflop", 2000, 90)); + h.send(pa(1, "fold", None, "preflop", 1990, 90)); + let mk = || { + your_turn( + "d1", + "same-token", + json!([{"action":"fold"},{"action":"call","amount":40},{"action":"raise","min":100,"max":2000}]), + 90, + &[], + players([2000, 1990, 1980, 2000, 1940, 2000], ["folded", "folded", "active", "folded", "active", "folded"]), + ) + }; + assert_eq!(h.send(mk()).len(), 1); + assert_eq!(h.send(mk()).len(), 0, "same turn_token delivered twice must not act twice"); +} + +#[test] +fn rejection_is_retried_once_with_a_safe_action() { + let (sp, _) = spec(false, true); + let mut h = H::new(sp, 100); + h.send(table_joined()); + h.send(hand_start("r1")); + h.send(json!({"type":"hole_cards","cards":["Ah","Ad"]})); + h.send(pa(3, "fold", None, "preflop", 2000, 30)); + h.send(pa(4, "raise", Some(60), "preflop", 1940, 90)); + h.send(pa(5, "fold", None, "preflop", 2000, 90)); + h.send(pa(0, "fold", None, "preflop", 2000, 90)); + h.send(pa(1, "fold", None, "preflop", 1990, 90)); + let out = h.send(your_turn( + "r1", + "tk", + json!([{"action":"fold"},{"action":"call","amount":40},{"action":"raise","min":100,"max":2000}]), + 90, + &[], + players([2000, 1990, 1980, 2000, 1940, 2000], ["folded", "folded", "active", "folded", "active", "folded"]), + )); + assert_eq!(out[0]["action"], "raise"); + let retry = h.send(json!({"type":"error","code":"invalid_action","message":"nope"})); + assert_eq!(retry.len(), 1); + assert_eq!(retry[0]["action"], "fold", "passive fallback when facing a bet and check is not offered"); + assert_ne!(retry[0]["client_action_id"], out[0]["client_action_id"]); + assert_eq!(retry[0]["turn_token"], "tk"); + let again = h.send(json!({"type":"error","code":"invalid_action"})); + assert!(again.is_empty(), "only one retry"); + assert_eq!(h.s.counters.rejects, 2); + let stale = h.send(json!({"type":"action_rejected","code":"stale_turn_token"})); + assert!(stale.is_empty()); +} + +#[test] +fn busted_without_auto_rebuy_rebuys_then_rejoins() { + let (sp, _) = spec(false, false); + let sink = MemSink::default(); + let mut s = Session::new(cfg(10, false), sp, Box::new(sink)); + let out = s.on_message(&json!({"type":"busted","options":["rebuy","leave"]})); + assert_eq!(out[0]["type"], "rebuy"); + let out = s.on_message(&json!({"type":"rebuy_confirmed","new_stack":1500})); + assert_eq!(out[0]["type"], "join_lobby"); + assert_eq!(out[0]["buy_in"], 2000); + let out = s.on_message(&json!({"type":"table_closed","reason":"x"})); + assert_eq!(out[0]["type"], "join_lobby"); +} + +#[test] +fn busted_with_chips_left_rejoins_when_rebuy_is_refused() { + // Live: after a bust the season balance still held chips, so the server answered our + // rebuy with `cannot_rebuy` — we must rejoin a table instead of idling. + let (sp, _) = spec(false, false); + let sink = MemSink::default(); + let mut s = Session::new(cfg(10, false), sp, Box::new(sink)); + let out = s.on_message(&json!({"type":"busted","options":["rebuy","leave"]})); + assert_eq!(out[0]["type"], "rebuy"); + let out = s.on_message(&json!({"type":"error","code":"cannot_rebuy","message":"Cannot rebuy — you still have chips."})); + assert_eq!(out[0]["type"], "join_lobby"); + assert_eq!(out[0]["buy_in"], 2000); +} + +#[test] +fn resync_snapshot_restores_turn() { + // Warm reconnect: the server replays the hand's events, then a snapshot with our turn token. + let (sp, _) = spec(false, false); + let mut h = H::new(sp, 100); + h.send(table_joined()); + let events = vec![ + hand_start("rs"), + json!({"type":"hole_cards","cards":["Ah","Ad"]}), + pa(3, "fold", None, "preflop", 2000, 30), + pa(4, "raise", Some(60), "preflop", 1940, 90), + pa(5, "fold", None, "preflop", 2000, 90), + pa(0, "fold", None, "preflop", 2000, 90), + pa(1, "fold", None, "preflop", 1990, 90), + ]; + let out = h.send(json!({ + "type":"resync_response","role":"player","from_table_seq":1,"to_table_seq":8, + "replayed_events": events, + "snapshot":{ + "street":"preflop","dealer_seat":0,"pot":90,"actor_seat":2,"to_call":40,"min_raise_to":100,"max_raise_to":2000, + "board":[], + "seats":[ + {"seat":0,"stack":2000,"bet":0,"status":"folded","in_hand":false}, + {"seat":1,"stack":1990,"bet":10,"status":"folded","in_hand":false}, + {"seat":2,"stack":1980,"bet":20,"status":"active","in_hand":true}, + {"seat":3,"stack":2000,"bet":0,"status":"folded","in_hand":false}, + {"seat":4,"stack":1940,"bet":60,"status":"active","in_hand":true}, + {"seat":5,"stack":2000,"bet":0,"status":"folded","in_hand":false} + ], + "hero":{"seat":2,"hole_cards":["Ah","Ad"],"turn_token":"resync-tok","valid_actions":[{"action":"fold"},{"action":"call","amount":40},{"action":"raise","min":100,"max":2000}]} + } + })); + assert_eq!(out.len(), 1, "snapshot with our turn must produce exactly one action"); + assert_eq!(out[0]["turn_token"], "resync-tok"); + assert_eq!(out[0]["action"], "call"); + assert!(h.bad_anomalies().is_empty(), "{:#?}", h.bad_anomalies()); + assert_eq!(h.s.counters.fallbacks, 0); +} + +#[test] +fn unplaceable_action_falls_back_to_passive_and_flags_desync() { + let (sp, _) = spec(false, false); + let mut h = H::new(sp, 100); + h.send(table_joined()); + h.send(hand_start("bad")); + h.send(json!({"type":"hole_cards","cards":["Ah","Ad"]})); + h.send(pa(3, "fold", None, "preflop", 2000, 30)); + // Seat 5 acts before seat 4: out of turn. + h.send(pa(5, "raise", Some(60), "preflop", 1940, 90)); + h.send(pa(4, "fold", None, "preflop", 2000, 90)); + let out = h.send(your_turn( + "bad", + "tk", + json!([{"action":"fold"},{"action":"call","amount":40},{"action":"raise","min":100,"max":2000}]), + 90, + &[], + players([2000, 1990, 1980, 2000, 2000, 1940], ["active", "active", "active", "folded", "folded", "active"]), + )); + assert_eq!(out.len(), 1); + assert_eq!(out[0]["action"], "fold", "safe action when facing a bet"); + assert_eq!(h.s.counters.fallbacks, 1); + assert_eq!(h.s.counters.decisions, 1); + let d = &h.sink.of_kind("decision")[0]; + assert!(d["fallback"].is_string()); + h.send(json!({"type":"hand_result","hand_id":"bad","winners":[],"final_stacks":{"2":1980}})); + assert!(h.hands()[0].desync); +} + +#[test] +fn history_fixture_loads_and_reconstructs() { + let text = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/history_sample.json")).unwrap(); + let v: Value = serde_json::from_str(&text).unwrap(); + let n = v["hands"].as_array().unwrap().len(); + let recs = openpoker::analyze::load_history(&v); + assert_eq!(recs.len(), n); + let total: i64 = v["hands"].as_array().unwrap().iter().map(|h| h["profit"].as_i64().unwrap()).sum(); + assert_eq!(recs.iter().filter_map(|r| r.profit).sum::(), total); + let rep = analyze(&recs, 1000); + assert_eq!(rep.hands, n); + assert!(rep.render().contains("bb/100")); + // The export is lossy (street labels, call amounts, pot_total): only clean hands reconstruct. + let ok = recs.iter().filter(|r| !r.players.is_empty() && !r.desync).count(); + assert!(ok >= 3, "only {ok}/{n} history hands reconstructed"); +} + +// ------------------------------------------------------------------ real recording + +/// Plays back the actions of a recorded decision list, ignoring what the engine says. +struct Scripted { + queue: Arc>>, +} +struct ScriptedPlayer { + queue: Arc>>, +} +impl PolicyFactory for Scripted { + fn name(&self) -> String { + "scripted".into() + } + fn new_player(&self, _seat: usize, _cfg: &GameConfig, _seed: u64) -> Box { + Box::new(ScriptedPlayer { queue: self.queue.clone() }) + } +} +impl Player for ScriptedPlayer { + fn dist(&mut self, _v: &View, _hole: [Card; 2]) -> Dist { + Dist::pure(self.queue.lock().unwrap().pop_front().expect("more decisions than recorded")) + } +} + +/// `tests/fixtures/smoke_raw.jsonl` is a real 10-hand session (builtin:tag, 2026-10-13, 3-6 +/// handed tables, names redacted). Replaying every inbound message with a policy that repeats +/// the recorded decisions must reproduce the recorded outbound actions exactly, with a clean +/// engine replay (no desync, no engine/server disagreement) and `final_stacks`-based profits. +#[test] +fn recorded_live_session_replays_exactly() { + let text = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/smoke_raw.jsonl")).unwrap(); + let rows: Vec = text.lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + let mut queue = std::collections::VecDeque::new(); + let mut recorded_out = Vec::new(); + for r in &rows { + if r["dir"] == "out" && r["msg"]["type"] == "action" { + let m = &r["msg"]; + let a = match m["action"].as_str().unwrap() { + "fold" => Action::Fold, + "check" => Action::Check, + "call" => Action::Call, + "raise" => Action::RaiseTo(m["amount"].as_i64().unwrap() as i32 * 5), + other => panic!("unexpected recorded action {other}"), + }; + queue.push_back(a); + recorded_out.push((m["action"].clone(), m["amount"].clone(), m["turn_token"].clone())); + } + } + let n_results = rows.iter().filter(|r| r["dir"] == "in" && r["msg"]["type"] == "hand_result").count(); + assert!(n_results >= 10, "the recording ends with at least 10 results"); + let sp = PolicySpec { + label: "scripted".into(), + main: Arc::new(Scripted { queue: Arc::new(std::sync::Mutex::new(queue)) }), + embed6: true, + fallback: builtin("tag").unwrap(), + hu: HuMode::Policy, + }; + let mut h = H::new(sp, 10); + let mut sent = Vec::new(); + for r in rows.iter().filter(|r| r["dir"] == "in") { + for m in h.send(r["msg"].clone()) { + if m["type"] == "action" { + sent.push((m["action"].clone(), m["amount"].clone(), m["turn_token"].clone())); + } + } + } + assert_eq!(sent.len(), recorded_out.len()); + for (i, (a, b)) in sent.iter().zip(&recorded_out).enumerate() { + // The recording has no `amount` key for non-raises; ours is JSON null in the same spot. + assert_eq!((&a.0, &a.2), (&b.0, &b.2), "decision {i}"); + assert!(a.1 == b.1 || (a.1.is_null() && b.1.is_null()), "decision {i}: amount {} vs {}", a.1, b.1); + } + assert!(h.bad_anomalies().is_empty(), "{:#?}", h.bad_anomalies()); + let hands = h.hands(); + assert!(hands.len() >= 10); + for r in &hands { + assert!(!r.desync, "{}", r.hand_id); + assert_eq!(r.issues, 0, "{}: {:#?}", r.hand_id, h.sink.of_kind("decision").iter().filter(|d| d["hand_id"] == r.hand_id.as_str()).map(|d| d["issues"].clone()).collect::>()); + assert_eq!(r.profit_src, "final_stacks"); + assert!(r.profit.is_some() && r.bb == 20); + } + assert!(h.s.done); + assert_eq!(h.s.counters.fallbacks, 0); + // The report over a real trace renders. + let rep = analyze(&hands, 2000); + assert_eq!(rep.hands, hands.len()); + // Every showdown hand with cards for all live players must be adjustable or river-locked. + for r in hands.iter().filter(|r| r.showdown) { + assert!(r.lock_len.is_some(), "showdown hand without lock info: {}", r.hand_id); + } +} + +/// A real (toy-trained) 6-player blueprint through the short-handed embedding: the policy sees +/// the phantom folds as part of its abstract history and answers from its tables. +#[test] +fn toy_blueprint_plays_a_four_handed_embedded_hand() { + let bp = Arc::new(bench::bp::train_toy(6, 20_000, 3)); + let sp = PolicySpec { label: "toy-bp".into(), main: bp.clone(), embed6: true, fallback: builtin("tag").unwrap(), hu: HuMode::Fallback }; + let mut h = H::new(sp, 100); + h.send(json!({"type":"table_joined","table_id":"t","seat":2,"players":[ + {"seat":0,"stack":2000},{"seat":1,"stack":2000},{"seat":2,"stack":2000},{"seat":4,"stack":2000}]})); + h.send(hand_start("h1")); + h.send(json!({"type":"hole_cards","cards":["Kh","Kd"]})); + h.send(pa(4, "raise", Some(60), "preflop", 1940, 90)); + h.send(pa(0, "fold", None, "preflop", 2000, 90)); + h.send(pa(1, "fold", None, "preflop", 1990, 90)); + let pl = json!([ + {"seat":0,"stack":2000},{"seat":1,"stack":1990},{"seat":2,"stack":1980},{"seat":4,"stack":1940} + ]); + let out = h.send(your_turn( + "h1", + "tk", + json!([{"action":"fold"},{"action":"call","amount":40},{"action":"raise","min":100,"max":2000},{"action":"all_in","amount":2000}]), + 90, + &[], + pl, + )); + assert_eq!(out.len(), 1); + assert!(h.bad_anomalies().is_empty(), "{:#?}", h.bad_anomalies()); + let d = &h.sink.of_kind("decision")[0]; + assert_eq!(d["meta"]["n_players"], 4); + assert!(d["fallback"].is_null()); + assert!(!d["dist"].as_array().unwrap().is_empty()); +} + +// ------------------------------------------------------------------ stack limit (reset + guard) + +fn empty_hand(h: &mut H, id: &str, final_stack: i64) -> Vec { + h.send(hand_start(id)); + h.send(json!({"type":"hole_cards","cards":["7h","2d"]})); + h.send(json!({"type":"hand_result","hand_id":id,"winners":[],"final_stacks":{"2":final_stack}})) +} + +fn count(out: &[Value], ty: &str) -> usize { + out.iter().filter(|m| m["type"] == ty).count() +} + +fn own_left() -> Value { + json!({"type":"player_left","seat":2,"name":"me","reason":"left"}) +} + +#[test] +fn over_deep_stack_leaves_once_rejoins_with_buy_in_and_resumes() { + let (sp, _) = spec(false, false); + let mut h = H::with_cap(sp, 100, 150.0); + h.send(json!({"type":"connected","agent_id":"a","name":"me"})); + h.send(table_joined()); + // 1,000 bb... well over 150 bb (cap = 3000 chips): leave, exactly once. + let out = empty_hand(&mut h, "big1", 22_000); + assert_eq!(count(&out, "leave_table"), 1, "{out:?}"); + // Still waiting for the server: another hand result must not send a second leave. + let out = empty_hand(&mut h, "big2", 22_000); + assert_eq!(count(&out, "leave_table"), 0); + // Server confirms our departure -> join the lobby with the normal buy-in. + let out = h.send(own_left()); + assert_eq!(count(&out, "join_lobby"), 1); + let jl = out.iter().find(|m| m["type"] == "join_lobby").unwrap(); + assert_eq!(jl["buy_in"], 2000); + assert_eq!(h.s.counters.stack_resets, 1); + // Another player leaving is not us. + assert!(h.send(json!({"type":"player_left","seat":4,"name":"bot4","reason":"left"})).is_empty()); + h.send(json!({"type":"lobby_joined","position":1})); + // New table, fresh sequence numbers; play resumes and a normal-depth hand does not reset. + h.send(table_joined()); + play_canonical_hand(&mut h, "after"); + assert!(h.bad_anomalies().is_empty(), "{:#?}", h.bad_anomalies()); + assert_eq!(h.s.counters.stack_resets, 1); + assert_eq!(h.s.counters.hands_done, 3); + assert!(h.sink.of_kind("note").iter().any(|n| n["what"] == "stack_reset_leave")); + assert!(h.s.on_idle().is_empty()); +} + +#[test] +fn refused_leave_falls_back_to_the_guard_with_cooldown() { + let (sp, _) = spec(false, false); + let mut h = H::with_cap(sp, 100, 150.0); + h.send(json!({"type":"connected","agent_id":"a","name":"me"})); + h.send(table_joined()); + assert_eq!(count(&empty_hand(&mut h, "b1", 22_000), "leave_table"), 1); + let out = h.send(json!({"type":"error","code":"cooldown","message":"nope"})); + assert!(out.is_empty()); + assert_eq!(h.s.counters.reset_aborts, 1); + assert_eq!(h.s.counters.stack_resets, 0); + // Cooldown: no leave/rejoin loop on the next over-deep hands. + assert_eq!(count(&empty_hand(&mut h, "b2", 22_000), "leave_table"), 0); + assert!(h.sink.of_kind("note").iter().any(|n| n["what"] == "stack_reset_aborted")); +} + +#[test] +fn stalled_rejoin_is_retried_then_given_up() { + let (sp, _) = spec(false, false); + let mut h = H::with_cap(sp, 100, 150.0); + h.send(json!({"type":"connected","agent_id":"a","name":"me"})); + h.send(table_joined()); + empty_hand(&mut h, "b1", 22_000); + h.send(own_left()); + let t0 = std::time::Instant::now(); + assert!(h.s.on_idle_at(t0).is_empty(), "too early"); + let out = h.s.on_idle_at(t0 + std::time::Duration::from_secs(16)); + assert_eq!(count(&out, "join_lobby"), 1); + // table_joined ends the rejoin; no more retries. + h.send(table_joined()); + assert!(h.s.on_idle_at(t0 + std::time::Duration::from_secs(100)).is_empty()); +} + +/// Hero (BB, seat 2) at 1,000 bb faces a 3x open; the mock policy shoves. +fn deep_hand(h: &mut H, id: &str) -> Vec { + h.send(hand_start(id)); + h.send(json!({"type":"hole_cards","cards":["Ah","Ad"]})); + h.send(pa(3, "fold", None, "preflop", 20_000, 30)); + h.send(pa(4, "raise", Some(60), "preflop", 19_940, 90)); + h.send(pa(5, "fold", None, "preflop", 20_000, 90)); + h.send(pa(0, "fold", None, "preflop", 20_000, 90)); + h.send(pa(1, "fold", None, "preflop", 19_990, 90)); + let pl = players([20_000, 19_990, 19_980, 20_000, 19_940, 20_000], ["folded", "folded", "active", "folded", "active", "folded"]); + h.send(your_turn( + id, + "tk", + json!([{"action":"fold"},{"action":"call","amount":40},{"action":"raise","min":100,"max":20000}]), + 90, + &[], + pl, + )) +} + +#[test] +fn deep_stack_jam_is_capped_at_max_stack_bb() { + let (sp, _) = spec(false, true); + let mut h = H::with_cap(sp, 100, 150.0); + h.send(table_joined()); + let out = deep_hand(&mut h, "deep"); + assert_eq!(out[0]["action"], "raise"); + assert_eq!(out[0]["amount"], 3000, "150 bb x 20 = 3000 chips total, not the 20,000 jam"); + let d = &h.sink.of_kind("decision")[0]; + assert!(d["stack_guard"].as_str().unwrap().contains("raise:3000"), "{d}"); + assert_eq!(h.s.counters.stack_guards, 1); + // The policy observes what was actually sent: echo + villain fold replay cleanly. + h.send(pa(2, "raise", Some(3000), "preflop", 17_000, 3070)); + h.send(pa(4, "fold", None, "preflop", 19_940, 3070)); + h.send(json!({"type":"hand_result","hand_id":"deep","winners":[{"seat":2,"amount":60}],"payouts":[{"seat":2,"amount":3090}], + "final_stacks":{"2":20_060,"4":19_940,"0":20000,"1":19990,"3":20000,"5":20000}})); + assert!(h.bad_anomalies().is_empty(), "{:#?}", h.bad_anomalies()); + let r = &h.hands()[0]; + assert!(!r.desync && r.issues == 0); +} + +#[test] +fn guard_converts_to_call_when_cap_is_below_min_raise_and_keeps_calls_and_folds() { + use openpoker::mapping::{cap_action, OpAction}; + use openpoker::proto::ValidSet; + let v = ValidSet { fold: true, check: false, call: Some(500), raise: Some((1000, 20_000)), all_in: None }; + let shove = OpAction { action: "raise".into(), amount: Some(20_000) }; + // cap leaves less than the min raise -> call + let (a, _) = cap_action(&shove, &v, 800, 0, 20_000).unwrap(); + assert_eq!(a.action, "call"); + // call / fold are never touched, even beyond the cap + assert!(cap_action(&OpAction { action: "call".into(), amount: None }, &v, 100, 0, 20_000).is_none()); + assert!(cap_action(&OpAction { action: "fold".into(), amount: None }, &v, 100, 0, 20_000).is_none()); + // all-in that fits under the cap is allowed; one that does not becomes a raise to the cap + let ai = OpAction { action: "all_in".into(), amount: None }; + assert!(cap_action(&ai, &v, 3000, 200, 2500).is_none()); + let (a, _) = cap_action(&ai, &v, 3000, 200, 20_000).unwrap(); + assert_eq!((a.action.as_str(), a.amount), ("raise", Some(2800))); +} + +#[test] +fn max_stack_bb_zero_changes_nothing() { + let (sp, _) = spec(false, true); + let mut h = H::with_cap(sp, 100, 0.0); + h.send(table_joined()); + let out = deep_hand(&mut h, "deep"); + assert_eq!(out[0]["amount"], 20_000, "full jam when disabled"); + assert!(h.sink.of_kind("decision")[0]["stack_guard"].is_null()); + h.send(pa(2, "raise", Some(20_000), "preflop", 0, 20_090)); + h.send(pa(4, "fold", None, "preflop", 19_940, 20_090)); + let out = h.send(json!({"type":"hand_result","hand_id":"deep","winners":[],"final_stacks":{"2":40_000}})); + assert_eq!(count(&out, "leave_table"), 0, "no reset when disabled"); + assert_eq!((h.s.counters.stack_guards, h.s.counters.stack_resets), (0, 0)); +} diff --git a/arena/referee/Cargo.toml b/arena/referee/Cargo.toml new file mode 100644 index 00000000..1c2ee161 --- /dev/null +++ b/arena/referee/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "referee" +edition.workspace = true +version.workspace = true +description = "Spot-by-spot referee: PokerBench accuracy and exact heads-up river EV loss for bench policies." + +[dependencies] +cards.workspace = true +rayon.workspace = true +serde.workspace = true +serde_json.workspace = true +nlhe = { path = "../../engine/nlhe" } +abstraction = { path = "../../sharingan-1/abstraction" } +blueprint = { path = "../../sharingan-1/blueprint" } +bench = { path = "../../arena/bench" } + +[[bin]] +name = "referee" +path = "src/main.rs" diff --git a/arena/referee/RESULTS.md b/arena/referee/RESULTS.md new file mode 100644 index 00000000..a6c3f85e --- /dev/null +++ b/arena/referee/RESULTS.md @@ -0,0 +1,92 @@ +# referee results + +All numbers produced on the dev box (`scripts/dev.sh`), seed 1, `RAYON_NUM_THREADS=16`. +Logs: `~/pluribus/logs/ref/*.json` on the box. + +## Dataset + +PokerBench (HF `RZ412/PokerBench`, license **Apache-2.0** per the HF card; the GitHub repo states none). +Downloaded the four `*_game_scenario_information.csv` files (the `prompt_and_label.json` files are +redundant prompt text) to `data/pokerbench/`; parsed as data only. + +| file | rows | +|---|---| +| preflop test | 1,000 | +| preflop train | 60,000 | +| postflop test | 10,000 (635 flop / 4,097 turn / 5,268 river) | +| postflop train | 500,000 | + +Postflop spots are heads-up (IP/OOP) after a 6-max preflop line; sizes are integer bb raise-to totals; +labels are one action (>50% solver frequency); test labels balance fold/check/call/bet-raise at 25% each. +**Coverage: 100% of all 574,200 rows replay** on the nlhe engine (test and train; 0 parse failures). +Pot cross-check against the source `pot_size`: ~94% within 1bb+3%; the rest are river spots where +integer-rounded source sizes accumulate (up to ~5bb). + +Dataset quirks handled: `Fold` listed beside `Check`; `Call` omitted at some pruned nodes; folds of +skipped seats are implicit; preflop lines for HU postflop spots end before the remaining seats fold. + +## PokerBench baselines (exact = argmax option equals label; mass = probability on label) + +Test split (11,000 spots, coverage 1.0): + +| policy | exact | class | mass_exact | mass_class | preflop | flop | turn | river | +|---|---|---|---|---|---|---|---|---| +| nit | 0.645 | 0.653 | 0.637 | 0.644 | 0.698 | 0.444 | 0.596 | 0.696 | +| tag | 0.512 | 0.522 | 0.510 | 0.520 | 0.608 | 0.362 | 0.471 | 0.543 | +| station | 0.500 | 0.500 | 0.500 | 0.500 | 0.500 | 0.624 | 0.493 | 0.491 | +| random | 0.500 | 0.500 | 0.446 | 0.452 | 0.500 | 0.624 | 0.493 | 0.491 | +| toy blueprint (60k it, coarse buckets, tiny sizing) | 0.450 | 0.449 | 0.453 | 0.458 | 0.488 | 0.487 | 0.438 | 0.447 | + +Train sample (50k strided rows) agrees within ~0.01 for every bot (e.g. tag 0.514, nit 0.647). +Chance level is not 25%: check/call labels are 50% of the test set, so a station scores 0.50 exact. +Treat accuracy as regression only: a deterministic modal-action lookup scores high (nit wins here). +Tag breakdown highlights: label class bet_raise 0.63, fold 0.56, check_call 0.43; preflop vs_4bet shove nodes 0.31; +heads-up-postflop facing-bet-no-raise spots are easiest (0.69-0.75). + +## Exact heads-up river referee (100 deduplicated river nodes from the test split, 1000 CFR+ iterations) + +Ranges: Bayes from the policy's own action probabilities along the history (floor 1e-4). Menu: first bet +{0.5, 1.0 pot, all-in}, raises {1.0, all-in}, 3 raises. Mean pot 27.8bb. EV loss = `value_p(eq) + BR_opponent(policy_p)`, +mbb of the big blind, per spot, mean over both seats. + +| policy | EV loss mbb (mean) | median | % of pot | calling-station control | +|---|---|---|---|---| +| tag | 11,095 | 9,239 | 56 | 27,959 | +| nit | 12,499 | 11,681 | 55 | 28,848 | +| random | 19,251 | 19,719 | 125 | 22,145 | +| station | 22,145 | 22,725 | 145 | 22,145 | +| toy blueprint | 29,538 | 28,351 | 185 | 31,229 | + +Reference solver exploitability (mean) 35-58 mbb, i.e. under 0.5% of the loss, so the numbers are not solver noise. +(The control differs by policy only because ranges differ.) A strong blueprint should land far below tag; those numbers +are large because heuristics play river spots far from equilibrium in ranges they shape themselves. + +## Solver validation (tests, `cargo test --release -p referee`, 7 pass in ~2s on the box) + +* Showdown/fold evaluation matches an O(n^2) brute force to 1e-9 with card removal. +* Toy river (board TsTcThTd2c, OOP = AA + 33 half/half, IP = KK, pot-size bet, no raises): CFR+ 10k iterations + gives values OOP +50 / IP -50 chips (analytic 0.25 pot), value hands bet 100%, air bluffs 50% (+-3%), IP calls 50% (+-3%), + exploitability < 5 mbb. +* Equilibrium vs itself: loss < 10 mbb; a 300-iteration strategy loses < 100 mbb; a calling station loses > 100 mbb in both seats. +* Real spots: zero-sum check, solver exploitability < 5% pot at 400 iterations. +* Parser roundtrips every test-set preflop/postflop line; all 11,000 test spots replay with hero to act and legal options. + +## Running against the real blueprint + +``` +DEV_TARGET=referee scripts/dev.sh run 'cargo build --release -p referee' +B=target/referee/release/referee +$B pokerbench --policy blueprint:data/run-paper/export.bp --sizing paper --buckets data/buckets-200 --split test +$B pokerbench --policy blueprint:... --sizing paper --buckets data/buckets-200 --split train --limit 50000 +$B river-spots --policy blueprint:... --sizing paper --buckets data/buckets-200 --n 200 --iters 1500 +``` +Set `--capacity` (default 2^26 slots) to the checkpoint's size. `--ranges uniform` isolates strategy quality from range quality. + +## Deviations / caveats + +* `pluribus` crate not used as a dependency (bench provides `sizing_by_name`/bucketers); spec `blueprint:` uses bench's loader; added `toy:`. +* Size mapping: raises map to the solver option with nearest raise-increment (log ratio); a raise when no solver raise exists is "unmapped" (never exact). +* Postflop spot sizes are integer-rounded; replay snaps sizes within 1bb of min-raise/all-in. +* River EV loss is range-conditional on the policy's own Bayes ranges, assumes the policy plays both seats, uses a fixed menu; turn spots not implemented. +* CFR+ here converges ~O(1/T) (70 mbb at 1000 its, 30 at 2000 on typical spots); use `ref_expl` in the JSON as the error bar. +* `river-spots --split train` loads the full train file; use the test split. diff --git a/arena/referee/src/lib.rs b/arena/referee/src/lib.rs new file mode 100644 index 00000000..c099db4b --- /dev/null +++ b/arena/referee/src/lib.rs @@ -0,0 +1,19 @@ +//! Referee: measures how close a bench policy plays to GTO-solver references, spot by spot. +//! +//! * [`pokerbench`]: PokerBench (GTO Wizard-labelled 6-max 100bb spots): parser, engine +//! replay, action-accuracy and probability-mass scoring with breakdowns. +//! * [`solver`]: exact heads-up river solver (vector CFR+, 1326 hands, card removal) with +//! best-response EV-loss computation. +//! * [`river`]: river referee: Bayes ranges from the policy, equilibrium of the spot, EV loss +//! in mbb of the policy's river strategy. +//! * [`replay`]: checked replay of external histories on the `nlhe` engine. +//! * [`policies`]: policy specs for the CLI (`builtin:tag`, `blueprint:`). +//! +//! Seeding: every random stream is derived per item with [`bench::mix`], never per thread. + +pub mod pokerbench; +pub mod policies; +pub mod replay; +pub mod river; +pub mod solver; +pub mod toy; diff --git a/arena/referee/src/main.rs b/arena/referee/src/main.rs new file mode 100644 index 00000000..10f8dd4e --- /dev/null +++ b/arena/referee/src/main.rs @@ -0,0 +1,170 @@ +//! `referee` CLI. +//! +//! ```text +//! referee pokerbench --policy builtin:tag|blueprint: [--sizing local] [--buckets DIR] +//! [--split test|train] [--which all|preflop|postflop] [--limit N] [--seed S] +//! referee river-spots --policy ... [--n 50] [--iters 400] [--ranges policy|uniform] +//! [--split test|train] [--seed S] +//! ``` +//! Both print a JSON summary on stdout. + +use rayon::prelude::*; +use referee::pokerbench::{self, Which}; +use referee::policies; +use referee::river::{self, RangeMode, RiverSpot}; +use serde_json::json; +use std::collections::{BTreeMap, HashSet}; +use std::path::PathBuf; + +struct Args(BTreeMap); +impl Args { + fn get(&self, k: &str, d: &str) -> String { + self.0.get(k).cloned().unwrap_or(d.to_string()) + } + fn num(&self, k: &str, d: T) -> T { + self.0.get(k).and_then(|v| v.parse().ok()).unwrap_or(d) + } +} + +fn main() { + let argv: Vec = std::env::args().collect(); + let cmd = argv.get(1).cloned().unwrap_or_default(); + let mut m = BTreeMap::new(); + let mut i = 2; + while i < argv.len() { + let k = argv[i].trim_start_matches("--").to_string(); + if i + 1 < argv.len() && !argv[i + 1].starts_with("--") { + m.insert(k, argv[i + 1].clone()); + i += 2; + } else { + m.insert(k, String::new()); + i += 1; + } + } + if let Err(e) = run(&cmd, &Args(m)) { + eprintln!("error: {e}"); + std::process::exit(1); + } +} + +fn mean(v: &[f64]) -> f64 { + v.iter().sum::() / v.len().max(1) as f64 +} + +fn median(v: &[f64]) -> f64 { + let mut s = v.to_vec(); + s.sort_by(|a, b| a.partial_cmp(b).unwrap()); + s.get(s.len() / 2).copied().unwrap_or(0.0) +} + +fn run(cmd: &str, a: &Args) -> Result<(), String> { + let data = + a.0.get("data") + .map(PathBuf::from) + .unwrap_or_else(pokerbench::default_dir); + let test = match a.get("split", "test").as_str() { + "test" => true, + "train" => false, + s => return Err(format!("bad --split {s}")), + }; + let buckets = a.0.get("buckets").cloned(); + let policy = || { + policies::parse( + &a.get("policy", "builtin:tag"), + &a.get("sizing", "tiny"), + buckets.as_deref(), + a.num("capacity", 1usize << 26), + ) + }; + let seed: u64 = a.num("seed", 1); + match cmd { + "pokerbench" => { + let which = match a.get("which", "all").as_str() { + "preflop" => Which::Preflop, + "postflop" => Which::Postflop, + _ => Which::All, + }; + let f = policy()?; + let limit: usize = a.num("limit", 0); + let (mut res, mut bad_total) = (Vec::new(), 0); + pokerbench::for_each_chunk(&data, which, test, limit, 20_000, |spots, bad| { + bad_total += bad; + res.extend(pokerbench::score_chunk(&spots, &*f, seed)); + })?; + let rep = pokerbench::report(&f.name(), bad_total, res); + println!("{}", serde_json::to_string_pretty(&rep).unwrap()); + } + "river-spots" => { + let f = policy()?; + let n: usize = a.num("n", 50); + let iters: usize = a.num("iters", 400); + let mode = match a.get("ranges", "policy").as_str() { + "uniform" => RangeMode::Uniform, + _ => RangeMode::Policy, + }; + let (spots, _) = pokerbench::load(&data, Which::Postflop, test)?; + let mut seen = HashSet::new(); + let mut valid: Vec = Vec::new(); + let (mut candidates, mut unusable) = (0, 0); + for s in spots.iter().filter(|s| s.street == nlhe::Street::River) { + if !seen.insert(RiverSpot::key(s)) { + continue; + } + candidates += 1; + match RiverSpot::from_spot(s) { + Ok(r) => valid.push(r), + Err(_) => unusable += 1, + } + } + let total = valid.len(); + let pick: Vec = if n == 0 || n >= total { + (0..total).collect() + } else { + (0..n).map(|i| i * total / n).collect() + }; + let results: Vec<_> = pick + .par_iter() + .map(|&i| river::evaluate(&valid[i], &*f, mode, iters, bench::mix(seed, i as u64))) + .collect(); + let ok: Vec<_> = results.iter().filter_map(|r| r.as_ref().ok()).collect(); + let col = |g: &dyn Fn(&river::RiverResult) -> f64| -> Vec { + ok.iter().map(|r| g(r)).collect() + }; + let oop = col(&|r| r.ev_loss_mbb[0]); + let ip = col(&|r| r.ev_loss_mbb[1]); + let st_oop = col(&|r| r.station_loss_mbb[0]); + let st_ip = col(&|r| r.station_loss_mbb[1]); + let both = col(&|r| (r.ev_loss_mbb[0] + r.ev_loss_mbb[1]) / 2.0); + let st_both = col(&|r| (r.station_loss_mbb[0] + r.station_loss_mbb[1]) / 2.0); + let pot = col(&|r| r.pot_bb); + let out = json!({ + "policy": f.name(), + "ranges": format!("{mode:?}"), + "iters": iters, + "river_nodes_in_split": candidates, + "unusable_nodes": unusable, + "evaluated": ok.len(), + "failed": results.len() - ok.len(), + "ev_loss_mbb": { + "mean_both_seats": mean(&both), + "median_both_seats": median(&both), + "mean_oop": mean(&oop), + "mean_ip": mean(&ip), + "mean_pct_of_pot": mean(&ok.iter().map(|r| (r.ev_loss_mbb[0] + r.ev_loss_mbb[1]) / 2.0 / 1000.0 / r.pot_bb * 100.0).collect::>()), + }, + "control_calling_station_loss_mbb": { + "mean_both_seats": mean(&st_both), "mean_oop": mean(&st_oop), "mean_ip": mean(&st_ip), + }, + "solver_ref_exploitability_mbb_mean": mean(&col(&|r| r.ref_expl_mbb)), + "mean_pot_bb": mean(&pot), + "mean_tree_nodes": mean(&col(&|r| r.nodes as f64)), + "first_spots": ok.iter().take(10).collect::>(), + }); + println!("{}", serde_json::to_string_pretty(&out).unwrap()); + } + _ => { + println!("usage: referee --policy builtin:tag|blueprint: [--sizing S] [--buckets DIR] [--split test|train] [--limit N | --n N]"); + } + } + Ok(()) +} diff --git a/arena/referee/src/pokerbench.rs b/arena/referee/src/pokerbench.rs new file mode 100644 index 00000000..40c787e0 --- /dev/null +++ b/arena/referee/src/pokerbench.rs @@ -0,0 +1,966 @@ +//! PokerBench (RZ412/PokerBench, Apache-2.0): parser, engine replay and policy scoring. +//! +//! Data is treated as untrusted text: it is only split and parsed, never evaluated. +//! +//! # Format (verified on the shipped CSVs) +//! * Preflop `*_game_scenario_information.csv`: `prev_line` is `POS/ACTION/POS/ACTION/...` +//! with sizes as raise-to totals in bb (`2.0bb`), `allin`, `call`, `fold`, `check`. Players +//! who never act before the hero are silently folded. +//! * Postflop CSVs are heads-up (`IP`/`OOP`) after a preflop line (`preflop_action`, same +//! grammar). `postflop_action` is `OOP_CHECK/IP_BET_5/OOP_RAISE_14/.../dealcards/Jc/...` +//! with integer-rounded raise-to sizes in bb. Options are `['Fold', 'Call', 'Raise 29']`. +//! Labels are a single action (selected because it has >50% solver frequency). +//! * Stacks are 100bb, pot sizes include all bets (`pot_size`), 6-max positions +//! UTG,HJ,CO,BTN,SB,BB. We map to our seats (SB=0, BB=1, UTG=2, HJ=3, CO=4, BTN=5). +//! +//! # Scoring +//! The policy's distribution over its own concrete legal actions is mapped onto the spot's +//! solver options: fold/check/call exactly; each raise goes to the solver raise (or all-in) +//! option whose raise increment is nearest in log-ratio (see [`crate::replay::nearest_action`]). +//! A policy raise when the solver offers no raise is "unmapped" (counts as aggressive class, +//! never as exact). Reported per spot: +//! * `exact` - argmax mapped option equals the label (greedy policy accuracy); +//! * `class` - argmax of class mass (fold / check-call / bet-raise) equals the label's class; +//! * `mass_exact` / `mass_class` - probability mass on the label / its class (the expected +//! accuracy of a policy that samples its distribution). + +use crate::replay::{Replay, BB}; +use bench::mix; +use bench::policy::PolicyFactory; +use cards::{parse_card, parse_cards, Card}; +use nlhe::{Action, Street}; +use rayon::prelude::*; +use serde::Serialize; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +pub const POS_NAMES: [&str; 6] = ["SB", "BB", "UTG", "HJ", "CO", "BTN"]; + +/// Seat for a PokerBench position name. +pub fn pos_seat(p: &str) -> Option { + POS_NAMES.iter().position(|&n| n == p) +} + +/// One action token. Sizes are raise-to totals in bb. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Tok { + Fold, + Check, + Call, + Bet(f64), + Raise(f64), + AllIn, +} + +impl Tok { + /// 0 = fold, 1 = check/call, 2 = bet/raise/all-in. + pub fn class(self) -> usize { + match self { + Tok::Fold => 0, + Tok::Check | Tok::Call => 1, + _ => 2, + } + } + pub fn size(self) -> Option { + match self { + Tok::Bet(x) | Tok::Raise(x) => Some(x), + _ => None, + } + } +} + +pub const CLASS_NAMES: [&str; 3] = ["fold", "check_call", "bet_raise"]; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Role { + Oop, + Ip, +} + +/// One token of the postflop line. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum PostTok { + Act(Role, Tok), + /// `dealcards` marker (followed by the card in the source). + Deal, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Hero { + Seat(usize), + Role(Role), +} + +#[derive(Clone, Debug)] +pub struct Spot { + pub test: bool, + pub row: usize, + pub street: Street, + /// Preflop line as (seat, token). + pub pre_line: Vec<(usize, Tok)>, + pub post_line: Vec, + /// Full board listed in the row (0 or 3..5 cards; postflop rows list all 5). + pub board_all: Vec, + pub hole: [Card; 2], + pub hero: Hero, + pub options: Vec, + pub label: Tok, + pub pot_bb: f64, +} + +// ---------------------------------------------------------------- csv + tokens + +/// Minimal RFC-4180 CSV: quotes, doubled quotes, newlines in quotes. Returns rows of fields. +pub fn parse_csv(text: &str) -> Vec> { + let mut rows = Vec::new(); + let mut row: Vec = Vec::new(); + let mut f = String::new(); + let mut q = false; + let mut it = text.chars().peekable(); + let mut dirty = false; + while let Some(c) = it.next() { + dirty = true; + if q { + if c == '"' { + if it.peek() == Some(&'"') { + f.push('"'); + it.next(); + } else { + q = false; + } + } else { + f.push(c); + } + } else { + match c { + '"' => q = true, + ',' => row.push(std::mem::take(&mut f)), + '\r' => {} + '\n' => { + row.push(std::mem::take(&mut f)); + rows.push(std::mem::take(&mut row)); + dirty = false; + } + _ => f.push(c), + } + } + } + if dirty { + row.push(f); + rows.push(row); + } + rows +} + +fn parse_bb(s: &str) -> Option { + s.strip_suffix("bb")?.parse().ok() +} + +/// Preflop token: `fold|call|check|allin|bb`. +pub fn parse_pre_tok(s: &str) -> Option { + match s.to_ascii_lowercase().as_str() { + "fold" => Some(Tok::Fold), + "call" => Some(Tok::Call), + "check" => Some(Tok::Check), + "allin" => Some(Tok::AllIn), + x => parse_bb(x).map(Tok::Raise), + } +} + +pub fn fmt_pre_tok(t: Tok) -> String { + match t { + Tok::Fold => "fold".into(), + Tok::Call => "call".into(), + Tok::Check => "check".into(), + Tok::AllIn => "allin".into(), + Tok::Bet(x) | Tok::Raise(x) => format!("{x:.1}bb"), + } +} + +pub fn parse_pre_line(s: &str) -> Result, String> { + if s.is_empty() { + return Ok(vec![]); + } + let parts: Vec<&str> = s.split('/').collect(); + if parts.len() % 2 != 0 { + return Err(format!("odd preflop line {s}")); + } + parts + .chunks(2) + .map(|c| { + let seat = pos_seat(c[0]).ok_or(format!("bad position {}", c[0]))?; + let t = parse_pre_tok(c[1]).ok_or(format!("bad token {}", c[1]))?; + Ok((seat, t)) + }) + .collect() +} + +pub fn fmt_pre_line(l: &[(usize, Tok)]) -> String { + l.iter() + .map(|&(s, t)| format!("{}/{}", POS_NAMES[s], fmt_pre_tok(t))) + .collect::>() + .join("/") +} + +pub fn parse_post_line(s: &str) -> Result, String> { + let mut out = Vec::new(); + let mut skip_card = false; + for t in s.split('/').filter(|t| !t.is_empty()) { + if skip_card { + skip_card = false; + parse_card(t).ok_or(format!("bad dealt card {t}"))?; + continue; + } + if t == "dealcards" { + out.push(PostTok::Deal); + skip_card = true; + continue; + } + let (role, rest) = if let Some(r) = t.strip_prefix("OOP_") { + (Role::Oop, r) + } else if let Some(r) = t.strip_prefix("IP_") { + (Role::Ip, r) + } else { + return Err(format!("bad postflop token {t}")); + }; + let mut it = rest.split('_'); + let verb = it.next().unwrap_or(""); + let num = it.next().and_then(|x| x.parse::().ok()); + let tok = match (verb, num) { + ("CHECK", None) => Tok::Check, + ("CALL", None) => Tok::Call, + ("FOLD", None) => Tok::Fold, + ("ALLIN", _) => Tok::AllIn, + ("BET", Some(x)) => Tok::Bet(x), + ("RAISE", Some(x)) => Tok::Raise(x), + _ => return Err(format!("bad postflop token {t}")), + }; + out.push(PostTok::Act(role, tok)); + } + Ok(out) +} + +/// Inverse of [`parse_post_line`] given the dealt cards (turn, river). +pub fn fmt_post_line(l: &[PostTok], dealt: &[Card]) -> String { + let mut d = 0; + l.iter() + .map(|t| match *t { + PostTok::Deal => { + let c = dealt + .get(d) + .map_or("??".to_string(), |&c| cards::card_str(c)); + d += 1; + format!("dealcards/{c}") + } + PostTok::Act(r, tok) => { + let r = if r == Role::Oop { "OOP" } else { "IP" }; + match tok { + Tok::Check => format!("{r}_CHECK"), + Tok::Call => format!("{r}_CALL"), + Tok::Fold => format!("{r}_FOLD"), + Tok::AllIn => format!("{r}_ALLIN"), + Tok::Bet(x) => format!("{r}_BET_{x}"), + Tok::Raise(x) => format!("{r}_RAISE_{x}"), + } + } + }) + .collect::>() + .join("/") +} + +/// Postflop option / label: `Check|Call|Fold|Bet 24|Raise 29|Allin`. +pub fn parse_post_option(s: &str) -> Option { + let s = s.trim(); + let mut it = s.split_whitespace(); + let verb = it.next()?.to_ascii_lowercase(); + let num = it.next().and_then(|x| x.parse::().ok()); + match (verb.as_str(), num) { + ("check", None) => Some(Tok::Check), + ("call", None) => Some(Tok::Call), + ("fold", None) => Some(Tok::Fold), + ("allin", _) => Some(Tok::AllIn), + ("bet", Some(x)) => Some(Tok::Bet(x)), + ("raise", Some(x)) => Some(Tok::Raise(x)), + _ => None, + } +} + +/// `['a', 'b c']` -> items. +pub fn parse_list(s: &str) -> Vec { + s.trim() + .trim_start_matches('[') + .trim_end_matches(']') + .split(',') + .map(|x| x.trim().trim_matches('\'').trim_matches('"').to_string()) + .filter(|x| !x.is_empty()) + .collect() +} + +fn col(h: &[String], name: &str) -> Result { + h.iter() + .position(|x| x == name) + .ok_or(format!("missing column {name}")) +} + +fn hole_of(s: &str) -> Result<[Card; 2], String> { + let c = parse_cards(s).ok_or(format!("bad holding {s}"))?; + if c.len() != 2 || c[0] == c[1] { + return Err(format!("bad holding {s}")); + } + Ok([c[0], c[1]]) +} + +/// Parse a preflop CSV (header row first). +pub fn parse_preflop_csv(text: &str, test: bool) -> Vec> { + let rows = parse_csv(text); + let Some((h, body)) = rows.split_first() else { + return vec![]; + }; + let (cl, cp, ch, cd, co, cs) = match (|| { + Ok::<_, String>(( + col(h, "prev_line")?, + col(h, "hero_pos")?, + col(h, "hero_holding")?, + col(h, "correct_decision")?, + col(h, "available_moves")?, + col(h, "pot_size")?, + )) + })() { + Ok(x) => x, + Err(e) => return vec![Err(e)], + }; + body.iter() + .enumerate() + .map(|(row, r)| { + let g = |i: usize| r.get(i).map(|s| s.as_str()).ok_or("short row".to_string()); + let hero = pos_seat(g(cp)?).ok_or("bad hero_pos")?; + let options = parse_list(g(co)?) + .iter() + .map(|x| parse_pre_tok(x).ok_or(format!("bad option {x}"))) + .collect::, _>>()?; + Ok(Spot { + test, + row, + street: Street::Preflop, + pre_line: parse_pre_line(g(cl)?)?, + post_line: vec![], + board_all: vec![], + hole: hole_of(g(ch)?)?, + hero: Hero::Seat(hero), + options, + label: parse_pre_tok(g(cd)?).ok_or("bad label")?, + pot_bb: g(cs)?.parse().map_err(|_| "bad pot")?, + }) + }) + .collect() +} + +/// Parse a postflop CSV (header row first). +pub fn parse_postflop_csv(text: &str, test: bool) -> Vec> { + let rows = parse_csv(text); + let Some((h, body)) = rows.split_first() else { + return vec![]; + }; + let cols = (|| { + Ok::<_, String>([ + col(h, "preflop_action")?, + col(h, "board_flop")?, + col(h, "board_turn")?, + col(h, "board_river")?, + col(h, "postflop_action")?, + col(h, "evaluation_at")?, + col(h, "available_moves")?, + col(h, "pot_size")?, + col(h, "hero_position")?, + col(h, "holding")?, + col(h, "correct_decision")?, + ]) + })(); + let c = match cols { + Ok(c) => c, + Err(e) => return vec![Err(e)], + }; + body.iter() + .enumerate() + .map(|(row, r)| { + let g = |i: usize| { + r.get(c[i]) + .map(|s| s.as_str()) + .ok_or("short row".to_string()) + }; + let mut board = parse_cards(g(1)?).ok_or("bad flop")?; + board.extend(parse_cards(g(2)?).ok_or("bad turn")?); + board.extend(parse_cards(g(3)?).ok_or("bad river")?); + let street = match g(5)? { + "Flop" => Street::Flop, + "Turn" => Street::Turn, + "River" => Street::River, + x => return Err(format!("bad street {x}")), + }; + if board.len() != 5 { + return Err("board is not 5 cards".into()); + } + let hero = match g(8)? { + "IP" => Role::Ip, + "OOP" => Role::Oop, + x => return Err(format!("bad hero_position {x}")), + }; + let options = parse_list(g(6)?) + .iter() + .map(|x| parse_post_option(x).ok_or(format!("bad option {x}"))) + .collect::, _>>()?; + Ok(Spot { + test, + row, + street, + pre_line: parse_pre_line(g(0)?)?, + post_line: parse_post_line(g(4)?)?, + board_all: board, + hole: hole_of(g(9)?)?, + hero: Hero::Role(hero), + options, + label: parse_post_option(g(10)?).ok_or("bad label")?, + pot_bb: g(7)?.parse().map_err(|_| "bad pot")?, + }) + }) + .collect() +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Which { + Preflop, + Postflop, + All, +} + +/// Dataset file name for (kind, split). +pub fn file_name(pre: bool, test: bool) -> &'static str { + match (pre, test) { + (true, true) => "preflop_1k_test_set_game_scenario_information.csv", + (true, false) => "preflop_60k_train_set_game_scenario_information.csv", + (false, true) => "postflop_10k_test_set_game_scenario_information.csv", + (false, false) => "postflop_500k_train_set_game_scenario_information.csv", + } +} + +/// Default data directory (`/data/pokerbench`). +pub fn default_dir() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../data/pokerbench") +} + +/// Stream a split in chunks of at most `chunk` rows (memory stays bounded: the file text is +/// read once, rows are parsed chunk by chunk). `limit > 0` first picks an evenly strided +/// subset of rows. `f` receives each chunk of parsed spots (with global row numbers) and the +/// number of rows in the chunk that failed to parse. Assumes no newlines inside fields +/// (true for the shipped files). +pub fn for_each_chunk( + dir: &Path, + which: Which, + test: bool, + limit: usize, + chunk: usize, + mut f: impl FnMut(Vec, usize), +) -> Result<(), String> { + // With `Which::All` and a limit the budget is split proportionally to file sizes. + let files: Vec = [true, false] + .into_iter() + .filter(|&pre| !((pre && which == Which::Postflop) || (!pre && which == Which::Preflop))) + .collect(); + let mut texts = Vec::new(); + for &pre in &files { + let p = dir.join(file_name(pre, test)); + texts.push(( + pre, + std::fs::read_to_string(&p).map_err(|e| format!("{}: {e}", p.display()))?, + )); + } + let total_rows: usize = texts + .iter() + .map(|t| t.1.lines().count().saturating_sub(1)) + .sum(); + for (pre, text) in &texts { + let mut lines = text.lines(); + let header = lines.next().ok_or("empty file")?; + let body: Vec<&str> = lines.collect(); + let k = if limit == 0 || limit >= total_rows { + body.len() + } else { + (limit * body.len() / total_rows.max(1)).max(1) + }; + let idx: Vec = if k >= body.len() { + (0..body.len()).collect() + } else { + (0..k).map(|i| i * body.len() / k).collect() + }; + for part in idx.chunks(chunk.max(1)) { + let mut t = String::from(header); + for &i in part { + t.push('\n'); + t.push_str(body[i]); + } + let parsed = if *pre { + parse_preflop_csv(&t, test) + } else { + parse_postflop_csv(&t, test) + }; + let (mut ok, mut bad) = (Vec::new(), 0); + for (r, &i) in parsed.into_iter().zip(part) { + match r { + Ok(mut s) => { + s.row = i; + ok.push(s) + } + Err(_) => bad += 1, + } + } + f(ok, bad); + } + } + Ok(()) +} + +/// Load a split fully (use [`for_each_chunk`] for the large train files). +pub fn load(dir: &Path, which: Which, test: bool) -> Result<(Vec, usize), String> { + let (mut spots, mut bad) = (Vec::new(), 0); + for_each_chunk(dir, which, test, 0, 20_000, |s, b| { + spots.extend(s); + bad += b; + })?; + Ok((spots, bad)) +} + +/// Deterministic evenly strided subsample of at most `n` items. +pub fn stride(v: &[T], n: usize) -> Vec { + if n == 0 || n >= v.len() { + return v.to_vec(); + } + (0..n).map(|i| v[i * v.len() / n].clone()).collect() +} + +// ---------------------------------------------------------------- replay + +pub struct Replayed { + pub replay: Replay, + pub hero_seat: usize, + pub pot_diff_bb: f64, +} + +fn to_action(r: &Replay, t: Tok) -> Result { + let l = r.state.legal(); + match t { + Tok::Fold => Ok(Action::Fold), + Tok::Check => Ok(Action::Check), + Tok::Call => Ok(if l.can_check { + Action::Check + } else { + Action::Call + }), + Tok::Bet(x) | Tok::Raise(x) => r.snap_raise((x * BB as f64).round() as i32), + Tok::AllIn => Ok(if l.can_raise { + Action::RaiseTo(l.max_raise_to) + } else { + Action::Call + }), + } +} + +/// Replay the preflop line (folding skipped seats), up to the point where `until_hero` (a +/// seat) is to act, or until the street changes when `until_hero` is `None`. +fn replay_preflop( + r: &mut Replay, + line: &[(usize, Tok)], + hero: Option, +) -> Result<(), String> { + for &(seat, t) in line { + if r.state.street() != Street::Preflop { + return Err("street advanced mid-line".into()); + } + r.skip_to(seat)?; + let a = to_action(r, t)?; + r.apply(a)?; + } + if let Some(h) = hero { + r.skip_to(h)?; + if r.state.street() != Street::Preflop { + return Err("street advanced".into()); + } + } else { + // Heads-up postflop spots: everyone still pending when the line ends folded. + while r.state.street() == Street::Preflop && r.to_act().is_some() { + r.apply(Action::Fold)?; + } + } + Ok(()) +} + +/// Check option consistency with the engine's legal actions at the hero decision. The source +/// lists `Fold` next to `Check` and omits `Call` for some prunable nodes, so only options that +/// are listed but impossible are errors. +fn check_options(r: &Replay, opts: &[Tok]) -> Result<(), String> { + let l = r.state.legal(); + let has = |f: fn(&Tok) -> bool| opts.iter().any(f); + if has(|t| *t == Tok::Fold) && !(l.can_fold || l.can_check) { + return Err("fold option mismatch".into()); + } + if has(|t| *t == Tok::Check) && !l.can_check { + return Err("check option mismatch".into()); + } + if has(|t| *t == Tok::Call) && l.can_check { + return Err("call option mismatch".into()); + } + if !l.can_raise && has(|t| t.class() == 2) { + return Err("raise option but cannot raise".into()); + } + Ok(()) +} + +/// Replay `spot` to the hero's decision. `full_board`: expose all five board cards to the +/// replay (used by river referee); otherwise only cards up to the hero's street are known. +pub fn replay_spot(spot: &Spot) -> Result { + let known = spot.street.board_len(); + let board: Vec = spot.board_all.iter().take(known).copied().collect(); + if spot.hole.iter().any(|h| board.contains(h)) { + return Err("hole collides with board".into()); + } + let mut r = Replay::new(6, &board); + let hero_seat; + match spot.hero { + Hero::Seat(h) => { + hero_seat = h; + replay_preflop(&mut r, &spot.pre_line, Some(h))?; + } + Hero::Role(role) => { + replay_preflop(&mut r, &spot.pre_line, None)?; + if r.state.street() != Street::Flop || r.state.live_count() != 2 { + return Err("preflop line does not end heads-up on the flop".into()); + } + let (oop, ip) = live_pair(&r); + let seat_of = |ro: Role| if ro == Role::Oop { oop } else { ip }; + hero_seat = seat_of(role); + let mut deals = 0; + for t in &spot.post_line { + match *t { + PostTok::Deal => { + deals += 1; + if r.state.street().idx() != 1 + deals { + return Err("dealcards marker without street change".into()); + } + } + PostTok::Act(ro, tok) => { + if r.to_act() != Some(seat_of(ro)) { + return Err("turn order mismatch".into()); + } + let a = to_action(&r, tok)?; + r.apply(a)?; + } + } + } + if r.state.street() != spot.street { + return Err("wrong street at hero".into()); + } + if r.to_act() != Some(hero_seat) { + return Err("hero not to act".into()); + } + } + } + if r.state.is_terminal() || r.to_act() != Some(hero_seat) { + return Err("hero not to act".into()); + } + check_options(&r, &spot.options)?; + let pot_diff_bb = r.state.pot() as f64 / BB as f64 - spot.pot_bb; + Ok(Replayed { + replay: r, + hero_seat, + pot_diff_bb, + }) +} + +/// Replay a postflop spot's history up to the start of the river decision (both players' +/// hole cards unknown). Returns the replay (full board known) and `[oop, ip]` seats. +pub fn replay_to_river(spot: &Spot) -> Result<(Replay, [usize; 2]), String> { + if !matches!(spot.hero, Hero::Role(_)) || spot.street != Street::River { + return Err("not a river spot".into()); + } + let mut r = Replay::new(6, &spot.board_all); + replay_preflop(&mut r, &spot.pre_line, None)?; + if r.state.street() != Street::Flop || r.state.live_count() != 2 { + return Err("preflop line does not end heads-up on the flop".into()); + } + let (oop, ip) = live_pair(&r); + let mut deals = 0; + for t in &spot.post_line { + match *t { + PostTok::Deal => { + deals += 1; + if r.state.street().idx() != 1 + deals { + return Err("dealcards marker without street change".into()); + } + if deals == 2 { + break; + } + } + PostTok::Act(ro, tok) => { + let seat = if ro == Role::Oop { oop } else { ip }; + if r.to_act() != Some(seat) { + return Err("turn order mismatch".into()); + } + let a = to_action(&r, tok)?; + r.apply(a)?; + } + } + } + if r.state.street() != Street::River || r.state.is_terminal() || r.to_act().is_none() { + return Err("no river decision".into()); + } + Ok((r, [oop, ip])) +} + +/// (OOP seat, IP seat) of the two live players after the preflop line. +pub fn live_pair(r: &Replay) -> (usize, usize) { + let live: Vec = (0..6).filter(|&s| !r.state.is_folded(s)).collect(); + (live[0], live[1]) +} + +// ---------------------------------------------------------------- scoring + +#[derive(Clone, Debug, Default, Serialize)] +pub struct Agg { + pub n: usize, + pub exact: f64, + pub class: f64, + pub mass_exact: f64, + pub mass_class: f64, +} + +impl Agg { + fn add(&mut self, r: &SpotScore) { + self.n += 1; + self.exact += r.exact as u8 as f64; + self.class += r.class as u8 as f64; + self.mass_exact += r.mass_exact; + self.mass_class += r.mass_class; + } + fn finish(mut self) -> Agg { + let n = self.n.max(1) as f64; + self.exact /= n; + self.class /= n; + self.mass_exact /= n; + self.mass_class /= n; + self + } +} + +#[derive(Clone, Debug)] +pub struct SpotScore { + pub exact: bool, + pub class: bool, + pub mass_exact: f64, + pub mass_class: f64, + pub street: Street, + pub position: String, + pub spot_type: String, + pub label_class: usize, + pub pot_ok: bool, +} + +/// Concrete engine action for a solver option at the replayed state. +fn option_action(r: &Replay, t: Tok) -> Action { + to_action(r, t).unwrap_or_else(|_| { + let l = r.state.legal(); + match t { + Tok::Bet(x) | Tok::Raise(x) => Action::RaiseTo( + ((x * BB as f64).round() as i32).clamp(l.min_raise_to, l.max_raise_to), + ), + _ => Action::Call, + } + }) +} + +fn spot_type(spot: &Spot) -> String { + match spot.street { + Street::Preflop => { + let raises = spot.pre_line.iter().filter(|x| x.1.class() == 2).count(); + let t = match raises { + 0 if spot.pre_line.iter().any(|x| x.1 == Tok::Call) => "limped", + 0 => "unopened", + 1 => "vs_open", + 2 => "vs_3bet", + 3 => "vs_4bet", + _ => "vs_5bet+", + }; + let allin = spot.options.contains(&Tok::AllIn) && spot.options.len() <= 3; + format!("{t}{}", if allin { "_shove_node" } else { "" }) + } + _ => { + let shape = if spot.options.contains(&Tok::Fold) { + if spot.options.iter().any(|t| t.class() == 2) { + "facing_bet_can_raise" + } else { + "facing_bet_no_raise" + } + } else if spot.options.iter().any(|t| matches!(t, Tok::Raise(_))) { + "check_or_raise" + } else { + "check_or_bet" + }; + let raises = spot.pre_line.iter().filter(|x| x.1.class() == 2).count(); + let pot = if raises <= 1 { "srp" } else { "3bp+" }; + format!("{shape}/{pot}") + } + } +} + +/// Score one spot. `seed` seeds the policy's hidden randomness. +pub fn score_spot(spot: &Spot, f: &dyn PolicyFactory, seed: u64) -> Result { + let rp = replay_spot(spot)?; + let r = &rp.replay; + let li = spot + .options + .iter() + .position(|&t| t == spot.label) + .ok_or("label not among options")?; + let targets: Vec = spot.options.iter().map(|&t| option_action(r, t)).collect(); + let mut p = r.player(f, rp.hero_seat, seed); + let d = r.dist(&mut *p, spot.hole); + let n = spot.options.len(); + // masses: options 0..n, then unmapped (index n). + let mut m = vec![0.0f64; n + 1]; + let mut cm = [0.0f64; 3]; + for i in 0..d.len() { + let (a, pr) = (d.action(i), d.prob(i)); + let cl = match a { + Action::Fold => 0, + Action::Check | Action::Call => 1, + Action::RaiseTo(_) => 2, + }; + cm[cl] += pr; + m[crate::replay::nearest_action(&r.state, &targets, a).unwrap_or(n)] += pr; + } + let argmax = |v: &[f64]| { + v.iter() + .enumerate() + .fold( + (0, f64::MIN), + |b, (i, &x)| if x > b.1 + 1e-12 { (i, x) } else { b }, + ) + .0 + }; + let lc = spot.label.class(); + Ok(SpotScore { + exact: argmax(&m) == li, + class: argmax(&cm) == lc, + mass_exact: m[li], + mass_class: cm[lc], + street: spot.street, + position: match spot.hero { + Hero::Seat(s) => POS_NAMES[s].to_string(), + Hero::Role(Role::Ip) => "IP".into(), + Hero::Role(Role::Oop) => "OOP".into(), + }, + spot_type: spot_type(spot), + label_class: lc, + pot_ok: rp.pot_diff_bb.abs() <= 1.0 + 0.03 * spot.pot_bb, + }) +} + +#[derive(Debug, Serialize)] +pub struct Report { + pub policy: String, + pub spots_total: usize, + pub parse_failures: usize, + pub replayable: usize, + pub coverage: f64, + pub pot_matches_source: f64, + pub failure_reasons: BTreeMap, + pub overall: Agg, + pub by_street: BTreeMap, + pub by_position: BTreeMap, + pub by_spot_type: BTreeMap, + pub by_label_class: BTreeMap, +} + +/// Score `spots` in parallel. Seeds are per spot: `mix(seed, row-id)`. +pub fn score_chunk( + spots: &[Spot], + f: &dyn PolicyFactory, + seed: u64, +) -> Vec> { + spots + .par_iter() + .map(|s| { + let id = + (s.row as u64) << 2 | (s.street != Street::Preflop) as u64 | (s.test as u64) << 1; + score_spot(s, f, mix(seed, id)) + }) + .collect() +} + +/// Convenience: score and report in one go. +pub fn run(spots: &[Spot], parse_failures: usize, f: &dyn PolicyFactory, seed: u64) -> Report { + report(&f.name(), parse_failures, score_chunk(spots, f, seed)) +} + +/// Aggregate per-spot scores into a [`Report`]. +pub fn report(name: &str, parse_failures: usize, res: Vec>) -> Report { + let mut rep = Report { + policy: name.to_string(), + spots_total: res.len() + parse_failures, + parse_failures, + replayable: 0, + coverage: 0.0, + pot_matches_source: 0.0, + failure_reasons: BTreeMap::new(), + overall: Agg::default(), + by_street: BTreeMap::new(), + by_position: BTreeMap::new(), + by_spot_type: BTreeMap::new(), + by_label_class: BTreeMap::new(), + }; + let mut pot_ok = 0; + for r in &res { + match r { + Err(e) => *rep.failure_reasons.entry(e.clone()).or_default() += 1, + Ok(s) => { + rep.replayable += 1; + pot_ok += s.pot_ok as usize; + rep.overall.add(s); + let st = format!("{:?}", s.street).to_lowercase(); + rep.by_street.entry(st).or_default().add(s); + rep.by_position + .entry(s.position.clone()) + .or_default() + .add(s); + rep.by_spot_type + .entry(format!( + "{}:{}", + if s.street == Street::Preflop { + "pre" + } else { + "post" + }, + s.spot_type + )) + .or_default() + .add(s); + rep.by_label_class + .entry(CLASS_NAMES[s.label_class].to_string()) + .or_default() + .add(s); + } + } + } + rep.coverage = rep.replayable as f64 / rep.spots_total.max(1) as f64; + rep.pot_matches_source = pot_ok as f64 / rep.replayable.max(1) as f64; + rep.overall = std::mem::take(&mut rep.overall).finish(); + for m in [ + &mut rep.by_street, + &mut rep.by_position, + &mut rep.by_spot_type, + &mut rep.by_label_class, + ] { + for v in m.values_mut() { + *v = std::mem::take(v).finish(); + } + } + rep +} diff --git a/arena/referee/src/policies.rs b/arena/referee/src/policies.rs new file mode 100644 index 00000000..f24e98e5 --- /dev/null +++ b/arena/referee/src/policies.rs @@ -0,0 +1,42 @@ +//! Policy specs for the CLI: `builtin:` (random|station|nit|tag|lag|maniac) or +//! `toy:` (in-process toy blueprint) or `blueprint:` (a `blueprint::io` checkpoint, with `--sizing` and `--buckets`). + +use bench::bp::{bucketer_by_name, sizing_by_name, BlueprintPolicy}; +use bench::builtin::builtin; +use bench::policy::PolicyFactory; +use std::path::Path; +use std::sync::Arc; + +pub fn parse( + spec: &str, + sizing: &str, + buckets: Option<&str>, + capacity: usize, +) -> Result, String> { + if let Some(name) = spec.strip_prefix("builtin:") { + return builtin(name).ok_or(format!("unknown builtin {name}")); + } + // `toy:`: tiny 6-max blueprint trained in-process (coarse buckets, tiny sizing). + if let Some(it) = spec.strip_prefix("toy:") { + let iters: u64 = it.parse().map_err(|_| "toy:")?; + return Ok(Arc::new(bench::bp::train_toy(6, iters, 1))); + } + if let Some(path) = spec.strip_prefix("blueprint:") { + let bucketer = match buckets { + Some(dir) => format!("tables:{dir}"), + None => "coarse".to_string(), + }; + let store = blueprint::io::load(Path::new(path), capacity, 0).map_err(|e| e.to_string())?; + let b = bucketer_by_name(&bucketer).ok_or(format!("cannot load buckets {bucketer}"))?; + let s = sizing_by_name(sizing).ok_or(format!("unknown sizing {sizing}"))?; + return Ok(Arc::new(BlueprintPolicy::new( + &format!("blueprint:{path}"), + Arc::new(store), + b, + s, + ))); + } + Err(format!( + "bad policy spec {spec} (builtin: | blueprint:)" + )) +} diff --git a/arena/referee/src/replay.rs b/arena/referee/src/replay.rs new file mode 100644 index 00000000..0ee7a6d0 --- /dev/null +++ b/arena/referee/src/replay.rs @@ -0,0 +1,214 @@ +//! Checked replay of an external action history on the `nlhe` engine, plus the glue that feeds +//! a bench [`Player`] and asks it for a distribution. +//! +//! External sources (PokerBench) give sizes in big blinds, rounded, and omit folds of players +//! who simply never acted. [`Replay`] therefore (a) never panics on illegal input (every +//! action is validated and returns `Err`), (b) can auto-fold skipped seats, and (c) snaps +//! rounded raise sizes to the legal range when they are within 1bb of a bound. + +use bench::policy::{Dist, Event, Player, PolicyFactory, View}; +use cards::Card; +use nlhe::abstraction::raise_fraction; +use nlhe::{Action, GameConfig, State, Step as NStep, Street}; + +/// Chips per big blind in the paper setup (50/100 blinds, 10,000 stacks = 100bb). +pub const BB: i32 = 100; + +/// One replayed engine step, enough to re-feed any [`Player`]. +#[derive(Clone, Copy, Debug)] +pub enum Step { + /// Action by `seat` taken at `pre` (state before the action); `blen` board cards visible. + Act { + pre: State, + seat: usize, + action: Action, + blen: usize, + }, + /// Board revealed up to this many cards. + Board(usize), +} + +pub struct Replay { + pub cfg: GameConfig, + pub state: State, + /// Full board known to the caller (the replay reveals a prefix as streets advance). + pub board: Vec, + pub blen: usize, + pub steps: Vec, + pub events: Vec, +} + +pub fn err(s: &str) -> Result { + Err(s.to_string()) +} + +impl Replay { + /// `players`-max, 100bb stacks, 0.5/1bb blinds. `board` is the (eventual) board. + pub fn new(players: usize, board: &[Card]) -> Replay { + let cfg = GameConfig::new(players); + Replay { + cfg, + state: State::new(&cfg), + board: board.to_vec(), + blen: 0, + steps: Vec::new(), + events: Vec::new(), + } + } + + pub fn visible_board(&self) -> &[Card] { + &self.board[..self.blen] + } + + pub fn to_act(&self) -> Option { + self.state.to_act() + } + + /// Validate and apply `a`. Returns the engine step. + pub fn apply(&mut self, a: Action) -> Result { + let Some(seat) = self.state.to_act() else { + return err("terminal"); + }; + let l = self.state.legal(); + let ok = match a { + Action::Fold => l.can_fold, + Action::Check => l.can_check, + Action::Call => !l.can_check, + Action::RaiseTo(t) => l.can_raise && t >= l.min_raise_to && t <= l.max_raise_to, + }; + if !ok { + return err("illegal action"); + } + let pre = self.state; + let st = self.state.street(); + let step = self.state.apply(a); + self.steps.push(Step::Act { + pre, + seat, + action: a, + blen: self.blen, + }); + self.events.push(Event { + seat: seat as u8, + street: st, + action: a, + }); + if let NStep::NewStreet(s) = step { + let n = s.board_len(); + if self.board.len() < n { + return err("board too short"); + } + self.blen = n; + self.steps.push(Step::Board(n)); + } + Ok(step) + } + + /// Fold every seat before `seat` that is to act (they were skipped in the source line). + pub fn skip_to(&mut self, seat: usize) -> Result<(), String> { + while let Some(t) = self.state.to_act() { + if t == seat { + return Ok(()); + } + if !self.state.legal().can_fold { + return err("skipped seat cannot fold"); + } + if let NStep::Terminal = self.apply(Action::Fold)? { + return err("hand ended while skipping"); + } + if self.state.street() != self.steps_street() { + return err("street advanced while skipping"); + } + } + err("seat never reached") + } + + fn steps_street(&self) -> Street { + self.events + .last() + .map(|e| e.street) + .unwrap_or(Street::Preflop) + } + + /// Convert a raise-to size in chips (rounded source data) into a legal `RaiseTo`: + /// within 1bb of the all-in or minimum bounds it snaps to them, otherwise it must be legal. + pub fn snap_raise(&self, to: i32) -> Result { + let l = self.state.legal(); + if !l.can_raise { + return err("cannot raise"); + } + let t = if to >= l.max_raise_to - BB { + l.max_raise_to + } else if to < l.min_raise_to { + if l.min_raise_to - to <= BB { + l.min_raise_to + } else { + return err("raise below minimum"); + } + } else { + to + }; + Ok(Action::RaiseTo(t)) + } + + /// Fresh player for `seat`, fed with every step so far. + pub fn player(&self, f: &dyn PolicyFactory, seat: usize, seed: u64) -> Box { + let mut p = f.new_player(seat, &self.cfg, seed); + feed(&mut *p, &self.steps, &self.board); + p + } + + /// Distribution of `p` for `hole` at the current decision. + pub fn dist(&self, p: &mut dyn Player, hole: [Card; 2]) -> Dist { + let seat = self.state.to_act().expect("decision"); + let v = View { + cfg: &self.cfg, + state: &self.state, + board: self.visible_board(), + history: &self.events, + seat, + }; + p.dist(&v, hole) + } +} + +/// Feed recorded steps to a player (observe / observe_board in engine order). +pub fn feed(p: &mut dyn Player, steps: &[Step], board: &[Card]) { + for s in steps { + match s { + Step::Act { + pre, seat, action, .. + } => p.observe(pre, *seat, *action), + Step::Board(n) => p.observe_board(&board[..*n]), + } + } +} + +/// Map a concrete policy action onto the index of the nearest option in `targets` +/// (same class; raises by log-ratio of the raise increment). `None` if no option has the class. +pub fn nearest_action(state: &State, targets: &[Action], a: Action) -> Option { + match a { + Action::Fold => targets.iter().position(|t| matches!(t, Action::Fold)), + Action::Check | Action::Call => targets + .iter() + .position(|t| matches!(t, Action::Check | Action::Call)), + Action::RaiseTo(to) => { + let inc = |x: i32| ((x - state.cur_bet()).max(1)) as f64; + let mut best: Option<(usize, f64)> = None; + for (i, t) in targets.iter().enumerate() { + if let Action::RaiseTo(tt) = t { + let d = (inc(to) / inc(*tt)).ln().abs(); + if best.is_none_or(|(_, bd)| d < bd) { + best = Some((i, d)); + } + } + } + best.map(|b| b.0) + } + } +} + +/// Pot fraction of a raise (for reports). +pub fn frac(state: &State, to: i32) -> f64 { + raise_fraction(state, to) +} diff --git a/arena/referee/src/river.rs b/arena/referee/src/river.rs new file mode 100644 index 00000000..9128d8c4 --- /dev/null +++ b/arena/referee/src/river.rs @@ -0,0 +1,281 @@ +//! Heads-up river referee: how many mbb does a policy's river strategy lose against the exact +//! equilibrium of the same spot? +//! +//! Pipeline for one spot (a PokerBench river row truncated to the river start): +//! 1. replay the history on the engine (6-max, all other seats folded); +//! 2. ranges: Bayes-update the policy's own action probabilities along the history for every +//! hole pair ([`RangeMode::Policy`]) or use uniform ranges; +//! 3. solve the river subgame with CFR+ ([`crate::solver`]) over a fixed bet menu; +//! 4. query the policy at every river decision node for every hand in range, map its action +//! distribution to the menu (nearest raise size), giving a full strategy; +//! 5. exact best responses give the policy's EV loss per seat, in mbb of the big blind +//! (`value_p(eq) + BR_opponent(policy_p)`); a calling station is evaluated as a control. +//! +//! The policy is assumed to play both seats, so both ranges and both strategies come from it. + +use crate::pokerbench::{replay_to_river, Spot}; +use crate::replay::{feed, nearest_action, Replay, Step, BB}; +use crate::solver::{Game, Kind, Strategy, N}; +use bench::mix; +use bench::policy::{Dist, PolicyFactory, View}; +use cards::{all_holes, Card}; +use nlhe::abstraction::{BetSizing, Menu}; +use nlhe::{Action, State}; +use serde::Serialize; + +/// River menu: first bet {0.5, 1.0} pot + all-in, later raises {1.0} + all-in, up to 3 raises +/// (the Pluribus river abstraction from the paper). +pub fn river_sizing() -> BetSizing { + let a = [Menu::new(&[0.5, 1.0], true), Menu::new(&[1.0], true)]; + BetSizing::new([&a, &a, &a, &a], [3, 3, 3, 3]) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RangeMode { + /// Bayes ranges from the policy's own action probabilities. + Policy, + Uniform, +} + +pub struct RiverSpot { + pub replay: Replay, + /// `[oop, ip]` seats. + pub seats: [usize; 2], + pub board: [Card; 5], +} + +impl RiverSpot { + pub fn from_spot(spot: &Spot) -> Result { + let (replay, seats) = replay_to_river(spot)?; + let board: [Card; 5] = replay.board.clone().try_into().map_err(|_| "board")?; + Ok(RiverSpot { + replay, + seats, + board, + }) + } + + /// Key identifying the river node (many dataset rows share one). + pub fn key(spot: &Spot) -> String { + let (mut deals, mut cut) = (0, spot.post_line.len()); + for (i, t) in spot.post_line.iter().enumerate() { + if *t == crate::pokerbench::PostTok::Deal { + deals += 1; + if deals == 2 { + cut = i; + break; + } + } + } + format!( + "{}|{}|{:?}", + crate::pokerbench::fmt_pre_line(&spot.pre_line), + cards::cards_str(&spot.board_all), + &spot.post_line[..cut] + ) + } + + pub fn pot_bb(&self) -> f64 { + self.replay.state.pot() as f64 / BB as f64 + } +} + +fn floor(p: f64) -> f64 { + p.max(1e-4) +} + +/// Probability that a player with this `Dist` takes `taken` (raises mapped to the nearest size). +fn taken_prob(d: &Dist, pre: &State, taken: Action) -> f64 { + let acts = d.actions(); + match nearest_action(pre, acts, taken) { + Some(i) => d.prob(i), + None => 0.0, + } +} + +/// Bayes range of `seat` over all hole pairs: product of the policy's probabilities of the +/// actions that seat actually took (normalised to max 1). Falls back to uniform if empty. +pub fn bayes_range(rs: &RiverSpot, f: &dyn PolicyFactory, player: usize, seed: u64) -> Vec { + let seat = rs.seats[player]; + let cfg = rs.replay.cfg; + let holes = all_holes(); + let bm = cards::mask_of(&rs.board); + let mut w: Vec = holes + .iter() + .map(|h| { + if cards::bit(h[0]) & bm == 0 && cards::bit(h[1]) & bm == 0 { + 1.0 + } else { + 0.0 + } + }) + .collect(); + let mut p = f.new_player(seat, &cfg, seed); + let mut k = 0; + for s in &rs.replay.steps { + match *s { + Step::Act { + pre, + seat: s_seat, + action, + blen, + } => { + if s_seat == seat { + let v = View { + cfg: &cfg, + state: &pre, + board: &rs.board[..blen], + history: &rs.replay.events[..k], + seat, + }; + let partial = cards::mask_of(&rs.board[..blen]); + for (i, h) in holes.iter().enumerate() { + if w[i] > 0.0 + && cards::bit(h[0]) & partial == 0 + && cards::bit(h[1]) & partial == 0 + { + let d = p.dist(&v, *h); + w[i] *= floor(taken_prob(&d, &pre, action)); + } + } + } + p.observe(&pre, s_seat, action); + k += 1; + } + Step::Board(n) => p.observe_board(&rs.board[..n]), + } + } + let mx = w.iter().cloned().fold(0.0, f64::max); + if mx <= 0.0 { + return vec![1.0; N]; + } + w.iter().map(|x| x / mx).collect() +} + +/// The policy's strategy on every river decision node of `game` (hands outside the range get +/// a uniform dummy). +pub fn policy_strategy(game: &Game, rs: &RiverSpot, f: &dyn PolicyFactory, seed: u64) -> Strategy { + let holes = all_holes(); + let cfg = rs.replay.cfg; + let mut out = vec![Vec::new(); game.tree.nodes.len()]; + for id in game.tree.action_nodes() { + let node = &game.tree.nodes[id]; + let Kind::Action { player, acts, .. } = &node.kind else { + unreachable!() + }; + let seat = game.tree.seats[*player]; + let mut p = f.new_player(seat, &cfg, mix(seed, id as u64)); + feed(&mut *p, &rs.replay.steps, &rs.board); + let mut events = rs.replay.events.clone(); + let mut st = rs.replay.state; + for &a in &node.path { + let s = st.to_act().unwrap(); + p.observe(&st, s, a); + events.push(bench::policy::Event { + seat: s as u8, + street: st.street(), + action: a, + }); + st.apply(a); + } + let v = View { + cfg: &cfg, + state: &node.state, + board: &rs.board, + history: &events, + seat, + }; + let n = acts.len(); + let mut s = vec![0.0; n * N]; + for h in 0..N { + if game.range[*player][h] <= 0.0 { + for a in 0..n { + s[a * N + h] = 1.0 / n as f64; + } + continue; + } + let d = p.dist(&v, holes[h]); + let mut tot = 0.0; + for i in 0..d.len() { + let j = nearest_action(&node.state, acts, d.action(i)).unwrap_or(0); + let pr = d.prob(i); + s[j * N + h] += pr; + tot += pr; + } + for a in 0..n { + s[a * N + h] = if tot > 0.0 { + s[a * N + h] / tot + } else { + 1.0 / n as f64 + }; + } + } + out[id] = s; + } + Strategy(out) +} + +#[derive(Clone, Debug, Serialize)] +pub struct RiverResult { + pub pot_bb: f64, + pub stack_bb: f64, + pub nodes: usize, + /// Reference solver exploitability, mbb (solver error). + pub ref_expl_mbb: f64, + /// EV loss of the policy's river strategy per seat `[oop, ip]`, mbb. + pub ev_loss_mbb: [f64; 2], + /// Same for a calling station (control). + pub station_loss_mbb: [f64; 2], + /// Equilibrium value per seat, mbb. + pub eq_value_mbb: [f64; 2], +} + +/// Evaluate one spot. `iters`: CFR+ iterations for the reference equilibrium. +pub fn evaluate( + rs: &RiverSpot, + f: &dyn PolicyFactory, + mode: RangeMode, + iters: usize, + seed: u64, +) -> Result { + let range = match mode { + RangeMode::Policy => [ + bayes_range(rs, f, 0, mix(seed, 1)), + bayes_range(rs, f, 1, mix(seed, 2)), + ], + RangeMode::Uniform => [vec![1.0; N], vec![1.0; N]], + }; + let game = Game::new( + rs.replay.state, + rs.seats, + rs.board, + range, + &river_sizing(), + BB, + )?; + let eq = game.solve(iters); + let pol = policy_strategy(&game, rs, f, mix(seed, 3)); + let station = station_strategy(&game); + let bbm = 1000.0 / BB as f64; + let v = game.value(&eq); + let st = &rs.replay.state; + Ok(RiverResult { + pot_bb: st.pot() as f64 / BB as f64, + stack_bb: st.stack(rs.seats[0]).min(st.stack(rs.seats[1])) as f64 / BB as f64, + nodes: game.tree.nodes.len(), + ref_expl_mbb: game.exploitability(&eq) * bbm, + ev_loss_mbb: game.ev_loss(&pol, &eq), + station_loss_mbb: game.ev_loss(&station, &eq), + eq_value_mbb: [v[0] * bbm, v[1] * bbm], + }) +} + +/// Always check/call. +pub fn station_strategy(game: &Game) -> Strategy { + Strategy::from_fn(&game.tree, |id, a, _, _| { + let Kind::Action { acts, .. } = &game.tree.nodes[id].kind else { + unreachable!() + }; + matches!(acts[a], Action::Check | Action::Call) as u8 as f64 + }) +} diff --git a/arena/referee/src/solver.rs b/arena/referee/src/solver.rs new file mode 100644 index 00000000..cefb34c3 --- /dev/null +++ b/arena/referee/src/solver.rs @@ -0,0 +1,566 @@ +//! Exact heads-up river solver: vector-form CFR+ over the 1326 hole pairs. +//! +//! Self-contained (no third-party solver code). The betting tree is generated by the `nlhe` +//! engine from a [`BetSizing`] menu, so a tested policy can be queried at exactly the same +//! states. Everything is `f64`; utilities are chips won from the start of the hand (money +//! already in the pot is sunk), so a showdown winner gains the loser's contribution. +//! +//! * [`Ctx`]: per-board hand ranks and O(n) showdown / fold evaluation with card removal +//! (sort by rank, prefix sums per card; inclusion-exclusion on the two hole cards). +//! * [`Tree`]: betting tree (player 0 = OOP, player 1 = IP). +//! * [`Solver`]: simultaneous-update CFR+ with linear averaging. +//! * [`Game::best_response`] / [`Game::ev_loss`]: exact BR against any fixed [`Strategy`]. +//! +//! EV values are normalised by the total compatible range mass `Z`, i.e. they are expected +//! chips for a random deal of both ranges. + +use cards::{all_holes, bit, evaluate, mask_of, Card}; +use nlhe::abstraction::{abstract_actions, ActionList, BetSizing}; +use nlhe::{Action, State, Step}; + +pub const N: usize = 1326; + +/// Per-board hand data. +pub struct Ctx { + pub board: [Card; 5], + pub cards: Vec<[u8; 2]>, + pub valid: Vec, + pub rank: Vec, + /// Valid hands ascending by rank, split into tie groups. + order: Vec, + groups: Vec<(usize, usize)>, +} + +impl Ctx { + pub fn new(board: [Card; 5]) -> Ctx { + let holes = all_holes(); + let bm = mask_of(&board); + let mut valid = vec![false; N]; + let mut rank = vec![0u32; N]; + let mut cards = vec![[0u8; 2]; N]; + for (i, h) in holes.iter().enumerate() { + cards[i] = *h; + if bit(h[0]) & bm == 0 && bit(h[1]) & bm == 0 { + valid[i] = true; + rank[i] = evaluate(bit(h[0]) | bit(h[1]) | bm); + } + } + let mut order: Vec = (0..N as u16).filter(|&i| valid[i as usize]).collect(); + order.sort_by_key(|&i| rank[i as usize]); + let mut groups = Vec::new(); + let mut s = 0; + for i in 1..=order.len() { + if i == order.len() || rank[order[i] as usize] != rank[order[s] as usize] { + groups.push((s, i)); + s = i; + } + } + Ctx { + board, + cards, + valid, + rank, + order, + groups, + } + } + + /// Zero out hands that collide with the board. + pub fn mask(&self, r: &mut [f64]) { + for i in 0..N { + if !self.valid[i] { + r[i] = 0.0; + } + } + } + + fn card_sums(&self, r: &[f64]) -> (f64, [f64; 52]) { + let mut t = 0.0; + let mut c = [0.0; 52]; + for i in 0..N { + if r[i] != 0.0 { + t += r[i]; + c[self.cards[i][0] as usize] += r[i]; + c[self.cards[i][1] as usize] += r[i]; + } + } + (t, c) + } + + /// `out[h]` = sum of `r[h']` over hands `h'` that do not share a card with `h`. + pub fn compat(&self, r: &[f64], out: &mut [f64]) { + let (t, c) = self.card_sums(r); + for i in 0..N { + out[i] = if self.valid[i] { + let [a, b] = self.cards[i]; + t - c[a as usize] - c[b as usize] + r[i] + } else { + 0.0 + }; + } + } + + /// Showdown counterfactual values for the holder: `amount * (P(win) - P(lose))` weighted + /// by the opponent reach `r` (ties pay nothing). + pub fn showdown(&self, r: &[f64], amount: f64, out: &mut [f64]) { + let (tot, tc) = self.card_sums(r); + let mut less = 0.0; + let mut lc = [0.0f64; 52]; + out.iter_mut().for_each(|x| *x = 0.0); + for &(s, e) in &self.groups { + let mut gt = 0.0; + let mut gc = [0.0f64; 52]; + for &h in &self.order[s..e] { + let h = h as usize; + gt += r[h]; + gc[self.cards[h][0] as usize] += r[h]; + gc[self.cards[h][1] as usize] += r[h]; + } + for &h in &self.order[s..e] { + let h = h as usize; + let [a, b] = [self.cards[h][0] as usize, self.cards[h][1] as usize]; + let comp_less = less - lc[a] - lc[b]; + let comp_eq = gt - gc[a] - gc[b] + r[h]; + let comp_all = tot - tc[a] - tc[b] + r[h]; + let greater = comp_all - comp_less - comp_eq; + out[h] = amount * (comp_less - greater); + } + for &h in &self.order[s..e] { + let h = h as usize; + less += r[h]; + lc[self.cards[h][0] as usize] += r[h]; + lc[self.cards[h][1] as usize] += r[h]; + } + } + } +} + +#[derive(Clone, Debug)] +pub enum Kind { + Action { + player: usize, + acts: Vec, + kids: Vec, + }, + /// `folder` (player index) loses `amount`. + Fold { folder: usize, amount: f64 }, + /// Showdown for `amount` (the smaller contribution). + Showdown { amount: f64 }, +} + +#[derive(Clone, Debug)] +pub struct Node { + pub kind: Kind, + /// Engine state at this node (before the acting player moves). + pub state: State, + /// Actions taken from the root. + pub path: Vec, +} + +pub struct Tree { + pub nodes: Vec, + pub seats: [usize; 2], +} + +impl Tree { + /// Build from a river decision state. `seats = [oop, ip]`. + pub fn build(root: State, seats: [usize; 2], sizing: &BetSizing) -> Result { + if root.is_terminal() || root.street() != nlhe::Street::River { + return Err("root must be a river decision".into()); + } + let mut t = Tree { + nodes: Vec::new(), + seats, + }; + t.rec(root, vec![], sizing)?; + Ok(t) + } + + fn rec(&mut self, st: State, path: Vec, sizing: &BetSizing) -> Result { + let id = self.nodes.len(); + let kind = if st.is_terminal() { + let [a, b] = self.seats; + if st.showdown() { + Kind::Showdown { + amount: st.contributed(a).min(st.contributed(b)) as f64, + } + } else { + let folder = if st.is_folded(a) { 0 } else { 1 }; + Kind::Fold { + folder, + amount: st.contributed(self.seats[folder]) as f64, + } + } + } else { + let seat = st.to_act().unwrap(); + let player = self + .seats + .iter() + .position(|&s| s == seat) + .ok_or("unexpected seat in river tree")?; + let mut list = ActionList::new(); + abstract_actions(&st, sizing, &mut list); + Kind::Action { + player, + acts: list.as_slice().to_vec(), + kids: vec![], + } + }; + self.nodes.push(Node { + kind: kind.clone(), + state: st, + path: path.clone(), + }); + if let Kind::Action { acts, .. } = kind { + let mut kids = Vec::new(); + for &a in &acts { + let mut s2 = st; + if let Step::NewStreet(_) = s2.apply(a) { + return Err("street change inside river tree".into()); + } + let mut p2 = path.clone(); + p2.push(a); + kids.push(self.rec(s2, p2, sizing)?); + } + if let Kind::Action { kids: k, .. } = &mut self.nodes[id].kind { + *k = kids; + } + } + Ok(id) + } + + pub fn action_nodes(&self) -> impl Iterator + '_ { + (0..self.nodes.len()).filter(|&i| matches!(self.nodes[i].kind, Kind::Action { .. })) + } +} + +/// Per node, `n_actions * N` probabilities laid out `[a * N + h]`. Empty for terminals. +#[derive(Clone, Debug)] +pub struct Strategy(pub Vec>); + +impl Strategy { + /// Build from `f(node_id, action_index, n_actions, hand) -> weight`, normalised per hand. + pub fn from_fn(tree: &Tree, mut f: impl FnMut(usize, usize, usize, usize) -> f64) -> Strategy { + let mut v = vec![Vec::new(); tree.nodes.len()]; + for id in tree.action_nodes() { + let Kind::Action { acts, .. } = &tree.nodes[id].kind else { + unreachable!() + }; + let n = acts.len(); + let mut s = vec![0.0; n * N]; + for h in 0..N { + let mut tot = 0.0; + for a in 0..n { + let w = f(id, a, n, h).max(0.0); + s[a * N + h] = w; + tot += w; + } + for a in 0..n { + s[a * N + h] = if tot > 0.0 { + s[a * N + h] / tot + } else { + 1.0 / n as f64 + }; + } + } + v[id] = s; + } + Strategy(v) + } +} + +pub struct Game { + pub ctx: Ctx, + pub tree: Tree, + /// Range weights per player (0 = OOP, 1 = IP), masked to valid hands. + pub range: [Vec; 2], + /// Total compatible mass. + pub z: f64, + pub bb: f64, +} + +impl Game { + pub fn new( + root: State, + seats: [usize; 2], + board: [Card; 5], + mut range: [Vec; 2], + sizing: &BetSizing, + bb: i32, + ) -> Result { + let ctx = Ctx::new(board); + for r in range.iter_mut() { + ctx.mask(r); + } + let tree = Tree::build(root, seats, sizing)?; + let mut c = vec![0.0; N]; + ctx.compat(&range[1], &mut c); + let z: f64 = (0..N).map(|h| range[0][h] * c[h]).sum(); + if z <= 0.0 { + return Err("empty compatible ranges".into()); + } + Ok(Game { + ctx, + tree, + range, + z, + bb: bb as f64, + }) + } + + fn terminal(&self, id: usize, reach: [&[f64]; 2]) -> Option<[Vec; 2]> { + match &self.tree.nodes[id].kind { + Kind::Showdown { amount } => { + let (mut a, mut b) = (vec![0.0; N], vec![0.0; N]); + self.ctx.showdown(reach[1], *amount, &mut a); + self.ctx.showdown(reach[0], *amount, &mut b); + Some([a, b]) + } + Kind::Fold { folder, amount } => { + let w = 1 - folder; + let mut cf = vec![0.0; N]; + let mut cw = vec![0.0; N]; + self.ctx.compat(reach[w], &mut cf); // folder's view: compatible winner reach + self.ctx.compat(reach[*folder], &mut cw); + cf.iter_mut().for_each(|x| *x *= -amount); + cw.iter_mut().for_each(|x| *x *= *amount); + let mut out = [Vec::new(), Vec::new()]; + out[*folder] = cf; + out[w] = cw; + Some(out) + } + Kind::Action { .. } => None, + } + } + + /// Counterfactual values of a fixed profile. + fn eval(&self, s: &Strategy, id: usize, reach: [&[f64]; 2]) -> [Vec; 2] { + if let Some(v) = self.terminal(id, reach) { + return v; + } + let Kind::Action { + player: p, kids, .. + } = &self.tree.nodes[id].kind + else { + unreachable!() + }; + let q = 1 - p; + let sig = &s.0[id]; + let (mut vp, mut vq) = (vec![0.0; N], vec![0.0; N]); + for (a, &k) in kids.iter().enumerate() { + let nr: Vec = (0..N).map(|h| reach[*p][h] * sig[a * N + h]).collect(); + let mut r2 = reach; + r2[*p] = &nr; + let c = self.eval(s, k, r2); + for h in 0..N { + vp[h] += sig[a * N + h] * c[*p][h]; + vq[h] += c[q][h]; + } + } + let mut out = [Vec::new(), Vec::new()]; + out[*p] = vp; + out[q] = vq; + out + } + + /// Expected chips per player when both follow `s` (random deal of the ranges). + pub fn value(&self, s: &Strategy) -> [f64; 2] { + let v = self.eval(s, 0, [&self.range[0], &self.range[1]]); + [0, 1].map(|p| (0..N).map(|h| self.range[p][h] * v[p][h]).sum::() / self.z) + } + + fn br(&self, id: usize, p: usize, opp: &Strategy, opp_reach: &[f64]) -> Vec { + let q = 1 - p; + // terminals: BR player's own reach is irrelevant to its cfv, pass dummy + let dummy = vec![0.0; N]; + let mut reach: [&[f64]; 2] = [&dummy, &dummy]; + reach[q] = opp_reach; + if let Some(v) = self.terminal(id, reach) { + return v.into_iter().nth(p).unwrap(); + } + let Kind::Action { player, kids, .. } = &self.tree.nodes[id].kind else { + unreachable!() + }; + if *player == p { + let mut best = vec![f64::NEG_INFINITY; N]; + for &k in kids { + let c = self.br(k, p, opp, opp_reach); + for h in 0..N { + best[h] = best[h].max(c[h]); + } + } + best + } else { + let sig = &opp.0[id]; + let mut sum = vec![0.0; N]; + for (a, &k) in kids.iter().enumerate() { + let nr: Vec = (0..N).map(|h| opp_reach[h] * sig[a * N + h]).collect(); + let c = self.br(k, p, opp, &nr); + for h in 0..N { + sum[h] += c[h]; + } + } + sum + } + } + + /// Expected chips of player `p` best-responding to the other player's part of `s`. + pub fn best_response(&self, s: &Strategy, p: usize) -> f64 { + let v = self.br(0, p, s, &self.range[1 - p]); + (0..N).map(|h| self.range[p][h] * v[h]).sum::() / self.z + } + + /// Exploitability in chips: `(BR_0 + BR_1)` summed over both seats' best responses + /// (0 at equilibrium since the game is zero-sum). + pub fn exploitability(&self, s: &Strategy) -> f64 { + (self.best_response(s, 0) + self.best_response(s, 1)) / 2.0 + } + + /// EV loss of each player's strategy in `s` versus the reference equilibrium `eq`, in mbb: + /// `value_p(eq) + BR_other(s_p)`. Zero (up to solver error) for an equilibrium strategy. + pub fn ev_loss(&self, s: &Strategy, eq: &Strategy) -> [f64; 2] { + let v = self.value(eq); + [0, 1].map(|p| (v[p] + self.best_response(s, 1 - p)) * 1000.0 / self.bb) + } + + /// Run `iters` iterations of CFR+ (linear averaging); returns the average strategy. + pub fn solve(&self, iters: usize) -> Strategy { + let mut sv = Solver::new(self); + for _ in 0..iters { + sv.iterate(); + } + sv.average() + } +} + +pub struct Solver<'g> { + g: &'g Game, + regret: Vec>, + ssum: Vec>, + t: f64, +} + +impl<'g> Solver<'g> { + pub fn new(g: &'g Game) -> Self { + let mut regret = vec![Vec::new(); g.tree.nodes.len()]; + for id in g.tree.action_nodes() { + if let Kind::Action { acts, .. } = &g.tree.nodes[id].kind { + regret[id] = vec![0.0; acts.len() * N]; + } + } + Solver { + g, + ssum: regret.clone(), + regret, + t: 0.0, + } + } + + fn sigma(&self, id: usize, n: usize) -> Vec { + let r = &self.regret[id]; + let mut s = vec![0.0; n * N]; + for h in 0..N { + let tot: f64 = (0..n).map(|a| r[a * N + h]).sum(); + for a in 0..n { + s[a * N + h] = if tot > 0.0 { + r[a * N + h] / tot + } else { + 1.0 / n as f64 + }; + } + } + s + } + + pub fn iterate(&mut self) { + self.t += 1.0; + let g = self.g; + self.walk(0, [&g.range[0], &g.range[1]]); + } + + fn walk(&mut self, id: usize, reach: [&[f64]; 2]) -> [Vec; 2] { + let g = self.g; + if let Some(v) = g.terminal(id, reach) { + return v; + } + let Kind::Action { + player: p, + kids, + acts, + } = &g.tree.nodes[id].kind + else { + unreachable!() + }; + let (p, q, n) = (*p, 1 - *p, acts.len()); + let sig = self.sigma(id, n); + let mut vp = vec![0.0; N]; + let mut vq = vec![0.0; N]; + let mut cp: Vec> = Vec::with_capacity(n); + for (a, &k) in kids.iter().enumerate() { + let nr: Vec = (0..N).map(|h| reach[p][h] * sig[a * N + h]).collect(); + let mut r2 = reach; + r2[p] = &nr; + let mut c = self.walk(k, r2); + for h in 0..N { + vp[h] += sig[a * N + h] * c[p][h]; + vq[h] += c[q][h]; + } + cp.push(std::mem::take(&mut c[p])); + } + let (reg, ss) = (&mut self.regret[id], &mut self.ssum[id]); + for a in 0..n { + for h in 0..N { + let i = a * N + h; + reg[i] = (reg[i] + cp[a][h] - vp[h]).max(0.0); + ss[i] += self.t * reach[p][h] * sig[i]; + } + } + let mut out = [Vec::new(), Vec::new()]; + out[p] = vp; + out[q] = vq; + out + } + + /// Average strategy (uniform where a hand was never reached). + pub fn average(&self) -> Strategy { + let g = self.g; + let mut v = vec![Vec::new(); g.tree.nodes.len()]; + for id in g.tree.action_nodes() { + let n = self.ssum[id].len() / N; + let mut s = vec![0.0; n * N]; + for h in 0..N { + let tot: f64 = (0..n).map(|a| self.ssum[id][a * N + h]).sum(); + for a in 0..n { + s[a * N + h] = if tot > 0.0 { + self.ssum[id][a * N + h] / tot + } else { + 1.0 / n as f64 + }; + } + } + v[id] = s; + } + Strategy(v) + } +} + +/// Reference O(n^2) showdown values (tests). +pub fn showdown_brute(ctx: &Ctx, r: &[f64], amount: f64) -> Vec { + let mut out = vec![0.0; N]; + for h in 0..N { + if !ctx.valid[h] { + continue; + } + for o in 0..N { + if !ctx.valid[o] || r[o] == 0.0 { + continue; + } + let (a, b) = (ctx.cards[h], ctx.cards[o]); + if a[0] == b[0] || a[0] == b[1] || a[1] == b[0] || a[1] == b[1] { + continue; + } + out[h] += r[o] * amount * (ctx.rank[h].cmp(&ctx.rank[o]) as i32 as f64); + } + } + out +} diff --git a/arena/referee/src/toy.rs b/arena/referee/src/toy.rs new file mode 100644 index 00000000..2312bb1e --- /dev/null +++ b/arena/referee/src/toy.rs @@ -0,0 +1,42 @@ +//! Toy river with a closed-form answer, used to validate the solver. +//! +//! Board `Ts Tc Th Td 2c` (quads; only the kicker matters). OOP holds half "nuts" (any `AA`, +//! kicker A) and half air (`33`, kicker 3); IP holds only bluff catchers (`KK`, kicker K). +//! Pot 200 (100 each), one pot-sized bet, no raises. Analytic equilibrium (bet = pot): +//! * OOP value always bets; air bets with probability 1/2 (so bluffs are 1/3 of bets); +//! * IP calls with probability P/(P+B) = 1/2; +//! * value to OOP = 50 chips (0.25 pot), IP = -50. + +use crate::replay::Replay; +use crate::solver::{Game, N}; +use cards::{all_holes, parse_cards}; +use nlhe::abstraction::{BetSizing, Menu}; +use nlhe::Action; + +pub fn toy_game() -> Game { + let board: [u8; 5] = parse_cards("TsTcThTd2c").unwrap().try_into().unwrap(); + let mut r = Replay::new(2, &board); + // Heads-up: SB (seat 0) limps, BB checks, then check-check on every street. + r.apply(Action::Call).unwrap(); + r.apply(Action::Check).unwrap(); + for _ in 0..2 { + r.apply(Action::Check).unwrap(); + r.apply(Action::Check).unwrap(); + } + assert_eq!(r.state.street(), nlhe::Street::River); + let holes = all_holes(); + let pair_of = |rank: u8| move |h: &[u8; 2]| h[0] >> 2 == rank && h[1] >> 2 == rank; + let (aa, tt, kk) = (pair_of(12), pair_of(1), pair_of(11)); + let (mut oop, mut ip) = (vec![0.0; N], vec![0.0; N]); + for (i, h) in holes.iter().enumerate() { + if aa(h) || tt(h) { + oop[i] = 1.0; + } + if kk(h) { + ip[i] = 1.0; + } + } + let menu = [Menu::new(&[1.0], false)]; + let sizing = BetSizing::new([&menu, &menu, &menu, &menu], [1, 1, 1, 1]); + Game::new(r.state, [1, 0], board, [oop, ip], &sizing, 100).unwrap() +} diff --git a/arena/referee/tests/referee.rs b/arena/referee/tests/referee.rs new file mode 100644 index 00000000..a35f5979 --- /dev/null +++ b/arena/referee/tests/referee.rs @@ -0,0 +1,231 @@ +//! Validation: parser roundtrips, replay legality, plausible scores, solver vs analytic answers. + +use bench::bp::train_toy; +use bench::builtin::builtin; +use bench::policy::PolicyFactory; +use referee::pokerbench::*; +use referee::river::{self, RangeMode, RiverSpot}; +use referee::solver::{showdown_brute, Ctx, Kind, Strategy, N}; +use referee::toy::toy_game; + +fn data_present() -> bool { + default_dir().join(file_name(true, true)).exists() +} + +#[test] +fn parser_roundtrips() { + if !data_present() { + eprintln!("PokerBench data missing; skipping"); + return; + } + let dir = default_dir(); + let pre = std::fs::read_to_string(dir.join(file_name(true, true))).unwrap(); + let rows = parse_csv(&pre); + let ci = rows[0].iter().position(|x| x == "prev_line").unwrap(); + for r in &rows[1..] { + let l = parse_pre_line(&r[ci]).unwrap(); + assert_eq!(fmt_pre_line(&l), r[ci]); + } + let post = std::fs::read_to_string(dir.join(file_name(false, true))).unwrap(); + let rows = parse_csv(&post); + let h = &rows[0]; + let col = |n: &str| h.iter().position(|x| x == n).unwrap(); + let (cp, cl, ct, cr, cf) = ( + col("postflop_action"), + col("preflop_action"), + col("board_turn"), + col("board_river"), + col("board_flop"), + ); + for r in &rows[1..] { + assert_eq!(fmt_pre_line(&parse_pre_line(&r[cl]).unwrap()), r[cl]); + let l = parse_post_line(&r[cp]).unwrap(); + let dealt = cards::parse_cards(&format!("{}{}", r[ct], r[cr])).unwrap(); + assert_eq!(fmt_post_line(&l, &dealt), r[cp]); + assert!(cards::parse_cards(&r[cf]).unwrap().len() == 3); + } +} + +#[test] +fn replayed_states_are_legal_and_covered() { + if !data_present() { + return; + } + let (spots, bad) = load(&default_dir(), Which::All, true).unwrap(); + assert_eq!(bad, 0); + assert_eq!(spots.len(), 11_000); + let mut ok = 0; + let mut pot_ok = 0; + for s in &spots { + if let Ok(r) = replay_spot(s) { + ok += 1; + let st = &r.replay.state; + assert_eq!(st.to_act(), Some(r.hero_seat)); + assert_eq!(st.street(), s.street); + assert!(!st.is_terminal()); + pot_ok += (r.pot_diff_bb.abs() <= 1.0 + 0.03 * s.pot_bb) as usize; + } + } + assert!( + ok as f64 / spots.len() as f64 > 0.99, + "coverage {ok}/{}", + spots.len() + ); + assert!(pot_ok as f64 / ok as f64 > 0.9); +} + +fn acc(name: &str, limit: usize) -> f64 { + let f = builtin(name).unwrap(); + let (spots, bad) = load(&default_dir(), Which::All, true).unwrap(); + let spots = stride(&spots, limit); + run(&spots, bad, &*f, 7).overall.exact +} + +#[test] +fn builtin_accuracy_is_plausible() { + if !data_present() { + return; + } + let (tag, station, random) = (acc("tag", 3000), acc("station", 3000), acc("random", 3000)); + eprintln!("tag {tag:.3} station {station:.3} random {random:.3}"); + // Labels are balanced over fold/check/call/raise, so chance for a 4-way guess is ~25-30%. + assert!(tag > 0.40 && tag < 0.80); + assert!(tag > station && tag > random); +} + +#[test] +fn showdown_matches_brute_force() { + let board: [u8; 5] = cards::parse_cards("Ks7h2dJc7c") + .unwrap() + .try_into() + .unwrap(); + let ctx = Ctx::new(board); + let mut rng = cards::Rng::new(5); + let mut r = vec![0.0; N]; + for x in r.iter_mut() { + *x = rng.f64(); + } + ctx.mask(&mut r); + let mut fast = vec![0.0; N]; + ctx.showdown(&r, 3.0, &mut fast); + let slow = showdown_brute(&ctx, &r, 3.0); + for h in 0..N { + assert!( + (fast[h] - slow[h]).abs() < 1e-9, + "hand {h}: {} vs {}", + fast[h], + slow[h] + ); + } +} + +#[test] +fn toy_river_matches_analytic_equilibrium() { + let g = toy_game(); + let eq = g.solve(10_000); + let v = g.value(&eq); + assert!( + (v[0] - 50.0).abs() < 0.5 && (v[1] + 50.0).abs() < 0.5, + "values {v:?}" + ); + assert!( + g.exploitability(&eq) * 10.0 < 5.0, + "expl mbb {}", + g.exploitability(&eq) * 10.0 + ); + // Root: OOP acts; actions = [check, bet pot]. + let Kind::Action { + acts, kids, player, .. + } = &g.tree.nodes[0].kind + else { + panic!() + }; + let player = &(*player); + assert_eq!((*player as usize, acts.len()), (0, 2)); + let avg = |node: usize, a: usize, pl: usize| { + let h: Vec = (0..N).filter(|&h| g.range[pl][h] > 0.0).collect(); + ( + h.iter().map(|&i| eq.0[node][a * N + i]).sum::() / h.len() as f64, + h, + ) + }; + // Value hands (AA) bet always, air (TT-as-3s: pairs of threes are our air) mix 1/2. + let holes = cards::all_holes(); + let bet_freq = |rank: u8| { + let hs: Vec = (0..N) + .filter(|&h| { + g.range[0][h] > 0.0 && holes[h][0] >> 2 == rank && holes[h][1] >> 2 == rank + }) + .collect(); + hs.iter().map(|&i| eq.0[0][N + i]).sum::() / hs.len() as f64 + }; + assert!(bet_freq(12) > 0.99, "value bet freq {}", bet_freq(12)); + assert!( + (bet_freq(1) - 0.5).abs() < 0.03, + "bluff freq {}", + bet_freq(1) + ); + // IP facing the bet (kids[1]): actions [fold, call]; calls half. + let (call, _) = avg(kids[1], 1, 1); + assert!((call - 0.5).abs() < 0.03, "call freq {call}"); +} + +#[test] +fn equilibrium_loses_nothing_and_station_does() { + let g = toy_game(); + let reference = g.solve(10_000); + let mid = g.solve(300); + let l = g.ev_loss(&mid, &reference); + assert!( + l[0].abs() < 100.0 && l[1].abs() < 100.0, + "converged-strategy loss {l:?}" + ); + let l_ref = g.ev_loss(&reference, &reference); + assert!( + l_ref[0].abs() < 10.0 && l_ref[1].abs() < 10.0, + "self loss {l_ref:?}" + ); + let station = river::station_strategy(&g); + let ls = g.ev_loss(&station, &reference); + // OOP station never bluffs/value-bets: loses a lot; IP station is exploited by value bets. + assert!(ls[0] > 100.0 && ls[1] > 100.0, "station loss {ls:?}"); + let _: &Strategy = &station; +} + +#[test] +fn river_spots_end_to_end() { + if !data_present() { + return; + } + let (spots, _) = load(&default_dir(), Which::Postflop, true).unwrap(); + let mut done = 0; + let tag = builtin("tag").unwrap(); + let toy = train_toy(6, 2000, 1); + for s in spots + .iter() + .filter(|s| s.street == nlhe::Street::River) + .step_by(997) + { + let Ok(rs) = RiverSpot::from_spot(s) else { + continue; + }; + for f in [&*tag as &dyn PolicyFactory, &toy] { + let r = river::evaluate(&rs, f, RangeMode::Policy, 400, 3).unwrap(); + assert!(r.ev_loss_mbb.iter().all(|x| x.is_finite())); + let tol = 0.05 * r.pot_bb * 1000.0; + assert!(r.ref_expl_mbb < tol, "solver not converged: {r:?}"); + // Losses are non-negative up to solver error. + assert!(r.ev_loss_mbb.iter().all(|&x| x > -tol), "{r:?}"); + assert!(r.station_loss_mbb.iter().all(|&x| x > 0.0), "{r:?}"); + assert!( + (r.eq_value_mbb[0] + r.eq_value_mbb[1]).abs() < 1.0, + "zero-sum: {r:?}" + ); + } + done += 1; + if done == 3 { + break; + } + } + assert!(done >= 1); +} diff --git a/arena/server/Cargo.toml b/arena/server/Cargo.toml new file mode 100644 index 00000000..b6a08a46 --- /dev/null +++ b/arena/server/Cargo.toml @@ -0,0 +1,43 @@ +[package] +name = "sharingan-arena" +edition.workspace = true +version.workspace = true +description = "Poker Sharingan arena table server: REST + WebSocket table API, duplicate matches, hand histories, leaderboard." +license.workspace = true + +[lib] +name = "arena_server" +path = "src/lib.rs" + +[[bin]] +name = "sharingan-arena" +path = "src/main.rs" + +[dependencies] +cards.workspace = true +serde.workspace = true +serde_json.workspace = true +rayon.workspace = true +nlhe = { path = "../../engine/nlhe" } +bench = { path = "../bench" } +axum = { version = "0.8", features = ["ws"] } +tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time", "net", "signal"] } +futures-util = "0.3" +rusqlite = { version = "0.32", features = ["bundled"] } +sha2 = "0.10" +hmac = "0.12" +hex = "0.4" +libc = "0.2" +rand_chacha = "0.9" +uuid = { version = "1", features = ["v4"] } +postgres = "0.19" +tokio-postgres-rustls = "0.13" +rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } +webpki-roots = "0.26" +ureq = { version = "2.10", features = ["json"] } +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } + +[dev-dependencies] +reqwest = { version = "0.12", default-features = false, features = ["json"] } +tokio-tungstenite = "0.26" diff --git a/arena/server/README.md b/arena/server/README.md new file mode 100644 index 00000000..8759ee1b --- /dev/null +++ b/arena/server/README.md @@ -0,0 +1,163 @@ +# sharingan-arena: the table server + +REST + WebSocket server implementing [docs/TABLE_API.md](../../docs/TABLE_API.md). One crate, binary `sharingan-arena`. +Rules come from `engine/nlhe`, house bots and AIVAT from `arena/bench`. Storage behind the `Store` trait (`src/store.rs`): SQLite by default, +Postgres (`src/pgstore.rs`, migrations in `migrations/`) with `ARENA_DATABASE_URL`. + +## Run + +```bash +cargo run --release -p sharingan-arena -- --port 8080 +``` + +## Self-host + +Both benchmark tracks (and `sharingan eval`) include the configured house blueprint, +so the arena needs a model file and its card buckets. The public arena uses +**SHARINGAN-1/C@2e10 without search**. **SHARINGAN-2 is final C@1.83e11** from the same +training run; search is optional code and is not stored in either weight file. + +**The public checkpoint** (~125 GB disk): download it from [Hugging Face](https://huggingface.co/markokraemer/sharingan-1) (see the [model card](../../model-cards/sharingan-1/README.md)), then + +```bash +ARENA_BLUEPRINT=$PWD/sharingan-1.plcp ARENA_BUCKETS=tables:$PWD/buckets-200 ARENA_SIZING=medium \ + cargo run --release -p sharingan-arena -- --port 8080 +``` + +To use final SHARINGAN-2 locally, download its [169.9-GB weights](https://huggingface.co/markokraemer/sharingan-2) +and set `ARENA_BLUEPRINT` to `sharingan-2.plcp`; keep `medium` sizing and the same +`buckets-200` tables. Local scores with that opponent are not public C@2e10 scores. +Even with the same model, comparisons require matching code revision and tracking +options; model fingerprints alone do not establish the complete policy version. + +**A toy one in a minute** (for testing your setup; its scores are not comparable to the leaderboard): + +```bash +cargo build --release -p abstraction --bin build_buckets -p pluribus -p sharingan-arena +./target/release/build_buckets data/buckets-200 200 200 200 200000 # ~30 s on 128 cores, minutes on a laptop +./target/release/pluribus train --out tinybp --iters 2000000 --sizing tiny --players 6 --mem-gb 8 --buckets data/buckets-200 +./target/release/pluribus compact --ckpt tinybp/blueprint.bin --sums tinybp/snapshots.sum --out tinybp/tiny.plcp +ARENA_BLUEPRINT=$PWD/tinybp/tiny.plcp ARENA_BUCKETS=tables:$PWD/data/buckets-200 ARENA_SIZING=tiny ./target/release/sharingan-arena --port 8080 +``` + +Then `sharingan eval mybot.py --server http://127.0.0.1:8080`, or `sharingan eval mybot.py --local` with `sharingan-arena` on `PATH` +(same `ARENA_*` variables) to skip the server. + +The first start logs a generated admin token (set `ARENA_ADMIN_TOKEN` to pin it). Flags: `--port`, `--bind HOST:PORT`, `--db PATH`. + +| env | default | meaning | +|---|---|---| +| `ARENA_BIND` | `127.0.0.1:8080` | listen address | +| `ARENA_DB` | `arena.db` | SQLite file (`:memory:` ok) | +| `ARENA_ADMIN_TOKEN` | random, logged | admin bearer token | +| `ARENA_BLUEPRINT` | unset | compact blueprint `.plcp`; enables house bot `house:sharingan-1` | +| `ARENA_BUCKETS` / `ARENA_SIZING` | `coarse` / `medium` | abstraction of that blueprint, e.g. `tables:data/buckets-200` | +| `ARENA_OPEN_REGISTRATION` | `true` | anyone may register a bot | +| `ARENA_ENABLE_WEBHOOKS` | `false` | allow bots with a `webhook_url` (the server then makes outbound requests) | +| `ARENA_HAND_DELAY_MS` | `300` | pause between hands on free tables | +| `ARENA_RECONNECT_GRACE_MS` | `2000` | how long a turn waits for a seat whose socket is gone | +| `ARENA_LEADERBOARD_MIN_HANDS` | `1000` | leaderboard threshold | +| `ARENA_RANKED_MIN_HANDS` | `0` (any) | a verified run sets a bot's track score only with at least this many hands (production: 20004) | +| `ARENA_SAVE_FREE_HANDS` | `true` | store histories of non-match tables | +| `ARENA_DATABASE_URL` | unset | `postgres://...` selects Postgres (TLS via rustls unless `sslmode=disable`); `ARENA_DB` is then ignored | +| `ARENA_DATABASE_SCHEMA` / `ARENA_DB_POOL` | unset / `8` | Postgres schema for all tables; connections | +| `ARENA_RUNNER_TOKEN` | unset | bearer token of the trusted eval runner: may start/attest hosted (verified) benchmark runs (TABLE_API.md 12b item 16) | +| `ARENA_WORKER_KEYS` | unset | `id=secret,id2=secret2` HMAC keys of match workers; `POST /v1/results` (runner/admin only) accepts a worker result signed with one of them as `verified` + `hosted` (TABLE_API.md 14.6) | +| `ARENA_RATE_LIMIT_RPS` / `ARENA_RATE_LIMIT_BURST` | `50` / `100` | per-token (anonymous: per-IP) request bucket; `0` = off. `ARENA_TRUST_PROXY=true` keys anonymous requests by `X-Forwarded-For` | +| `ARENA_MAX_TABLES_PER_PLAYER` | `10` | open free tables a player owns or sits at | +| `ARENA_MAX_MATCHES_PER_PLAYER` | `4` | unfinished matches/benchmark runs per player | +| `ARENA_MAX_WS_PER_PLAYER` | `4` | simultaneous `/v1/play` sockets per player | +| `ARENA_MAX_RUN_HANDS` / `ARENA_MAX_MATCH_HANDS` | `100000` / `1000000` | hands per benchmark run (players) / per match | +| `ARENA_MAX_BODY_BYTES` / `ARENA_MAX_WS_MESSAGE_BYTES` | `262144` / `65536` | request body / one client WebSocket message | +| `ARENA_SHUTDOWN_GRACE_MS` | `20000` | SIGTERM drain: how long running matches may finish before they are aborted | + +Probes for a load balancer: `GET /healthz` (liveness), `GET /readyz` (200 only if the database answers and the server is not draining). +`SIGTERM`/`SIGINT` drains gracefully (see TABLE_API.md 12b item 18). + +## Tests on both backends + +```bash +cargo test -p sharingan-arena # SQLite (in-memory) +ARENA_TEST_DATABASE_URL=postgres://user@host:5432/db cargo test -p sharingan-arena # same suite on Postgres, one fresh schema per test server +``` +Test schemas (`t_*`, `s_*`) are left behind; use a throwaway database. + +## curl tour + +```bash +H=http://127.0.0.1:8080; ADMIN=... # admin token from the log + +# 1. register a bot (token shown once; only its sha256 is stored) +curl -s $H/v1/bots -d '{"name":"mybot","kind":"bot"}' -H 'content-type: application/json' + +# 2. a table with you and five house bots, then connect ws://127.0.0.1:8080/v1/play?token=$TOKEN +curl -s $H/v1/tables -H "authorization: Bearer $TOKEN" -H 'content-type: application/json' -d '{"decision_time_ms":3000}' +curl -s -X POST $H/v1/tables/$T/seats/0 -H "authorization: Bearer $TOKEN" -d '{}' -H 'content-type: application/json' +curl -s -X POST $H/v1/tables/$T/fill -H "authorization: Bearer $TOKEN" -d '{"bot":"house:tight_aggressive"}' -H 'content-type: application/json' + +# 3. a duplicate match against the ladder (random, calling_station, 2x tight_aggressive, sharingan-1) +curl -s $H/v1/matches -H "authorization: Bearer $TOKEN" -H 'content-type: application/json' \ + -d '{"participants":["'$BOT_ID'"],"field":"ladder","hands_planned":600,"duplicate":true,"seed":"my-seed"}' +curl -s -X POST $H/v1/matches/$M/start -H "authorization: Bearer $TOKEN" +curl -s $H/v1/matches/$M # status + standings (mbb_per_game, ci95_mbb, ...) +curl -s $H/v1/matches/$M/hands.jsonl -H "authorization: Bearer $TOKEN" +curl -s "$H/v1/leaderboard?min_hands=1000" +``` + +## Benchmark tracks and throughput + +```bash +curl -s $H/v1/benchmarks # ladder-v1, sharingan-1 (need ARENA_BLUEPRINT) +curl -s -X POST $H/v1/benchmarks/ladder-v1/runs -H "authorization: Bearer $TOKEN" \ + -H 'content-type: application/json' -d '{"lanes":4}' # your bot, 20,000 hands by default (connect to /v1/play first) +curl -s $H/v1/benchmarks/ladder-v1/runs/$RUN # progress + running estimate; also a WS benchmark_progress event +curl -s "$H/v1/leaderboard?track=ladder-v1" # vs_ladder_v1, vs_sharingan_1, verified per bot +python3 arena/server/scripts/throughput.py --mode benchmark --lanes 4 --hands 6000 # hands/s with the python SDK +``` + +Fast path: `"mode":"benchmark"` (tables and matches), `"lanes":N` for parallel blocks of a duplicate match, hand histories written in +batches by a background thread, TCP_NODELAY on all sockets. See TABLE_API.md 12b items 11-15. + +## Match worker: high-throughput evals (`sharingan-arena run`) + +Headless, no server, no database: plays the duplicate benchmark of a track against a bot that runs as a **subprocess** speaking newline-delimited JSON on +stdin/stdout (the "pipe protocol", TABLE_API.md section 14). Same frozen panels, seeds, deals and AIVAT as the server's benchmark runs, one bot process per lane. + +```bash +export ARENA_BLUEPRINT=... ARENA_BUCKETS=... ARENA_SIZING=... # as for the server (both tracks need SHARINGAN-1) +sharingan-arena run --bot "sharingan pipe mybot.py" --track ladder-v1 --hands 20000 --lanes 8 \ + --out result.json --sign-key-file worker.key --player-id p_abc # signed result +sharingan-arena run --bot "sharingan-arena pipe-house tight_aggressive" --lanes 16 --out r.json # Rust reference bot +# control plane: accept it (ARENA_WORKER_KEYS=id=secret on the server, runner token) +curl -s $H/v1/results -H "authorization: Bearer $RUNNER" -H 'content-type: application/json' -d @result.json +``` +`--seed-file F` reads a secret per-run seed (`run:`, fresh deals) instead of the public track seed; the bot never sees it (TABLE_API.md 14.4). `POST /v1/results` accepts the track seed (`deals: "frozen"`) or such a seed (`deals: "fresh"`). +Timeouts kill and fold, crashes forfeit the lane's remaining hands (TABLE_API.md 14.3). Measured: 4.6k hands/s for a trivial Python bot on 8 lanes, 11-17k hands/s for a Rust bot on 16 lanes. +Code: `src/worker.rs` (schedule, lanes, pipes, signing), `src/pipe_bot.rs` (reference Rust pipe bot), `src/results.rs` (intake); tests in `tests/worker.rs`. + +## What is where + +- `src/hand.rs`: one hand on top of `nlhe::State` (seat mapping, payloads, side-pot results, history). No I/O. +- `src/table.rs`: per-table task, decision loop, timeouts, reconnect, house bots, webhook seats. +- `src/matches.rs`: duplicate schedule, AIVAT replay (bench `Tracker` over stored hands), finalize. +- `src/benchmarks.rs`: tracks, runs, verified flag. `src/worker.rs`, `src/pipe_bot.rs`, `src/results.rs`: match worker (above). `src/writer.rs`: batched hand writer. +- `src/stats.rs`: standings (deal as the sample) and leaderboard (inverse-variance combine). +- `src/api.rs`, `src/ws.rs`: REST and WebSocket. `src/deck.rs`: HMAC-SHA256 + ChaCha20 Fisher-Yates dealing. + +## Behaviour worth knowing + +- Fold when check is free becomes a check. Illegal actions get an `error` and the same `your_turn` (same `decision_id`) again until the deadline. +- `deadline_ms` includes the player's remaining time bank. A seat with no live socket at the start of its turn gets only the reconnect grace. +- Free tables deal when `min_players_to_deal` seats are filled and connected (or house) and at least one is not a house bot. +- Match ownership: creating a match requires every non-house participant to be the caller's own bot (admins: any); `start`/`resume` return `409 not_connected` while a non-house participant is offline (admins exempt). All errors, including framework rejections and unknown routes, are the JSON envelope; player names reject control, invisible and bidi-override characters. +- Matches: `stack_mode` is forced to `reset`, duplicate needs `hands_planned % 6 == 0`. Deals are played in blocks of `block_deals` (12) rotation-major so a deal's rotations are far apart. Hand histories of a running match are readable only by its owner/admin. `"reveal":"match_end"` also withholds other players' cards in `hand_end` until the match ends (default follows the spec and reveals). +- Scores: AIVAT (bench `EquityEstimator` baseline; house bots that expose probabilities also get decision corrections) when `aivat` is `full`/`cards`, else plain duplicate. There is no learned blueprint value function yet. Leaderboard combines matches by inverse variance, so a score depends on the field faced. +- Sandbox tables (`"mode":"sandbox"`) take `sandbox.decks` (card prefixes per hand), `button_seat`, `stacks`. + +## Tests + +`cargo test -p sharingan-arena` runs the section 12 conformance vectors and the end-to-end paths in `tests/conformance.rs` against an in-process server. + +## Known gaps + +No webhook test and no `/events` callbacks to webhook bots; `hello{resume}` always sends a fresh snapshot (no replay); tables are in memory (matches and hands persist, running matches are aborted on restart); no spectator stream; in-memory per-hand records for running matches. diff --git a/arena/server/migrations/0001_init.sql b/arena/server/migrations/0001_init.sql new file mode 100644 index 00000000..ae777312 --- /dev/null +++ b/arena/server/migrations/0001_init.sql @@ -0,0 +1,25 @@ +-- Arena storage, Postgres. Values that are not queried are stored as JSON text (same layout as the SQLite store). +CREATE TABLE players( + player_id TEXT PRIMARY KEY, name TEXT NOT NULL, kind TEXT NOT NULL, owner TEXT, + house BOOLEAN NOT NULL DEFAULT FALSE, token_hash TEXT NOT NULL DEFAULT '', + webhook_url TEXT, webhook_secret TEXT, created_at TEXT NOT NULL, created_seq BIGSERIAL +); +CREATE INDEX players_token ON players(token_hash); +CREATE TABLE matches( + match_id TEXT PRIMARY KEY, status TEXT NOT NULL, body TEXT NOT NULL, created_seq BIGSERIAL +); +CREATE INDEX matches_status ON matches(status); +CREATE TABLE hands( + hand_id TEXT PRIMARY KEY, match_id TEXT, hand_no BIGINT NOT NULL, body TEXT NOT NULL, events TEXT NOT NULL +); +CREATE INDEX hands_match ON hands(match_id, hand_no); +CREATE TABLE match_results( + match_id TEXT NOT NULL, player_id TEXT NOT NULL, hands BIGINT NOT NULL, deals BIGINT NOT NULL, + net_chips BIGINT NOT NULL, score_mbb DOUBLE PRECISION NOT NULL, se_mbb DOUBLE PRECISION NOT NULL, method TEXT NOT NULL, + PRIMARY KEY(match_id, player_id) +); +CREATE INDEX results_player ON match_results(player_id); +CREATE TABLE benchmark_runs( + run_id TEXT PRIMARY KEY, track TEXT NOT NULL, player_id TEXT NOT NULL, body TEXT NOT NULL, created_seq BIGSERIAL +); +CREATE INDEX runs_track ON benchmark_runs(track, player_id); diff --git a/arena/server/scripts/house_run.py b/arena/server/scripts/house_run.py new file mode 100644 index 00000000..e2804f20 --- /dev/null +++ b/arena/server/scripts/house_run.py @@ -0,0 +1,30 @@ +"""Run a benchmark-track run for a house bot (server-hosted, verified) and print progress + throughput. + python3 house_run.py http://127.0.0.1:8080 ADMIN_TOKEN ladder-v1 house:tight_aggressive [hands]""" +import json, sys, time, urllib.request + +base, admin, track, bot = sys.argv[1:5] +hands = int(sys.argv[5]) if len(sys.argv) > 5 else None + + +def call(method, path, body=None): + req = urllib.request.Request(base + path, data=json.dumps(body).encode() if body is not None else None, method=method, + headers={"authorization": f"Bearer {admin}", "content-type": "application/json"}) + with urllib.request.urlopen(req) as r: + return json.loads(r.read()) + + +t0 = time.time() +run = call("POST", f"/v1/benchmarks/{track}/runs", {"player_id": bot, **({"hands": hands} if hands else {})}) +print("started", run["run_id"], "planned", run["hands_planned"], "verified", run["verified"]) +last = 0 +while True: + r = call("GET", f"/v1/benchmarks/{track}/runs/{run['run_id']}") + if time.time() - last > 2 or r["status"] != "running": + print(f" {r['status']} {r['hands_done']}/{r['hands_total']} running={r.get('running_mbb_per_game')} +-{r.get('running_ci95_mbb')}") + last = time.time() + if r["status"] != "running": + break + time.sleep(0.2) +dt = time.time() - t0 +print(f"{r['hands_done']} hands in {dt:.1f}s = {r['hands_done']/dt:.0f} hands/s; score {r['mbb_per_game']:+.1f} +- {r['ci95_mbb']:.1f} mbb/game ({r['method']}) verified={r['verified']}") +print(json.dumps(call("GET", "/v1/leaderboard?track=" + track))["rows"][:1] if False else "") diff --git a/arena/server/scripts/throughput.py b/arena/server/scripts/throughput.py new file mode 100644 index 00000000..19f942ac --- /dev/null +++ b/arena/server/scripts/throughput.py @@ -0,0 +1,62 @@ +"""Throughput probe: one external WebSocket bot (python SDK) vs 5 house bots in a duplicate match. + + PYTHONPATH=sdk/python: python3 arena/server/scripts/throughput.py \ + --server http://127.0.0.1:8080 --hands 3000 --mode benchmark --lanes 1 + +Prints hands/s measured from match start to `finished` (includes the server-side AIVAT pass) +and from start to the last played hand (play only). +""" +import argparse, asyncio, time + +from sharingan.bot import Bot +from sharingan.client import ArenaClient, Runner +from sharingan.models import Action + + +class Caller(Bot): + name = "caller" + + def act(self, state): + return Action.check() if state.legal.check else Action.call() + + +async def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--server", default="http://127.0.0.1:8080") + ap.add_argument("--hands", type=int, default=3000) + ap.add_argument("--mode", default="normal") + ap.add_argument("--lanes", type=int, default=1) + ap.add_argument("--vs", default="tight_aggressive") + ap.add_argument("--aivat", default="full") + a = ap.parse_args() + api = ArenaClient(a.server) + me = api.register_bot("tp-caller") + runner = Runner(Caller(), a.server, me.token) + rt = asyncio.ensure_future(runner.run()) + await asyncio.sleep(0.5) + cfg = {"decision_time_ms": 5000, "mode": a.mode} + body = dict(table_config=cfg, participants=[me.player_id] + [f"house:{a.vs}"] * 5, hands_planned=a.hands, + duplicate={"enabled": True, "rotations": 6, "deck_from": "seed"}, seed="tp") + body["aivat"] = a.aivat + if a.lanes > 1: + body["lanes"] = a.lanes + m = api.request("POST", "/v1/matches", body) + api.match_action(m["match_id"], "start") + t0 = time.time() + t_play = None + while True: + cur = api.get_match(m["match_id"]) + if t_play is None and cur["hands_played"] >= a.hands: + t_play = time.time() - t0 + if cur["status"] in ("finished", "aborted"): + break + await asyncio.sleep(0.1) + t1 = time.time() - t0 + runner.stop() + await asyncio.gather(rt, return_exceptions=True) + tp = t_play or t1 + print(f"mode={a.mode} lanes={a.lanes} vs={a.vs} hands={a.hands}: play {tp:.2f}s = {a.hands / tp:.1f} hands/s; " + f"total incl. finalize {t1:.2f}s = {a.hands / t1:.1f} hands/s; status={cur['status']}") + + +asyncio.run(main()) diff --git a/arena/server/src/api.rs b/arena/server/src/api.rs new file mode 100644 index 00000000..63fb4b67 --- /dev/null +++ b/arena/server/src/api.rs @@ -0,0 +1,968 @@ +//! REST surface (TABLE_API.md section 3). + +use crate::error::{ApiError, Res}; +use crate::house::{house_id, HouseRegistry}; +use crate::matches::{self, MatchRuntime, NewMatch}; +use crate::model::*; +use crate::state::{AppState, Principal}; +use crate::stats::leaderboard; +use crate::table::{spawn_table, SeatState}; +use crate::util::*; +use axum::body::{Body, Bytes}; +use axum::extract::{Path, Query, State}; +use axum::http::{HeaderMap, StatusCode}; +use axum::response::{IntoResponse, Response}; +use axum::routing::{get, post}; +use axum::{Json, Router}; +use serde::Deserialize; +use serde_json::{json, Value}; +use std::collections::HashMap; +use std::convert::Infallible; +use std::sync::Arc; + +type App = State>; + +pub fn router(app: Arc) -> Router { + Router::new() + .route("/healthz", get(|| async { "ok" })) + .route("/livez", get(|| async { "ok" })) + .route("/readyz", get(readyz)) + .route("/v1/runner/hosted", post(runner_hosted)) + .route("/v1/results", post(crate::results::post_result)) + .route("/v1/bots", post(register).get(list_players)) + .route("/v1/players", post(register).get(list_players)) + .route("/v1/me", get(whoami)) + .route("/v1/bots/{id}", get(get_player).delete(delete_bot)) + .route("/v1/players/{id}", get(get_player)) + .route("/v1/house", get(list_house)) + .route("/v1/tables", post(create_table).get(list_tables)) + .route("/v1/tables/{id}", get(get_table).delete(close_table)) + .route("/v1/tables/{id}/seats/{seat}", post(sit).delete(stand)) + .route("/v1/tables/{id}/fill", post(fill)) + .route("/v1/matches", post(create_match).get(list_matches)) + .route("/v1/matches/{id}", get(get_match)) + .route("/v1/matches/{id}/start", post(start_match)) + .route("/v1/matches/{id}/resume", post(start_match)) + .route("/v1/matches/{id}/pause", post(pause_match)) + .route("/v1/matches/{id}/abort", post(abort_match)) + .route("/v1/matches/{id}/hands", get(match_hands)) + .route("/v1/matches/{id}/hands.jsonl", get(match_hands_jsonl)) + .route("/v1/hands/{id}", get(get_hand)) + .route("/v1/hands/{id}/events", get(get_hand_events)) + .route("/v1/leaderboard", get(get_leaderboard)) + .route("/v1/benchmarks", get(crate::benchmarks::list_tracks)) + .route("/v1/benchmarks/{track}", get(crate::benchmarks::get_track)) + .route("/v1/benchmarks/{track}/runs", post(crate::benchmarks::create_run).get(crate::benchmarks::list_runs)) + .route("/v1/benchmarks/{track}/runs/{run}", get(crate::benchmarks::get_run)) + .route("/v1/benchmarks/{track}/runs/{run}/abort", post(crate::benchmarks::abort_run)) + .route("/v1/play", get(crate::ws::play)) + .layer(axum::extract::DefaultBodyLimit::max(app.cfg.max_body_bytes)) + .layer(axum::middleware::from_fn_with_state(app.clone(), json_errors)) + .layer(axum::middleware::from_fn_with_state(app.clone(), rate_limit)) + .layer(axum::middleware::from_fn(cors)) + .with_state(app) +} + +/// Per-address (internal callers: per-token) token-bucket limiter; 429 `rate_limited` with `Retry-After`. +/// Health probes, CORS preflights and the admin/runner tokens are exempt. +async fn rate_limit(State(app): App, req: axum::extract::Request, next: axum::middleware::Next) -> Response { + let path = req.uri().path(); + if !app.limiter.enabled() || matches!(path, "/healthz" | "/livez" | "/readyz") || req.method() == axum::http::Method::OPTIONS { + return next.run(req).await; + } + let tok = crate::state::bearer(req.headers()); + if let Some(t) = &tok { + if ct_eq(t, &app.admin_token) || app.cfg.runner_token.as_deref().map(|r| ct_eq(t, r)).unwrap_or(false) { + return next.run(req).await; + } + } + // Public traffic (through our proxy) is limited per client address, whatever token it sends: a fresh random token + // must not buy a fresh bucket. Internal callers (no forwarded address, e.g. the inference server checking a token) + // per token. + let key = match (forwarded_ip(&app, req.headers()), &tok) { + (Some(ip), _) => format!("ip:{ip}"), + (None, Some(t)) => format!("t:{}", &sha256_hex(t.as_bytes())[..16]), + (None, None) => { + let ip = req.extensions().get::>().map(|c| addr_key(&c.0.ip().to_string())); + format!("ip:{}", ip.unwrap_or_default()) + } + }; + match app.limiter.check(&key) { + Ok(()) => next.run(req).await, + Err(ms) => ApiError::rate_limited( + "too many requests; slow down", + json!({"limit": "ARENA_RATE_LIMIT_RPS", "rps": app.cfg.rate_limit_rps, "burst": app.cfg.rate_limit_burst, "retry_after_ms": ms}), + ) + .into_response(), + } +} + +/// Rejections raised by axum itself (malformed JSON or query string, missing fields, wrong content type, +/// body limit, unknown route, wrong method) come back as plain text or an empty body. Give every non-JSON +/// 4xx the contract's error envelope (TABLE_API.md section 10) so clients can always parse `error.code`. +async fn json_errors(State(app): App, req: axum::extract::Request, next: axum::middleware::Next) -> Response { + let res = next.run(req).await; + let status = res.status(); + if !status.is_client_error() { + return res; + } + let is_json = res.headers().get(axum::http::header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).map(|v| v.starts_with("application/json")).unwrap_or(false); + if is_json { + return res; + } + if status == StatusCode::PAYLOAD_TOO_LARGE { + return ApiError::payload_too_large(app.cfg.max_body_bytes).into_response(); + } + let (parts, body) = res.into_parts(); + let text = match axum::body::to_bytes(body, 8 * 1024).await { + Ok(b) => String::from_utf8_lossy(&b).trim().to_string(), + Err(_) => String::new(), + }; + let (code, default_msg): (&'static str, &str) = match status { + StatusCode::NOT_FOUND => ("not_found", "no such route"), + StatusCode::METHOD_NOT_ALLOWED => ("method_not_allowed", "method not allowed for this route"), + StatusCode::UNSUPPORTED_MEDIA_TYPE => ("unsupported_media_type", "send the body as application/json"), + _ => ("bad_request", "bad request"), + }; + let msg = if text.is_empty() { default_msg.to_string() } else { text.chars().take(500).collect() }; + // a body that parses as JSON but misses fields or has the wrong types is a 400 like any other bad request + let http = if status == StatusCode::UNPROCESSABLE_ENTITY { 400 } else { status.as_u16() }; + let mut out = ApiError::new(http, code, msg).into_response(); + for h in [axum::http::header::ALLOW, axum::http::header::WWW_AUTHENTICATE, axum::http::header::RETRY_AFTER] { + if let Some(v) = parts.headers.get(&h) { + out.headers_mut().insert(h, v.clone()); + } + } + out +} + +/// Load-balancer readiness: 200 only when the database answers and the server is not draining. +async fn readyz(State(app): App) -> Response { + let a = app.clone(); + let db_ok = tokio::task::spawn_blocking(move || a.store.ping().is_ok()).await.unwrap_or(false); + let draining = app.is_draining(); + let running = app.matches.read().unwrap().values().filter(|m| m.state.lock().unwrap().rec.status == "running").count(); + let status = if draining { "draining" } else if !db_ok { "unavailable" } else { "ready" }; + let body = json!({"status": status, "db": if db_ok { "ok" } else { "error" }, "draining": draining, + "tables": app.tables.read().unwrap().len(), "matches_running": running, "ws_connections": app.hub.total()}); + ((if status == "ready" { StatusCode::OK } else { StatusCode::SERVICE_UNAVAILABLE }), Json(body)).into_response() +} + +#[derive(Deserialize)] +struct HostedReq { + player_id: String, + run_id: String, + #[serde(default = "yes")] + hosted: bool, +} +fn yes() -> bool { + true +} + +/// Runner-only: register (or revoke) a bot as `hosted` for one running benchmark run. Only a hosted +/// run is `verified`; the flag is stored with the run and shows on the leaderboard. +async fn runner_hosted(State(app): App, headers: HeaderMap, Json(req): Json) -> Res> { + match app.authenticate_any(&headers)? { + Principal::Runner => {} + _ => return Err(ApiError::forbidden("only the runner token (ARENA_RUNNER_TOKEN) can attest hosted bots")), + } + let mut run = app.store.get_run(&req.run_id)?.ok_or_else(|| ApiError::not_found("run"))?; + let pid = if HouseRegistry::looks_like_house(&req.player_id) { house_id(&app.house.resolve(&req.player_id)?) } else { req.player_id.clone() }; + if run.player_id != pid { + return Err(ApiError::bad_request("run_id does not belong to that player_id")); + } + if run.status != "running" { + return Err(ApiError::conflict("match_not_running", format!("run is {}; attest while it is running", run.status))); + } + let house = app.store.get_player(&pid)?.map(|p| p.house).unwrap_or(false); + run.hosted = req.hosted; + run.verified = req.hosted || house; + app.store.put_run(&run)?; + app.leaderboard_changed(); + Ok(Json(json!({"run_id": run.run_id, "player_id": run.player_id, "hosted": run.hosted, "verified": run.verified}))) +} + +async fn close_table(State(app): App, headers: HeaderMap, Path(id): Path) -> Res> { + let who = app.authenticate(&headers)?; + let t = app.table(&id)?; + let (owner, is_match) = { + let i = t.inner.lock().unwrap(); + (i.owner.clone(), i.match_id.is_some()) + }; + if !who.is_admin() && who.owner_id() != owner { + return Err(ApiError::forbidden("only the table owner or an admin can close a table")); + } + if is_match { + return Err(ApiError::conflict("table_locked", "match tables close with their match (abort the match)")); + } + let _ = t.tx.send(crate::table::TableCmd::Close); + t.wake.notify_one(); + t.inner.lock().unwrap().status = "closed".into(); + Ok(Json(t.table_json(&app.hub))) +} + +/// Minimal CORS so the static site (a different origin) can call the REST API from a browser. +/// Auth is a bearer token (no cookies), so `*` is safe. +async fn cors(req: axum::extract::Request, next: axum::middleware::Next) -> Response { + let preflight = req.method() == axum::http::Method::OPTIONS; + let mut res = if preflight { StatusCode::NO_CONTENT.into_response() } else { next.run(req).await }; + let h = res.headers_mut(); + h.insert("access-control-allow-origin", "*".parse().unwrap()); + h.insert("access-control-allow-methods", "GET, POST, DELETE, OPTIONS".parse().unwrap()); + h.insert("access-control-allow-headers", "authorization, content-type".parse().unwrap()); + h.insert("access-control-max-age", "86400".parse().unwrap()); + res +} + +fn public_player(p: &PlayerRecord) -> Value { + json!({"player_id": p.player_id, "bot_id": p.player_id, "name": p.name, "kind": p.kind, + "owner": p.owner, "created_at": p.created_at, "house": p.house, + "webhook": p.webhook_url.is_some()}) +} + +#[derive(Deserialize)] +struct RegisterReq { + name: String, + #[serde(default)] + kind: Option, + #[serde(default)] + owner: Option, + #[serde(default)] + webhook_url: Option, + #[serde(default)] + secret: Option, +} + +/// Longest player name, in characters (not bytes). +pub const MAX_NAME_CHARS: usize = 64; + +/// Lowercase with common look-alikes folded to Latin (Cyrillic, Greek, fullwidth), for the reserved-name check only. +fn latin_skeleton(s: &str) -> String { + s.chars() + .flat_map(|c| c.to_lowercase()) + .map(|c| match c { + 'а' | 'α' => 'a', 'в' | 'β' => 'b', 'с' | 'ϲ' => 'c', 'ԁ' => 'd', 'е' | 'ε' => 'e', 'һ' | 'н' | 'η' => 'h', + 'і' | 'ι' | 'ӏ' => 'i', 'ј' => 'j', 'к' | 'κ' => 'k', 'м' | 'μ' => 'm', 'ν' => 'v', 'о' | 'ο' => 'o', 'р' | 'ρ' => 'p', + 'ԛ' => 'q', 'ѕ' => 's', 'т' | 'τ' => 't', 'υ' => 'u', 'ԝ' => 'w', 'х' | 'χ' => 'x', 'у' => 'y', 'ζ' => 'z', + '\u{ff01}'..='\u{ff5e}' => char::from_u32(c as u32 - 0xfee0).unwrap_or(c), + o => o, + }) + .collect() +} + +/// Free text that is stored and shown to other users (player names, owners, seeds) must not carry control +/// characters (NUL, newlines, tabs, escapes), bidirectional overrides/isolates (U+202A-202E, U+2066-2069), zero-width and +/// invisible formatting characters (U+200B-200F, U+2028/2029, U+2060-2064, U+FEFF, U+061C). Accents, emoji and other ordinary Unicode are fine. +pub fn check_text(what: &str, s: &str) -> Res<()> { + let bad = |c: char| { + c.is_control() + || matches!(c as u32, 0x200B..=0x200F | 0x202A..=0x202E | 0x2066..=0x2069 | 0x2028 | 0x2029 | 0x2060..=0x2064 | 0xFEFF | 0x061C) + }; + if let Some(c) = s.chars().find(|&c| bad(c)) { + return Err(ApiError::bad_request(format!("{what} must not contain control, invisible or bidirectional-override characters (found U+{:04X})", c as u32))); + } + Ok(()) +} + +/// The caller's address: the first `X-Forwarded-For` hop behind our proxy (`ARENA_TRUST_PROXY`), else the socket peer. +fn client_ip(app: &AppState, headers: &HeaderMap, peer: Option) -> String { + forwarded_ip(app, headers).or_else(|| peer.map(|a| addr_key(&a.ip().to_string()))).unwrap_or_default() +} + +/// The client address our proxy forwarded (`X-Forwarded-For`, first hop), as a per-address key; `None` without a proxy. +fn forwarded_ip(app: &AppState, headers: &HeaderMap) -> Option { + if !app.cfg.trust_proxy { + return None; + } + headers.get("x-forwarded-for").and_then(|v| v.to_str().ok()).and_then(|v| v.split(',').next()).map(|s| addr_key(s.trim())).filter(|s| !s.is_empty()) +} + +/// One key per subscriber: an IPv4 address as is, an IPv6 address by its /64 (one host gets a whole /64 to rotate through). +pub fn addr_key(ip: &str) -> String { + match ip.parse::() { + Ok(std::net::IpAddr::V6(v6)) => match v6.to_ipv4_mapped() { + Some(v4) => v4.to_string(), + None => { + let s = v6.segments(); + format!("{:x}:{:x}:{:x}:{:x}::/64", s[0], s[1], s[2], s[3]) + } + }, + Ok(a) => a.to_string(), + Err(_) => ip.to_string(), + } +} + +async fn register( + State(app): App, + headers: HeaderMap, + peer: Option>>, + Json(req): Json, +) -> Res<(StatusCode, Json)> { + if !app.cfg.open_registration { + let p = app.authenticate(&headers)?; + if !p.is_admin() { + return Err(ApiError::forbidden("registration is closed")); + } + } + let name = req.name.trim().to_string(); + if name.is_empty() || name.chars().count() > MAX_NAME_CHARS { + return Err(ApiError::bad_request(format!("name must be 1..{MAX_NAME_CHARS} characters"))); + } + check_text("name", &name)?; + if let Some(o) = &req.owner { + if o.chars().count() > 128 { + return Err(ApiError::bad_request("owner must be at most 128 characters")); + } + check_text("owner", o)?; + } + for (what, v) in [("webhook_url", &req.webhook_url), ("secret", &req.secret)] { + if v.as_deref().map(|x| x.contains('\0')).unwrap_or(false) { + return Err(ApiError::bad_request(format!("{what} must not contain NUL bytes"))); + } + } + let kind = req.kind.unwrap_or_else(|| "bot".into()); + if kind != "bot" && kind != "human" { + return Err(ApiError::bad_request("kind must be bot or human")); + } + if name.starts_with("house:") { + return Err(ApiError::bad_request("the house: prefix is reserved")); + } + // Nobody may pose as SHARINGAN-1 (or a later SHARINGAN) or as a reference bot, under any kind, also not with look-alike + // letters ("Rаndom" with a Cyrillic а). House bots are created internally. + let lower = latin_skeleton(&name); + if lower.starts_with("sharingan") || HouseRegistry::looks_like_house(&lower) || app.house.key_of(&lower).is_some() { + return Err(ApiError::bad_request(format!("the name {name} is reserved for a reference bot; pick another (the bot is named after its file)"))); + } + let admin = crate::state::bearer(&headers).map(|t| ct_eq(&t, &app.admin_token)).unwrap_or(false); + { + if !admin && app.cfg.bots_per_ip_per_day > 0.0 { + let ip = client_ip(&app, &headers, peer.map(|c| (c.0).0)); + let limiter = if kind == "bot" { &app.reg_limiter } else { &app.human_reg_limiter }; + if let Err(ms) = limiter.check(&format!("reg:{ip}")) { + return Err(ApiError::rate_limited( + "too many new bots from this address today; reuse a bot you have (its token is in ~/.config/sharingan/tokens.json)", + json!({"limit": "ARENA_BOTS_PER_IP_PER_DAY", "per_day": app.cfg.bots_per_ip_per_day, "retry_after_ms": ms}), + )); + } + } + } + if req.webhook_url.is_some() { + if !app.cfg.enable_webhooks { + return Err(ApiError::bad_request("webhook mode is disabled on this server (ARENA_ENABLE_WEBHOOKS)")); + } + if req.secret.as_deref().unwrap_or("").is_empty() { + return Err(ApiError::bad_request("webhook_url requires a secret")); + } + } + let token = format!("sk_{}", random_hex()); + let rec = PlayerRecord { + player_id: new_id("p"), + name, + kind, + owner: req.owner, + created_at: now_iso(), + house: false, + token_hash: sha256_hex(token.as_bytes()), + webhook_url: req.webhook_url, + webhook_secret: req.secret, + }; + app.store.put_player(&rec)?; + let mut v = public_player(&rec); + v["token"] = json!(token); + v["api_key"] = json!(token); + Ok((StatusCode::CREATED, Json(v))) +} + +async fn list_players(State(app): App) -> Res> { + let v: Vec = app.store.list_players(500)?.iter().map(public_player).collect(); + Ok(Json(json!(v))) +} + +/// Who does this bearer token belong to? Used by the hosted runner to authenticate public users with their bot token. +async fn whoami(State(app): App, headers: HeaderMap) -> Res> { + match app.authenticate(&headers)? { + Principal::Player(p) => Ok(Json(public_player(&p))), + _ => Ok(Json(json!({"player_id": "admin", "name": "admin", "admin": true}))), + } +} + +async fn get_player(State(app): App, Path(id): Path) -> Res> { + let id = if HouseRegistry::looks_like_house(&id) { house_id(&app.house.resolve(&id)?) } else { id }; + let p = app.store.get_player(&id)?.ok_or_else(|| ApiError::not_found("player"))?; + let rs = app.store.results_of_player(&id)?; + let mut v = public_player(&p); + let hands: u64 = rs.iter().map(|r| r.hands).sum(); + let lb = leaderboard(&rs, &HashMap::from([(id.clone(), p.clone())]), &[], 0, 0, true, None); + v["stats"] = json!({"matches": rs.len(), "hands": hands, + "mbb_per_game": lb.first().and_then(|r| r.score_mbb_per_hand), + "ci95_mbb": lb.first().and_then(|r| r.ci95_mbb_per_hand)}); + Ok(Json(v)) +} + +async fn list_house(State(app): App) -> Json { + Json(json!(app.house.bots.keys().map(|k| json!({"player_id": house_id(k), "name": k})).collect::>())) +} + +// ---- tables ---- + +async fn create_table(State(app): App, headers: HeaderMap, Json(cfg): Json) -> Res<(StatusCode, Json)> { + app.ensure_accepting()?; + let who = app.authenticate(&headers)?; + cfg.validate()?; + if !who.is_admin() { + let n = app.open_tables_of(&who.owner_id()); + if n >= app.cfg.max_tables_per_player { + return Err(ApiError::rate_limited( + format!("you already have {n} open tables (limit {}); close one with DELETE /v1/tables/{{id}}", app.cfg.max_tables_per_player), + json!({"limit": "ARENA_MAX_TABLES_PER_PLAYER", "max": app.cfg.max_tables_per_player}), + )); + } + } + let id = new_id("t"); + let t = spawn_table(&app, id, who.owner_id(), cfg, None, 0); + Ok((StatusCode::CREATED, Json(t.table_json(&app.hub)))) +} + +async fn list_tables(State(app): App) -> Json { + let mut v: Vec<(String, Value)> = app + .tables + .read() + .unwrap() + .values() + .map(|t| { + let mut j = t.table_json(&app.hub); + j["hand"] = Value::Null; + (j["created_at"].as_str().unwrap_or("").to_string(), j) + }) + .collect(); + v.sort_by(|a, b| a.0.cmp(&b.0)); + Json(json!(v.into_iter().map(|x| x.1).collect::>())) +} + +async fn get_table(State(app): App, Path(id): Path) -> Res> { + Ok(Json(app.table(&id)?.table_json(&app.hub))) +} + +#[derive(Deserialize)] +struct SitReq { + #[serde(default)] + player_id: Option, + #[serde(default)] + house: Option, +} + +fn seat_player(app: &AppState, who: &Principal, owner: &str, req: &SitReq) -> Res { + let id = match (&req.house, &req.player_id) { + (Some(h), _) => house_id(&app.house.resolve(h)?), + (None, Some(p)) if HouseRegistry::looks_like_house(p) => house_id(&app.house.resolve(p)?), + (None, Some(p)) => p.clone(), + (None, None) => match who { + Principal::Player(p) => p.player_id.clone(), + Principal::Admin | Principal::Runner => return Err(ApiError::bad_request("player_id required")), + }, + }; + let rec = app.store.get_player(&id)?.ok_or_else(|| ApiError::not_found("player"))?; + let allowed = who.is_admin() + || (rec.house && who.owner_id() == owner) + || matches!(who, Principal::Player(p) if p.player_id == rec.player_id); + if !allowed { + return Err(ApiError::forbidden("only an admin or the player itself can seat a player (the table owner can seat house bots)")); + } + Ok(rec) +} + +fn do_sit(app: &AppState, t: &crate::table::TableShared, seat: usize, rec: &PlayerRecord) -> Res { + { + let mut inner = t.inner.lock().unwrap(); + if inner.match_id.is_some() { + return Err(ApiError::conflict("table_locked", "match tables are seated by the match")); + } + if seat >= inner.seats.len() { + return Err(ApiError::bad_request(format!("seat must be 0..{}", inner.seats.len() - 1))); + } + if inner.seats[seat].player_id.is_some() { + return Err(ApiError::conflict("seat_taken", "seat is taken")); + } + if !rec.house && inner.seats.iter().any(|s| s.player_id.as_deref() == Some(&rec.player_id)) { + return Err(ApiError::conflict("seat_taken", "player already has a seat at this table")); + } + let stack = inner.config.starting_stack; + inner.seats[seat] = SeatState { + player_id: Some(rec.player_id.clone()), + name: Some(rec.name.clone()), + kind: rec.kind.clone(), + house: rec.house, + stack, + stand_up: false, + }; + } + t.emit_seat_update(&app.hub, seat); + t.wake.notify_one(); + let inner = t.inner.lock().unwrap(); + Ok(crate::table::TableShared::seat_json(&inner, seat, &app.hub)) +} + +async fn sit(State(app): App, headers: HeaderMap, Path((id, seat)): Path<(String, usize)>, Json(req): Json) -> Res> { + let who = app.authenticate(&headers)?; + let t = app.table(&id)?; + let owner = t.inner.lock().unwrap().owner.clone(); + app.ensure_accepting()?; + let rec = seat_player(&app, &who, &owner, &req)?; + if !rec.house && !who.is_admin() { + let n = app.open_tables_of(&rec.player_id); + if n >= app.cfg.max_tables_per_player { + return Err(ApiError::rate_limited( + format!("{} is already at or owns {n} open tables (limit {})", rec.player_id, app.cfg.max_tables_per_player), + json!({"limit": "ARENA_MAX_TABLES_PER_PLAYER", "max": app.cfg.max_tables_per_player}), + )); + } + } + Ok(Json(do_sit(&app, &t, seat, &rec)?)) +} + +async fn stand(State(app): App, headers: HeaderMap, Path((id, seat)): Path<(String, usize)>) -> Res> { + let who = app.authenticate(&headers)?; + let t = app.table(&id)?; + { + let mut inner = t.inner.lock().unwrap(); + if inner.match_id.is_some() { + return Err(ApiError::conflict("table_locked", "match tables are seated by the match")); + } + let s = inner.seats.get(seat).ok_or_else(|| ApiError::bad_request("bad seat"))?.clone(); + let Some(pid) = s.player_id else { return Err(ApiError::conflict("not_seated", "seat is empty")) }; + let ok = who.is_admin() || inner.owner == who.owner_id() || pid == who.owner_id(); + if !ok { + return Err(ApiError::forbidden("not allowed to stand this seat up")); + } + if inner.in_hand { + inner.seats[seat].stand_up = true; // takes effect after the current hand + } else { + inner.seats[seat] = SeatState::empty(); + } + } + t.emit_seat_update(&app.hub, seat); + let inner = t.inner.lock().unwrap(); + Ok(Json(crate::table::TableShared::seat_json(&inner, seat, &app.hub))) +} + +#[derive(Deserialize)] +struct FillReq { + bot: String, +} + +/// Fill the empty seats with a house bot, or with the `ladder` line-up. +async fn fill(State(app): App, headers: HeaderMap, Path(id): Path, Json(req): Json) -> Res> { + let who = app.authenticate(&headers)?; + let t = app.table(&id)?; + let owner = t.inner.lock().unwrap().owner.clone(); + if !who.is_admin() && who.owner_id() != owner { + return Err(ApiError::forbidden("only the table owner can fill seats")); + } + let ids: Vec = if req.bot == "ladder" { app.house.ladder()? } else { vec![house_id(&app.house.resolve(&req.bot)?)] }; + let empty: Vec = { + let inner = t.inner.lock().unwrap(); + (0..inner.seats.len()).filter(|&i| inner.seats[i].player_id.is_none()).collect() + }; + for (k, seat) in empty.into_iter().enumerate() { + if req.bot == "ladder" && k >= ids.len() { + break; + } + let pid = if req.bot == "ladder" { &ids[k] } else { &ids[0] }; + let rec = app.store.get_player(pid)?.ok_or_else(|| ApiError::not_found("house player"))?; + do_sit(&app, &t, seat, &rec)?; + } + Ok(Json(t.table_json(&app.hub))) +} + +// ---- matches ---- + +#[derive(Deserialize)] +struct MatchReq { + #[serde(default)] + table_config: Option, + #[serde(default)] + participants: Vec, + /// `"ladder"` appends random, calling_station, 2x tight_aggressive, sharingan-1 to `participants`. + #[serde(default)] + field: Option, + hands_planned: u32, + #[serde(default)] + duplicate: Option, + #[serde(default)] + seed: Option, + /// "full" (default) | "cards" | "off" + #[serde(default)] + aivat: Option, + #[serde(default)] + block_deals: Option, + /// "hand_end" (default, per spec) | "match_end": withhold other players' cards until the match ends + #[serde(default)] + reveal: Option, + /// Play disjoint blocks of deals on this many tables in parallel (duplicate matches; default 1). + #[serde(default)] + lanes: Option, +} + +/// Players may have a limited number of unfinished matches / benchmark runs at once (admin and runner: unlimited). +pub fn check_match_quota(app: &AppState, who: &Principal) -> Res<()> { + if matches!(who, Principal::Player(_)) { + let n = app.live_matches_of(&who.owner_id()); + if n >= app.cfg.max_matches_per_player { + return Err(ApiError::rate_limited( + format!("you already have {n} unfinished matches or runs (limit {})", app.cfg.max_matches_per_player), + json!({"limit": "ARENA_MAX_MATCHES_PER_PLAYER", "max": app.cfg.max_matches_per_player}), + )); + } + } + Ok(()) +} + +fn match_json(rt: &MatchRuntime, app: &AppState) -> Value { + let mut v = serde_json::to_value(rt.record()).unwrap(); + v["standings"] = serde_json::to_value(rt.standings()).unwrap(); + v["reveal"] = json!(if rt.hide_cards { "match_end" } else { "hand_end" }); + let _ = app; + v +} + +/// Shared by match creation/start and benchmark runs. +pub const YOUR_OWN_BOT: &str = "you can only run your own bot (admins can run any, including house bots)"; + +async fn create_match(State(app): App, headers: HeaderMap, Json(req): Json) -> Res<(StatusCode, Json)> { + app.ensure_accepting()?; + let who = app.authenticate(&headers)?; + check_match_quota(&app, &who)?; + let mut parts = req.participants.clone(); + match req.field.as_deref() { + None => {} + Some("ladder") => parts.extend(app.house.ladder()?), + Some(o) => return Err(ApiError::bad_request(format!("unknown field {o}"))), + } + if parts.len() != 6 { + return Err(ApiError::bad_request(format!("need exactly 6 participants, got {}", parts.len()))); + } + let mut ids = Vec::new(); + for p in &parts { + let id = if HouseRegistry::looks_like_house(p) { house_id(&app.house.resolve(p)?) } else { p.clone() }; + let rec = app.store.get_player(&id)?.ok_or_else(|| ApiError::not_found(&format!("participant {p}")))?; + // A match scores its participants on the leaderboard: nobody may enter someone else's bot. + if !rec.house && !who.is_admin() && rec.player_id != who.owner_id() { + return Err(ApiError::forbidden(YOUR_OWN_BOT).with(json!({"player_id": rec.player_id}))); + } + if !rec.house && ids.contains(&rec.player_id) { + return Err(ApiError::bad_request(format!("{} appears twice; only house bots can fill several seats", rec.player_id))); + } + ids.push(rec.player_id); + } + let mut cfg = req.table_config.unwrap_or_default(); + if cfg.stack_mode != StackMode::Reset { + return Err(ApiError::bad_request("matches require stack_mode=reset")); + } + cfg.max_seats = 6; + cfg.min_players_to_deal = 6; + cfg.validate()?; + let duplicate = match req.duplicate { + None | Some(Value::Null) | Some(Value::Bool(false)) => None, + Some(Value::Bool(true)) => Some(DuplicateConfig { enabled: true, rotations: 6, deck_from: "seed".into() }), + Some(v) => { + let d: DuplicateConfig = serde_json::from_value(v).map_err(|e| ApiError::bad_request(format!("duplicate: {e}")))?; + if d.rotations != 6 || d.deck_from != "seed" { + return Err(ApiError::bad_request("duplicate supports rotations=6, deck_from=seed")); + } + if d.enabled { Some(d) } else { None } + } + }; + if req.hands_planned == 0 || req.hands_planned > app.cfg.max_match_hands { + return Err(ApiError::bad_request(format!("hands_planned must be 1..{}", app.cfg.max_match_hands)) + .with(json!({"limit": "ARENA_MAX_MATCH_HANDS", "max": app.cfg.max_match_hands}))); + } + if duplicate.is_some() && req.hands_planned % 6 != 0 { + return Err(ApiError::bad_request("duplicate matches need hands_planned to be a multiple of 6 (one deal = 6 hands)")); + } + let aivat = req.aivat.unwrap_or_else(|| "full".into()); + if !["full", "cards", "off"].contains(&aivat.as_str()) { + return Err(ApiError::bad_request("aivat must be full, cards or off")); + } + let reveal = req.reveal.unwrap_or_else(|| "hand_end".into()); + if !["hand_end", "match_end"].contains(&reveal.as_str()) { + return Err(ApiError::bad_request("reveal must be hand_end or match_end")); + } + let rt = matches::create( + &app, + NewMatch { + owner: who.owner_id(), + cfg, + participants: ids, + hands: req.hands_planned, + duplicate, + seed: match req.seed { + Some(sd) => { + if sd.is_empty() || sd.chars().count() > 256 { + return Err(ApiError::bad_request("seed must be 1..256 characters")); + } + check_text("seed", &sd)?; + sd + } + None => random_hex()[..32].to_string(), + }, + aivat, + block_deals: req.block_deals.unwrap_or(12), + hide_cards: reveal == "match_end", + lanes: req.lanes.unwrap_or(1), + bench: None, + }, + )?; + Ok((StatusCode::CREATED, Json(match_json(&rt, &app)))) +} + +async fn list_matches(State(app): App) -> Res> { + let ids: Vec = app.store.list_matches(200)?; + let v: Vec = ids + .into_iter() + .map(|m| { + // live records win over stored ones + let live = app.matches.read().unwrap().get(&m.match_id).map(|r| r.record()); + serde_json::to_value(live.unwrap_or(m)).unwrap() + }) + .collect(); + Ok(Json(json!(v))) +} + +async fn get_match(State(app): App, Path(id): Path) -> Res> { + if let Ok(rt) = app.match_rt(&id) { + return Ok(Json(match_json(&rt, &app))); + } + let m = app.store.get_match(&id)?.ok_or_else(|| ApiError::not_found("match"))?; + let rows: Vec = app.store.all_results()?.into_iter().filter(|r| r.match_id == id).collect(); + let mut v = serde_json::to_value(m)?; + v["results"] = json!(rows); + Ok(Json(v)) +} + +fn controls(app: &AppState, who: &Principal, rt: &MatchRuntime) -> Res> { + let t = app.table(&rt.table_id)?; + let owner = t.inner.lock().unwrap().owner.clone(); + if !who.is_admin() && who.owner_id() != owner { + return Err(ApiError::forbidden("only the match owner or an admin can control it")); + } + Ok(t) +} + +/// Starting (or resuming) a match plays every non-house participant: it must be the caller's own bot, and it +/// must be connected (a missing bot would just auto-fold and its result would be recorded). Admins are exempt from both. +fn check_can_start(app: &AppState, who: &Principal, rt: &MatchRuntime) -> Res<()> { + if who.is_admin() { + return Ok(()); + } + let waiting = matches!(rt.record().status.as_str(), "scheduled" | "paused"); + for pid in &rt.participants { + let rec = app.store.get_player(pid)?.ok_or_else(|| ApiError::not_found(&format!("participant {pid}")))?; + if rec.house { + continue; + } + if rec.player_id != who.owner_id() { + return Err(ApiError::forbidden(YOUR_OWN_BOT).with(json!({"player_id": rec.player_id}))); + } + let reachable = app.hub.connected(&rec.player_id) || (app.cfg.enable_webhooks && rec.webhook_url.is_some()); + if waiting && !reachable { + return Err(ApiError::conflict("not_connected", "connect to /v1/play with your bot token before starting the match") + .with(json!({"player_id": rec.player_id}))); + } + } + Ok(()) +} + +async fn start_match(State(app): App, headers: HeaderMap, Path(id): Path) -> Res> { + let who = app.authenticate(&headers)?; + let rt = app.match_rt(&id)?; + controls(&app, &who, &rt)?; + check_can_start(&app, &who, &rt)?; + matches::start(&app, &rt)?; + Ok(Json(match_json(&rt, &app))) +} + +async fn pause_match(State(app): App, headers: HeaderMap, Path(id): Path) -> Res> { + let who = app.authenticate(&headers)?; + let rt = app.match_rt(&id)?; + controls(&app, &who, &rt)?; + { + let mut s = rt.state.lock().unwrap(); + if s.rec.status != "running" { + return Err(ApiError::conflict("match_not_running", format!("match is {}", s.rec.status))); + } + s.rec.status = "paused".into(); + app.store.put_match(&s.rec)?; + } + Ok(Json(match_json(&rt, &app))) +} + +async fn abort_match(State(app): App, headers: HeaderMap, Path(id): Path) -> Res> { + let who = app.authenticate(&headers)?; + let rt = app.match_rt(&id)?; + controls(&app, &who, &rt)?; + { + let mut s = rt.state.lock().unwrap(); + if s.rec.status == "finished" || s.rec.status == "aborted" { + return Err(ApiError::conflict("match_not_running", format!("match is {}", s.rec.status))); + } + s.abort = true; + s.rec.status = "aborted".into(); + app.store.put_match(&s.rec)?; + } + matches::wake_all(&app, &rt); + Ok(Json(match_json(&rt, &app))) +} + +// ---- hands ---- + +/// Hand histories carry every hole card. While a match is live only its owner and admins may read them, +/// otherwise a participant could look up a deal's other rotations. +fn can_read_match_hands(app: &AppState, who: &Principal, match_id: &str) -> Res<()> { + if who.is_admin() { + return Ok(()); + } + let m = app.match_rt(match_id).map(|r| r.record()).or_else(|_| { + app.store.get_match(match_id)?.ok_or_else(|| ApiError::not_found("match")) + })?; + if m.status == "finished" || m.status == "aborted" { + return Ok(()); + } + let owner = app.tables.read().unwrap().get(&m.table_id).map(|t| t.inner.lock().unwrap().owner.clone()); + if owner.as_deref() == Some(&who.owner_id()) { + return Ok(()); + } + Err(ApiError::forbidden("hand histories of a running match are only visible to its owner")) +} + +/// Page size of `GET /v1/matches/{id}/hands` (default and maximum). +const MAX_HANDS_PAGE: u32 = 500; + +#[derive(Deserialize)] +struct HandsQ { + #[serde(default)] + after_hand_no: u32, + #[serde(default)] + limit: Option, +} + +async fn match_hands(State(app): App, headers: HeaderMap, Path(id): Path, Query(q): Query) -> Res> { + let who = app.authenticate(&headers)?; + can_read_match_hands(&app, &who, &id)?; + app.writer.flush().await; + let limit = q.limit.unwrap_or(MAX_HANDS_PAGE); + if limit == 0 { + return Err(ApiError::bad_request(format!("limit must be 1..{MAX_HANDS_PAGE}"))); + } + let h = app.store.list_hands(&id, q.after_hand_no, limit.min(MAX_HANDS_PAGE))?; + Ok(Json(serde_json::to_value(h)?)) +} + +async fn match_hands_jsonl(State(app): App, headers: HeaderMap, Path(id): Path) -> Res { + let who = app.authenticate(&headers)?; + can_read_match_hands(&app, &who, &id)?; + app.writer.flush().await; + let stream = futures_util::stream::unfold((app, id, 0u32, false), |(app, id, after, done)| async move { + if done { + return None; + } + let page = app.store.list_hands(&id, after, 500).unwrap_or_default(); + if page.is_empty() { + return None; + } + let last = page.last().unwrap().hand_no; + let mut buf = String::new(); + for h in &page { + buf.push_str(&serde_json::to_string(h).unwrap_or_default()); + buf.push('\n'); + } + let short = page.len() < 500; + Some((Ok::(Bytes::from(buf)), (app, id, last, short))) + }); + Ok(([("content-type", "application/x-ndjson")], Body::from_stream(stream)).into_response()) +} + +async fn get_hand(State(app): App, headers: HeaderMap, Path(id): Path) -> Res> { + let who = app.authenticate(&headers)?; + app.writer.flush().await; + let h = app.store.get_hand(&id)?.ok_or_else(|| ApiError::not_found("hand"))?; + if let Some(m) = &h.match_id { + can_read_match_hands(&app, &who, m)?; + } + Ok(Json(serde_json::to_value(h)?)) +} + +async fn get_hand_events(State(app): App, headers: HeaderMap, Path(id): Path) -> Res> { + let who = app.authenticate(&headers)?; + app.writer.flush().await; + let h = app.store.get_hand(&id)?.ok_or_else(|| ApiError::not_found("hand"))?; + if let Some(m) = &h.match_id { + can_read_match_hands(&app, &who, m)?; + } + let ev = app.store.get_hand_events(&id)?.unwrap_or_default(); + Ok(Json(json!(ev))) +} + +#[derive(Deserialize)] +struct LbQ { + #[serde(default)] + min_hands: Option, + #[serde(default)] + include_house: Option, + /// Only bots with a run on this track, ranked by it (e.g. `ladder-v1`). + #[serde(default)] + track: Option, +} + +async fn get_leaderboard(State(app): App, Query(q): Query) -> Res> { + // Every page view of the site asks for this, and it reads every result and run: keep each answer for 2 s. + let ck = format!("{:?}|{:?}|{:?}", q.min_hands, q.include_house, q.track); + if let Some((at, v)) = app.lb_cache.lock().unwrap().get(&ck) { + if at.elapsed() < std::time::Duration::from_secs(2) { + return Ok(Json(v.clone())); + } + } + let v = leaderboard_json(&app, &q)?; + let mut c = app.lb_cache.lock().unwrap(); + if c.len() > 256 { + c.clear(); + } + c.insert(ck, (std::time::Instant::now(), v.clone())); + Ok(Json(v)) +} + +fn leaderboard_json(app: &AppState, q: &LbQ) -> Res { + let results = app.store.all_results()?; + let runs = app.store.list_runs(None, None, 100_000)?; + let players: HashMap = app.store.list_players(100_000)?.into_iter().map(|p| (p.player_id.clone(), p)).collect(); + let min = q.min_hands.unwrap_or(app.cfg.min_leaderboard_hands); + let ranked = app.cfg.ranked_min_hands; + let rows = leaderboard(&results, &players, &runs, min, ranked, q.include_house.unwrap_or(true), q.track.as_deref()); + Ok(json!({"min_hands": min, "ranked_min_hands": ranked, "track": q.track, "rows": rows})) +} + +/// Admin only: delete a (non-house) bot with its benchmark runs and every match it played in +/// (hands and results included). Refuses while one of those matches is still running. +async fn delete_bot(State(app): App, headers: HeaderMap, Path(id): Path) -> Res> { + let who = app.authenticate_any(&headers)?; + if !who.is_admin() { + return Err(ApiError::forbidden("admin token required")); + } + let p = app.store.get_player(&id)?.ok_or_else(|| ApiError::not_found("player"))?; + if p.house { + return Err(ApiError::forbidden("house bots cannot be deleted")); + } + let matches: Vec = app.store.list_matches(1_000_000)?.into_iter().filter(|m| m.participants.contains(&id)).collect(); + if let Some(m) = matches.iter().find(|m| m.status == "running" || m.status == "paused") { + return Err(ApiError::conflict("match_running", format!("match {} is still {}; abort it first", m.match_id, m.status))); + } + let runs = app.store.list_runs(None, Some(&id), 1_000_000)?; + for m in &matches { + app.store.delete_match_data(&m.match_id)?; + } + for r in &runs { + app.store.delete_run(&r.run_id)?; + } + app.store.delete_player(&id)?; + app.leaderboard_changed(); + Ok(Json(json!({"deleted": id, "name": p.name, "matches": matches.len(), "runs": runs.len()}))) +} diff --git a/arena/server/src/benchmarks.rs b/arena/server/src/benchmarks.rs new file mode 100644 index 00000000..d61f33ef --- /dev/null +++ b/arena/server/src/benchmarks.rs @@ -0,0 +1,252 @@ +//! Benchmark tracks: versioned, frozen opponent panels. A run is a duplicate match of one bot +//! against the track's panel with a fixed seed (every bot sees the same deals, so scores are paired). +//! +//! Verification: a run is `verified` only if the server itself ran the bot (house/hosted bots). +//! A remote bot's run is stored and ranked but flagged unverified, because the bot code runs +//! on the owner's machine and the seed is public. + +use crate::error::{ApiError, Res}; +use crate::house::house_id; +use crate::matches::{self, BenchLink, NewMatch}; +use crate::model::*; +use crate::state::AppState; +use crate::util::*; +use axum::extract::{Path, Query, State}; +use axum::http::{HeaderMap, StatusCode}; +use axum::Json; +use serde::Deserialize; +use serde_json::{json, Value}; +use std::sync::Arc; + +pub struct Track { + pub id: &'static str, + pub version: &'static str, + pub description: &'static str, + /// The five opponents, house bot names. + pub panel: &'static [&'static str], +} + +pub const TRACKS: &[Track] = &[ + Track { + id: "ladder-v1", + version: "1", + description: "Rule bots weak to strong, then SHARINGAN-1: random, calling_station, 2x tight_aggressive, sharingan-1.", + panel: &["random", "calling_station", "tight_aggressive", "tight_aggressive", "sharingan-1"], + }, + Track { + id: "sharingan-1", + version: "1", + description: "Five copies of SHARINGAN-1.", + panel: &["sharingan-1", "sharingan-1", "sharingan-1", "sharingan-1", "sharingan-1"], + }, +]; + +/// Server-side default size of a benchmark run (hands). +pub const DEFAULT_HANDS: u32 = 20_000; + +pub fn track(id: &str) -> Res<&'static Track> { + TRACKS.iter().find(|t| t.id == id).ok_or_else(|| ApiError::not_found("benchmark track")) +} + +fn track_json(app: &AppState, t: &Track) -> Value { + let available = app.house.bots.contains_key("sharingan-1"); + json!({"track": t.id, "version": t.version, "description": t.description, + "panel": t.panel.iter().map(|k| format!("house:{k}")).collect::>(), + "seed": seed_of(t), "default_hands": DEFAULT_HANDS, "available": available, + "blueprint_fingerprint": app.house.blueprint_fp}) +} + +pub fn seed_of(t: &Track) -> String { + format!("bench:{}:v{}", t.id, t.version) +} + +type App = State>; + +pub async fn list_tracks(State(app): App) -> Json { + Json(json!(TRACKS.iter().map(|t| track_json(&app, t)).collect::>())) +} + +pub async fn get_track(State(app): App, Path(id): Path) -> Res> { + let t = track(&id)?; + let mut v = track_json(&app, t); + let mut runs: Vec = app.store.list_runs(Some(t.id), None, 10_000)?.into_iter().filter(|r| r.status == "finished").collect(); + runs.sort_by(|a, b| b.mbb_per_game.partial_cmp(&a.mbb_per_game).unwrap_or(std::cmp::Ordering::Equal)); + v["top_runs"] = json!(runs.into_iter().take(50).collect::>()); + Ok(Json(v)) +} + +#[derive(Deserialize)] +pub struct RunReq { + #[serde(default)] + player_id: Option, + #[serde(default)] + hands: Option, + /// Parallel tables (default: 1 for remote bots, up to 8 for house bots). + #[serde(default)] + lanes: Option, + #[serde(default)] + decision_time_ms: Option, + /// Runner token only: the trusted runner is playing this bot on operator-controlled infrastructure, + /// so the run is `verified`. Anyone else sending `hosted: true` gets 403. + #[serde(default)] + hosted: Option, +} + +pub async fn create_run( + State(app): App, + headers: HeaderMap, + Path(tid): Path, + body: Option>, +) -> Res<(StatusCode, Json)> { + app.ensure_accepting()?; + let who = app.authenticate_any(&headers)?; + let t = track(&tid)?; + let req = body.map(|b| b.0).unwrap_or(RunReq { player_id: None, hands: None, lanes: None, decision_time_ms: None, hosted: None }); + let runner = matches!(who, crate::state::Principal::Runner); + if req.hosted == Some(true) && !runner { + return Err(ApiError::forbidden("only the runner token (ARENA_RUNNER_TOKEN) can start a hosted (verified) run")); + } + crate::api::check_match_quota(&app, &who)?; + if matches!(who, crate::state::Principal::Player(_)) && req.hands.map(|h| h > app.cfg.max_run_hands).unwrap_or(false) { + return Err(ApiError::bad_request(format!("hands exceeds the per-run limit of {}", app.cfg.max_run_hands)) + .with(json!({"limit": "ARENA_MAX_RUN_HANDS", "max": app.cfg.max_run_hands}))); + } + let pid = match (&req.player_id, &who) { + (Some(p), _) if crate::house::HouseRegistry::looks_like_house(p) => house_id(&app.house.resolve(p)?), + (Some(p), _) => p.clone(), + (None, crate::state::Principal::Player(p)) => p.player_id.clone(), + (None, _) => return Err(ApiError::bad_request("player_id required")), + }; + let rec = app.store.get_player(&pid)?.ok_or_else(|| ApiError::not_found("player"))?; + if !who.is_admin() && !runner && who.owner_id() != rec.player_id { + return Err(ApiError::forbidden(crate::api::YOUR_OWN_BOT)); + } + let mut panel = Vec::new(); + for k in t.panel { + panel.push(house_id(&app.house.resolve(k)?)); + } + if !rec.house && !app.hub.connected(&rec.player_id) { + return Err(ApiError::conflict("not_connected", "connect to /v1/play with your bot token before starting a run")); + } + let hosted = runner && req.hosted == Some(true); + let hands = req.hands.unwrap_or(DEFAULT_HANDS).clamp(6, 1_000_000); + let hands = (hands + 5) / 6 * 6; + let lanes = req.lanes.unwrap_or(if rec.house { std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4).min(8) } else { 1 }); + let run_id = new_id("r"); + let seed = seed_of(t); + let mut participants = vec![rec.player_id.clone()]; + participants.extend(panel.iter().cloned()); + let cfg = TableConfig { + mode: Some("benchmark".into()), + decision_time_ms: req.decision_time_ms.unwrap_or(5000), + min_players_to_deal: 6, + ..Default::default() + }; + cfg.validate()?; + let rt = matches::create( + &app, + NewMatch { + owner: who.owner_id(), + cfg, + participants, + hands, + duplicate: Some(DuplicateConfig { enabled: true, rotations: 6, deck_from: "seed".into() }), + seed: seed.clone(), + aivat: "full".into(), + block_deals: 12, + hide_cards: true, + lanes, + bench: Some(BenchLink { run_id: run_id.clone(), track: t.id.into(), player_id: rec.player_id.clone() }), + }, + )?; + let run = RunRecord { + run_id, + track: t.id.into(), + panel_version: t.version.into(), + panel: panel.clone(), + player_id: rec.player_id.clone(), + name: rec.name.clone(), + match_id: rt.id.clone(), + seed, + deals: None, + hands_planned: hands, + hands_done: 0, + status: "running".into(), + verified: rec.house || hosted, + hosted, + mbb_per_game: None, + ci95_mbb: None, + method: None, + blueprint_fingerprint: app.house.blueprint_fp.clone(), + created_at: now_iso(), + finished_at: None, + }; + app.store.put_run(&run)?; + app.leaderboard_changed(); + matches::start(&app, &rt)?; + Ok((StatusCode::CREATED, Json(run_json(&app, run)))) +} + +/// A run with live progress while it is playing: `hands_done`, `hands_total`, running estimate. +fn run_json(app: &AppState, run: RunRecord) -> Value { + let mut v = serde_json::to_value(&run).unwrap(); + v["hands_total"] = json!(run.hands_planned); + if run.status == "running" { + if let Ok(rt) = app.match_rt(&run.match_id) { + if let Some(p) = rt.progress() { + v["hands_done"] = p["hands_done"].clone(); + v["running_mbb_per_game"] = p["mbb_per_game"].clone(); + v["running_ci95_mbb"] = p["ci95_mbb"].clone(); + v["running_method"] = p["method"].clone(); + } + } + } + v +} + +fn find_run(app: &AppState, tid: &str, rid: &str) -> Res { + let r = app.store.get_run(rid)?.ok_or_else(|| ApiError::not_found("run"))?; + if r.track != tid { + return Err(ApiError::not_found("run")); + } + Ok(r) +} + +pub async fn get_run(State(app): App, Path((tid, rid)): Path<(String, String)>) -> Res> { + track(&tid)?; + let r = find_run(&app, &tid, &rid)?; + Ok(Json(run_json(&app, r))) +} + +#[derive(Deserialize)] +pub struct RunsQ { + #[serde(default)] + player_id: Option, + #[serde(default)] + limit: Option, +} + +pub async fn list_runs(State(app): App, Path(tid): Path, Query(q): Query) -> Res> { + track(&tid)?; + let runs = app.store.list_runs(Some(&tid), q.player_id.as_deref(), q.limit.unwrap_or(100).min(1000))?; + Ok(Json(json!(runs.into_iter().map(|r| run_json(&app, r)).collect::>()))) +} + +pub async fn abort_run(State(app): App, headers: HeaderMap, Path((tid, rid)): Path<(String, String)>) -> Res> { + let who = app.authenticate_any(&headers)?; + let r = find_run(&app, &tid, &rid)?; + if !who.is_admin() && !matches!(who, crate::state::Principal::Runner) && who.owner_id() != r.player_id { + return Err(ApiError::forbidden("not your run")); + } + let rt = app.match_rt(&r.match_id)?; + { + let mut s = rt.state.lock().unwrap(); + if s.rec.status == "finished" || s.rec.status == "aborted" { + return Err(ApiError::conflict("match_not_running", format!("run is {}", s.rec.status))); + } + s.abort = true; + s.rec.status = "aborted".into(); + } + matches::wake_all(&app, &rt); + Ok(Json(run_json(&app, r))) +} diff --git a/arena/server/src/config.rs b/arena/server/src/config.rs new file mode 100644 index 00000000..a4456951 --- /dev/null +++ b/arena/server/src/config.rs @@ -0,0 +1,157 @@ +//! Server configuration (environment variables, see README). + +use std::path::PathBuf; + +#[derive(Clone, Debug)] +pub struct ServerConfig { + /// `ARENA_BIND`, default `127.0.0.1:8080`. + pub bind: String, + /// `ARENA_DB`, SQLite path (ignored when `ARENA_DATABASE_URL` is set) or `:memory:`, default `arena.db`. + pub db_path: String, + /// `ARENA_ADMIN_TOKEN`; if unset a random one is generated and logged at startup. + pub admin_token: Option, + /// `ARENA_BLUEPRINT`: path to a compact blueprint (.plcp) to seat as house bot `blueprint`. + pub blueprint: Option, + /// `ARENA_BUCKETS`: bucketer spec, e.g. `tables:data/buckets-200` (default `coarse`). + pub buckets: String, + /// `ARENA_SIZING`: bet-size menu of the blueprint (default `medium`). + pub sizing: String, + /// `ARENA_OPEN_REGISTRATION` (default true): anyone may `POST /v1/bots`. + pub open_registration: bool, + /// `ARENA_ENABLE_WEBHOOKS` (default false): allow bots with a `webhook_url` (server-side requests). + pub enable_webhooks: bool, + /// `ARENA_HAND_DELAY_MS` (default 300): pause between hands on free tables. + pub hand_delay_ms: u64, + /// `ARENA_RECONNECT_GRACE_MS` (default 2000): how long a turn waits for a disconnected remote seat. + pub reconnect_grace_ms: u64, + /// `ARENA_LEADERBOARD_MIN_HANDS` (default 1000). + pub min_leaderboard_hands: u64, + /// `ARENA_RANKED_MIN_HANDS` (default 0 = any length): a verified run sets a bot's track score only with at least this many + /// hands, so a pile of short, wide-interval runs can't fish for a lucky score. Shorter runs still score for their owner. + pub ranked_min_hands: u64, + /// `ARENA_SAVE_FREE_HANDS` (default true): store hand histories of free tables too. + pub save_free_hands: bool, + /// `ARENA_DATABASE_URL` (`postgres://...`): use Postgres instead of SQLite. + pub database_url: Option, + /// `ARENA_DATABASE_SCHEMA`: Postgres schema for all tables (default: the connection's `public`). + pub database_schema: Option, + /// `ARENA_DB_POOL` (default 8): Postgres connections. + pub db_pool: usize, + /// `ARENA_RUNNER_TOKEN`: bearer token of the trusted eval runner (hosted attestation). Unset = no runner. + pub runner_token: Option, + /// `ARENA_WORKER_KEYS`: `id=secret,id2=secret2` HMAC keys of match workers (`sharingan-arena run --sign-key-file`); + /// `POST /v1/results` accepts only results signed with one of them. Unset = the endpoint refuses everything (401). + pub worker_keys: Vec<(String, String)>, + /// `ARENA_RATE_LIMIT_RPS` (default 50, 0 = off): sustained requests/s per bearer token (per IP when anonymous). + pub rate_limit_rps: f64, + /// `ARENA_RATE_LIMIT_BURST` (default 100). + pub rate_limit_burst: f64, + /// `ARENA_TRUST_PROXY` (default false): key anonymous requests by the first `X-Forwarded-For` hop. + pub trust_proxy: bool, + /// `ARENA_BOTS_PER_IP_PER_DAY` (default 0 = off; production sets 30): new bot registrations per client address per day (token bucket, + /// so a burst of 10, then one more every 2.4 h). Stops one person from minting bots to get around per-bot quotas. + pub bots_per_ip_per_day: f64, + /// `ARENA_MAX_TABLES_PER_PLAYER` (default 10): open free tables a player owns or sits at. + pub max_tables_per_player: usize, + /// `ARENA_MAX_MATCHES_PER_PLAYER` (default 4): unfinished matches/benchmark runs a player owns. + pub max_matches_per_player: usize, + /// `ARENA_MAX_WS_PER_PLAYER` (default 4): simultaneous `/v1/play` sockets. + pub max_ws_per_player: usize, + /// `ARENA_MAX_RUN_HANDS` (default 100000): hands of one benchmark run. + pub max_run_hands: u32, + /// `ARENA_MAX_MATCH_HANDS` (default 1000000): `hands_planned` of one match. + pub max_match_hands: u32, + /// `ARENA_MAX_BODY_BYTES` (default 262144): HTTP request body. + pub max_body_bytes: usize, + /// `ARENA_MAX_WS_MESSAGE_BYTES` (default 65536): one client WebSocket message. + pub max_ws_message_bytes: usize, + /// `ARENA_SHUTDOWN_GRACE_MS` (default 20000): how long SIGTERM lets running matches finish. + pub shutdown_grace_ms: u64, +} + +impl Default for ServerConfig { + fn default() -> Self { + ServerConfig { + bind: "127.0.0.1:8080".into(), + db_path: "arena.db".into(), + admin_token: None, + blueprint: None, + buckets: "coarse".into(), + sizing: "medium".into(), + open_registration: true, + enable_webhooks: false, + hand_delay_ms: 300, + reconnect_grace_ms: 2000, + min_leaderboard_hands: 1000, + ranked_min_hands: 0, + save_free_hands: true, + database_url: None, + database_schema: None, + db_pool: 8, + runner_token: None, + worker_keys: Vec::new(), + rate_limit_rps: 50.0, + rate_limit_burst: 100.0, + trust_proxy: false, + bots_per_ip_per_day: 0.0, + max_tables_per_player: 10, + max_matches_per_player: 4, + max_ws_per_player: 4, + max_run_hands: 100_000, + max_match_hands: 1_000_000, + max_body_bytes: 256 * 1024, + max_ws_message_bytes: 64 * 1024, + shutdown_grace_ms: 20_000, + } + } +} + +fn env(k: &str) -> Option { + std::env::var(k).ok().filter(|v| !v.is_empty()) +} + +fn flag(k: &str, d: bool) -> bool { + env(k).map(|v| matches!(v.as_str(), "1" | "true" | "yes" | "on")).unwrap_or(d) +} + +fn num(k: &str, d: T) -> T { + env(k).and_then(|v| v.parse().ok()).unwrap_or(d) +} + +impl ServerConfig { + pub fn from_env() -> Self { + let d = ServerConfig::default(); + ServerConfig { + bind: env("ARENA_BIND").unwrap_or(d.bind), + db_path: env("ARENA_DB").unwrap_or(d.db_path), + admin_token: env("ARENA_ADMIN_TOKEN"), + blueprint: env("ARENA_BLUEPRINT").map(PathBuf::from), + buckets: env("ARENA_BUCKETS").unwrap_or(d.buckets), + sizing: env("ARENA_SIZING").unwrap_or(d.sizing), + open_registration: flag("ARENA_OPEN_REGISTRATION", d.open_registration), + enable_webhooks: flag("ARENA_ENABLE_WEBHOOKS", d.enable_webhooks), + hand_delay_ms: num("ARENA_HAND_DELAY_MS", d.hand_delay_ms), + reconnect_grace_ms: num("ARENA_RECONNECT_GRACE_MS", d.reconnect_grace_ms), + min_leaderboard_hands: num("ARENA_LEADERBOARD_MIN_HANDS", d.min_leaderboard_hands), + ranked_min_hands: num("ARENA_RANKED_MIN_HANDS", d.ranked_min_hands), + save_free_hands: flag("ARENA_SAVE_FREE_HANDS", d.save_free_hands), + database_url: env("ARENA_DATABASE_URL"), + database_schema: env("ARENA_DATABASE_SCHEMA"), + db_pool: num("ARENA_DB_POOL", d.db_pool), + runner_token: env("ARENA_RUNNER_TOKEN"), + worker_keys: env("ARENA_WORKER_KEYS").map(|v| crate::worker::parse_keys(&v)).unwrap_or_default(), + rate_limit_rps: num("ARENA_RATE_LIMIT_RPS", d.rate_limit_rps), + rate_limit_burst: num("ARENA_RATE_LIMIT_BURST", d.rate_limit_burst), + trust_proxy: flag("ARENA_TRUST_PROXY", d.trust_proxy), + bots_per_ip_per_day: num("ARENA_BOTS_PER_IP_PER_DAY", d.bots_per_ip_per_day), + max_tables_per_player: num("ARENA_MAX_TABLES_PER_PLAYER", d.max_tables_per_player), + max_matches_per_player: num("ARENA_MAX_MATCHES_PER_PLAYER", d.max_matches_per_player), + max_ws_per_player: num("ARENA_MAX_WS_PER_PLAYER", d.max_ws_per_player), + max_run_hands: num("ARENA_MAX_RUN_HANDS", d.max_run_hands), + max_match_hands: num("ARENA_MAX_MATCH_HANDS", d.max_match_hands), + max_body_bytes: num("ARENA_MAX_BODY_BYTES", d.max_body_bytes), + max_ws_message_bytes: num("ARENA_MAX_WS_MESSAGE_BYTES", d.max_ws_message_bytes), + shutdown_grace_ms: num("ARENA_SHUTDOWN_GRACE_MS", d.shutdown_grace_ms), + } + } +} diff --git a/arena/server/src/deck.rs b/arena/server/src/deck.rs new file mode 100644 index 00000000..fbe7b7c7 --- /dev/null +++ b/arena/server/src/deck.rs @@ -0,0 +1,43 @@ +//! Deterministic dealing (TABLE_API.md section 7). +//! +//! `deck_i = Fisher-Yates(ChaCha20(key = HMAC_SHA256(seed_utf8, "deal:" + i)))` over the cards in the +//! order `2c 2d 2h 2s 3c ... As` (the `cards` crate ids 0..52). The shuffle runs `i = 51 .. 1` and draws +//! `j in [0, i]` by rejection sampling on consecutive little-endian `u32` words of the ChaCha20 +//! keystream (the stream with an all-zero nonce, block counter 0). Dealing order from the deck: +//! hole cards one at a time clockwise starting left of the button (two rounds), then burn+3 flop, +//! burn+turn, burn+river. + +use crate::util::{hmac_sha256, sha256_hex}; +use rand_chacha::rand_core::{RngCore, SeedableRng}; +use rand_chacha::ChaCha20Rng; + +pub fn deal_deck(seed: &str, deal_no: u64) -> Vec { + let key = hmac_sha256(seed.as_bytes(), format!("deal:{deal_no}").as_bytes()); + let mut rng = ChaCha20Rng::from_seed(key.try_into().expect("32-byte hmac")); + let mut deck: Vec = (0..52).collect(); + for i in (1..52usize).rev() { + let n = (i + 1) as u32; + let zone = u32::MAX - (u32::MAX % n); // accept x < zone + let j = loop { + let x = rng.next_u32(); + if x < zone { + break (x % n) as usize; + } + }; + deck.swap(i, j); + } + deck +} + +/// Put `prefix` first and keep the remaining cards in their `base` order (sandbox scripted decks). +pub fn with_prefix(base: &[u8], prefix: &[u8]) -> Vec { + let mut out: Vec = prefix.to_vec(); + out.extend(base.iter().copied().filter(|c| !prefix.contains(c))); + out +} + +pub fn commitment(deck: &[u8], salt: &str) -> String { + let mut s = cards::cards_str(deck); + s.push_str(salt); + sha256_hex(s.as_bytes()) +} diff --git a/arena/server/src/error.rs b/arena/server/src/error.rs new file mode 100644 index 00000000..0af56dac --- /dev/null +++ b/arena/server/src/error.rs @@ -0,0 +1,92 @@ +//! API errors: `{ "error": { "code", "message", "details" } }` with the HTTP status of TABLE_API.md section 10. + +use axum::http::StatusCode; +use axum::response::{IntoResponse, Response}; +use serde_json::{json, Value}; + +#[derive(Debug, Clone)] +pub struct ApiError { + pub status: StatusCode, + pub code: &'static str, + pub message: String, + pub details: Value, +} + +pub type Res = Result; + +impl ApiError { + pub fn new(status: u16, code: &'static str, message: impl Into) -> Self { + ApiError { + status: StatusCode::from_u16(status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR), + code, + message: message.into(), + details: json!({}), + } + } + pub fn with(mut self, details: Value) -> Self { + self.details = details; + self + } + pub fn bad_request(m: impl Into) -> Self { + Self::new(400, "bad_request", m) + } + pub fn unauthorized() -> Self { + Self::new(401, "unauthorized", "missing or invalid bearer token") + } + pub fn forbidden(m: impl Into) -> Self { + Self::new(403, "forbidden", m) + } + pub fn not_found(what: &str) -> Self { + Self::new(404, "not_found", format!("{what} not found")) + } + pub fn conflict(code: &'static str, m: impl Into) -> Self { + Self::new(409, code, m) + } + /// 429 `rate_limited`; `details.limit` names the knob (an `ARENA_*` setting) that was hit. + pub fn rate_limited(m: impl Into, details: Value) -> Self { + Self::new(429, "rate_limited", m).with(details) + } + pub fn payload_too_large(max: usize) -> Self { + Self::new(413, "payload_too_large", format!("request body exceeds {max} bytes")).with(json!({"max_bytes": max})) + } + pub fn shutting_down() -> Self { + Self::new(503, "shutting_down", "the server is draining for shutdown; retry against another instance") + } + pub fn internal(m: impl std::fmt::Display) -> Self { + Self::new(500, "internal", m.to_string()) + } + pub fn body(&self) -> Value { + json!({"error": {"code": self.code, "message": self.message, "details": self.details}}) + } +} + +impl std::fmt::Display for ApiError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}: {}", self.code, self.message) + } +} + +impl IntoResponse for ApiError { + fn into_response(self) -> Response { + let retry_ms = self.details.get("retry_after_ms").and_then(|v| v.as_u64()); + let mut res = (self.status, axum::Json(self.body())).into_response(); + if let Some(ms) = retry_ms { + if let Ok(v) = ((ms + 999) / 1000).max(1).to_string().parse() { + res.headers_mut().insert("retry-after", v); + } + } + res + } +} + +impl From for ApiError { + fn from(e: rusqlite::Error) -> Self { + ApiError::internal(format!("storage: {e}")) + } +} + +impl From for ApiError { + fn from(e: serde_json::Error) -> Self { + ApiError::internal(format!("json: {e}")) + } +} diff --git a/arena/server/src/hand.rs b/arena/server/src/hand.rs new file mode 100644 index 00000000..097e04a4 --- /dev/null +++ b/arena/server/src/hand.rs @@ -0,0 +1,852 @@ +//! One hand of NLHE as an event-producing state machine on top of `nlhe::State`. +//! +//! The rules live entirely in the `nlhe` engine; this module maps physical seats to engine seats, +//! deals from a given deck, validates client actions against `State::legal()` and renders every +//! payload of TABLE_API.md section 5 (`hand_start`, `hole_cards`, `action`, `street`, `your_turn`, +//! `hand_end`) plus the `HandHistory` of section 8. It is synchronous and does no I/O. +//! +//! Engine seat `i` (0 = SB ... last = button; heads-up: 0 = button/SB) maps to the physical seat +//! `order[i]`. Sequence numbers: `action`, `street`, `your_turn` and `hand_end` events share one +//! gap-free per-hand counter starting at 1 (blinds are 1 and 2); `hand_start` and `hole_cards` +//! are unsequenced. + +use crate::deck; +use crate::error::{ApiError, Res}; +use crate::model::*; +use crate::util::iso; +use bench::policy::Event; +use cards::{bit, card_str, category, evaluate, Card}; +use nlhe::{Action, Deal, GameConfig, State, Step, Street, MAX_PLAYERS}; +use serde_json::{json, Value}; +use std::collections::BTreeMap; + +#[derive(Clone, Debug)] +pub struct SeatInfo { + pub seat: usize, + pub player_id: String, + pub name: String, + pub kind: String, + pub stack: i64, +} + +#[derive(Clone, Debug)] +pub struct HandSetup { + pub table_id: String, + pub hand_id: String, + pub match_id: Option, + pub hand_no: u32, + pub deal_no: Option, + pub rotation: Option, + pub cfg: TableConfig, + pub button_seat: usize, + /// Seats dealt into this hand (2..=6). + pub seats: Vec, + /// Seated but not dealt in (reported as `in_hand: false`). + pub sitting_out: Vec, + pub deck: Vec, + pub salt: String, + pub started_ms: u64, + /// Benchmark fast path: build no JSON for events the recipients will not get. + pub lean: bool, +} + +/// A server event of this hand before it is wrapped in an envelope. +#[derive(Clone, Debug)] +pub struct HandEvent { + pub kind: &'static str, + pub seq: Option, + /// Physical seat the event is private to; `None` = broadcast. + pub to: Option, + pub data: Value, +} + +#[derive(Clone, Debug)] +pub struct ActReq { + pub kind: String, + pub to: Option, +} + +pub struct Applied { + pub events: Vec, + pub action: Action, + /// State before the action (for `Player::observe`). + pub pre: State, + pub idx: usize, + /// Board lengths revealed by this action (for `Player::observe_board`). + pub reveals: Vec, +} + +#[derive(Clone, Debug)] +pub struct PendingTurn { + pub decision_id: String, + pub idx: usize, + pub seat: usize, + pub event: HandEvent, +} + +pub struct HandRunner { + pub setup: HandSetup, + pub order: Vec, + pub info: Vec, + pub ecfg: GameConfig, + pub st: State, + pub deal: Deal, + pub board_len: usize, + pub ehist: Vec, + actions: Vec, + seq: u32, + pub pending: Option, + decision_times: BTreeMap, + pub anomalies: Vec, + last_decision: u32, +} + +fn street_name(s: Street) -> &'static str { + ["preflop", "flop", "turn", "river"][s.idx()] +} + +fn street_for_len(len: usize) -> &'static str { + match len { + 3 => "flop", + 4 => "turn", + _ => "river", + } +} + +fn cstr(c: Card) -> String { + card_str(c) +} + +fn pair(h: [Card; 2]) -> [String; 2] { + [cstr(h[0]), cstr(h[1])] +} + +impl HandRunner { + /// Build the hand and its opening events (`hand_start`, `hole_cards`, blinds, and any run-out + /// when the blinds already put everyone all-in). + pub fn new(setup: HandSetup) -> Res<(HandRunner, Vec)> { + let n = setup.seats.len(); + if !(2..=MAX_PLAYERS).contains(&n) { + return Err(ApiError::internal("hand needs 2..6 players")); + } + if setup.deck.len() != 52 { + return Err(ApiError::internal("deck must have 52 cards")); + } + let max_seats = setup.cfg.max_seats as usize; + let occupied: Vec = setup.seats.iter().map(|s| s.seat).collect(); + if !occupied.contains(&setup.button_seat) { + return Err(ApiError::internal("button must be an occupied seat")); + } + let order: Vec = if n == 2 { + let other = *occupied.iter().find(|&&s| s != setup.button_seat).unwrap(); + vec![setup.button_seat, other] + } else { + (1..=max_seats) + .map(|k| (setup.button_seat + k) % max_seats) + .filter(|s| occupied.contains(s)) + .collect() + }; + let info: Vec = order + .iter() + .map(|&s| setup.seats.iter().find(|x| x.seat == s).unwrap().clone()) + .collect(); + let stacks: Vec = info.iter().map(|s| s.stack as i32).collect(); + let ecfg = GameConfig { + players: n, + stack: setup.cfg.starting_stack as i32, + small_blind: setup.cfg.small_blind as i32, + big_blind: setup.cfg.big_blind as i32, + stacks: None, + ..GameConfig::new(2) + } + .with_stacks(&stacks); + let st = State::new(&ecfg); + let d = &setup.deck; + let mut holes = [[0u8; 2]; MAX_PLAYERS]; + for (i, h) in holes.iter_mut().enumerate().take(n) { + *h = [d[i], d[n + i]]; + } + let board = [d[2 * n + 1], d[2 * n + 2], d[2 * n + 3], d[2 * n + 5], d[2 * n + 7]]; + let deal = Deal { holes, board }; + let mut r = HandRunner { + setup, + order, + info, + ecfg, + st, + deal, + board_len: 0, + ehist: Vec::new(), + actions: Vec::new(), + seq: 0, + pending: None, + decision_times: BTreeMap::new(), + anomalies: Vec::new(), + last_decision: 0, + }; + let mut ev = Vec::new(); + if !r.setup.lean { + ev.push(r.hand_start_event()); + } + for i in 0..n { + if r.setup.lean { + break; + } + ev.push(HandEvent { + kind: "hole_cards", + seq: None, + to: Some(r.order[i]), + data: json!({"hand_id": r.setup.hand_id, "seat": r.order[i], "cards": pair(r.deal.holes[i])}), + }); + } + r.post_blinds(&mut ev); + if r.st.is_terminal() { + r.runout(&mut ev, &mut Vec::new()); + } + Ok((r, ev)) + } + + // ---- small accessors ---- + pub fn hand_id(&self) -> &str { + &self.setup.hand_id + } + pub fn n(&self) -> usize { + self.info.len() + } + pub fn seat_of(&self, idx: usize) -> usize { + self.order[idx] + } + pub fn idx_of_seat(&self, seat: usize) -> Option { + self.order.iter().position(|&s| s == seat) + } + pub fn is_over(&self) -> bool { + self.st.is_terminal() + } + pub fn to_act_idx(&self) -> Option { + self.st.to_act() + } + pub fn board(&self) -> &[Card] { + &self.deal.board[..self.board_len] + } + fn next_seq(&mut self) -> u32 { + self.seq += 1; + self.seq + } + fn aid(&self, seq: u32) -> String { + format!("a-{}-{}", self.setup.hand_id, seq) + } + fn sb_seat(&self) -> usize { + self.order[0] + } + fn bb_seat(&self) -> usize { + self.order[1] + } + + fn hand_start_event(&self) -> HandEvent { + let s = &self.setup; + let mut players: Vec = s + .seats + .iter() + .map(|p| (p, true)) + .chain(s.sitting_out.iter().map(|p| (p, false))) + .map(|(p, inh)| { + json!({"seat": p.seat, "player_id": p.player_id, "name": p.name, "stack_start": p.stack, "in_hand": inh}) + }) + .collect(); + players.sort_by_key(|p| p["seat"].as_u64()); + let ds = s.deal_no; + HandEvent { + kind: "hand_start", + seq: None, + to: None, + data: json!({ + "hand_id": s.hand_id, "hand_no": s.hand_no, "match_id": s.match_id, + "deal_no": ds, "rotation": s.rotation, + "button_seat": s.button_seat, "sb_seat": self.sb_seat(), "bb_seat": self.bb_seat(), + "small_blind": s.cfg.small_blind, "big_blind": s.cfg.big_blind, "ante": 0, + "players": players, + "deck_commitment": deck::commitment(&s.deck, &s.salt), + }), + } + } + + fn mk_action( + &mut self, + street: &str, + idx: usize, + kind: &str, + to: i64, + added: i64, + all_in: bool, + forced: bool, + timeout: bool, + stack: i64, + pot: i64, + current_bet: i64, + min_raise_to: i64, + next: Option, + ) -> ActionEvent { + let seq = self.next_seq(); + let ev = ActionEvent { + hand_id: self.setup.hand_id.clone(), + seq, + action_id: self.aid(seq), + street: street.to_string(), + seat: self.order[idx] as u8, + kind: kind.to_string(), + to, + added, + all_in, + forced, + timeout, + stack, + pot, + current_bet, + min_raise_to, + next_to_act: next.map(|i| self.order[i] as u8), + }; + self.actions.push(ev.clone()); + ev + } + + fn action_he(ev: &ActionEvent) -> HandEvent { + HandEvent { kind: "action", seq: Some(ev.seq), to: None, data: serde_json::to_value(ev).unwrap() } + } + + fn post_blinds(&mut self, ev: &mut Vec) { + let (sb, bb) = (self.setup.cfg.small_blind, self.setup.cfg.big_blind); + let s0 = self.info[0].stack; + let s1 = self.info[1].stack; + let sb_add = sb.min(s0); + let bb_add = bb.min(s1); + let a = self.mk_action( + "preflop", 0, "post_sb", sb_add, sb_add, sb_add == s0, true, false, + s0 - sb_add, sb_add, sb_add, bb, Some(1), + ); + if !self.setup.lean { + ev.push(Self::action_he(&a)); + } + let cur = sb_add.max(bb_add); + let next = self.st.to_act(); + let b = self.mk_action( + "preflop", 1, "post_bb", bb_add, bb_add, bb_add == s1, true, false, + s1 - bb_add, sb_add + bb_add, cur, cur + self.st.last_raise() as i64, next, + ); + if !self.setup.lean { + ev.push(Self::action_he(&b)); + } + } + + // ---- pots ---- + /// Main and side pots as (amount, eligible engine seats). + fn pot_levels(&self) -> Vec<(i64, Vec)> { + let n = self.n(); + let live: Vec = (0..n).filter(|&i| !self.st.is_folded(i)).collect(); + let tot = |i: usize| self.st.contributed(i) as i64; + let mut levels: Vec = live.iter().map(|&i| tot(i)).collect(); + levels.sort_unstable(); + levels.dedup(); + let mut prev = 0; + let mut out = Vec::new(); + for lv in levels { + if lv == prev { + continue; + } + let amount: i64 = (0..n).map(|i| tot(i).min(lv) - tot(i).min(prev)).sum(); + let elig: Vec = live.iter().copied().filter(|&i| tot(i) >= lv).collect(); + out.push((amount, elig)); + prev = lv; + } + out + } + + fn pots_json(&self) -> Value { + Value::Array( + self.pot_levels() + .into_iter() + .map(|(a, e)| { + let mut seats: Vec = e.iter().map(|&i| self.order[i]).collect(); + seats.sort_unstable(); + json!({"amount": a, "eligible_seats": seats}) + }) + .collect(), + ) + } + + fn status_of(&self, i: usize) -> &'static str { + if self.st.is_folded(i) { + "folded" + } else if self.st.is_all_in(i) { + "all_in" + } else { + "active" + } + } + + fn players_json(&self) -> Value { + let mut v: Vec<(usize, Value)> = (0..self.n()) + .map(|i| { + ( + self.order[i], + json!({ + "seat": self.order[i], "player_id": self.info[i].player_id, "name": self.info[i].name, + "stack_start": self.info[i].stack, "stack": self.st.stack(i), + "street_contrib": self.st.street_bet(i), "hand_contrib": self.st.contributed(i), + "status": self.status_of(i), + }), + ) + }) + .collect(); + v.sort_by_key(|x| x.0); + Value::Array(v.into_iter().map(|x| x.1).collect()) + } + + /// Public hand state for `GET /v1/tables/{id}` (no hole cards). + pub fn public_state(&self) -> Value { + let street = if self.is_over() { "showdown" } else { street_name(self.st.street()) }; + json!({ + "hand_id": self.setup.hand_id, "hand_no": self.setup.hand_no, "match_id": self.setup.match_id, + "deal_no": self.setup.deal_no, "rotation": self.setup.rotation, + "street": street, + "board": self.board().iter().map(|&c| cstr(c)).collect::>(), + "button_seat": self.setup.button_seat, "sb_seat": self.sb_seat(), "bb_seat": self.bb_seat(), + "small_blind": self.setup.cfg.small_blind, "big_blind": self.setup.cfg.big_blind, + "pot": self.st.pot(), "pots": self.pots_json(), + "to_act": self.st.to_act().map(|i| self.order[i]), + "players": self.players_json(), + "actions": self.actions.len(), + }) + } + + pub fn hole_cards_of_seat(&self, seat: usize) -> Option<[String; 2]> { + self.idx_of_seat(seat).map(|i| pair(self.deal.holes[i])) + } + + // ---- turns ---- + /// Create the `your_turn` event for the seat to act (allocates its seq and decision id). + pub fn begin_turn(&mut self, deadline_ms: u64, bank_ms: u64) -> Option<&PendingTurn> { + let idx = self.st.to_act()?; + // `your_turn` carries the seq the next event will take but does not consume it, so the + // seqs of all other events stay gap-free. + let seq = self.seq + 1; + self.last_decision += 1; + let decision_id = format!("d-{}-{}", self.setup.hand_id, seq); + let l = self.st.legal(); + let call = if l.can_check { + Value::Null + } else { + json!({"to": self.st.street_bet(idx) + l.call_amount, "added": l.call_amount, + "all_in": l.call_amount >= self.st.stack(idx)}) + }; + let raise = if l.can_raise { + json!({"min_to": l.min_raise_to, "max_to": l.max_raise_to}) + } else { + Value::Null + }; + let seat = self.order[idx]; + let data = json!({ + "hand_id": self.setup.hand_id, "seq": seq, "decision_id": decision_id, "seat": seat, + "street": street_name(self.st.street()), + "hole_cards": pair(self.deal.holes[idx]), + "board": self.board().iter().map(|&c| cstr(c)).collect::>(), + "history": self.actions, + "players": self.players_json(), + "button_seat": self.setup.button_seat, + "small_blind": self.setup.cfg.small_blind, "big_blind": self.setup.cfg.big_blind, + "pot": self.st.pot(), "pots": self.pots_json(), + "legal": {"fold": l.can_fold, "check": l.can_check, "call": call, "raise": raise}, + "deadline_ms": deadline_ms, "time_bank_ms": bank_ms, + }); + self.pending = Some(PendingTurn { + decision_id, + idx, + seat, + event: HandEvent { kind: "your_turn", seq: Some(seq), to: Some(seat), data }, + }); + self.pending.as_ref() + } + + /// Validate a client action against the legal set; the state is untouched on error. + pub fn validate(&self, req: &ActReq) -> Res { + let l = self.st.legal(); + let illegal = |m: &str| { + ApiError::new(422, "illegal_action", m.to_string()).with(json!({"type": req.kind})) + }; + Ok(match req.kind.as_str() { + // Fold when check is free is converted to a check (TABLE_API.md 6.6). + "fold" => { + if l.can_fold { + Action::Fold + } else { + Action::Check + } + } + "check" => { + if !l.can_check { + return Err(illegal("cannot check, there is a bet to call")); + } + Action::Check + } + "call" => { + if l.can_check { + return Err(illegal("nothing to call, use check")); + } + Action::Call + } + "bet" | "raise" => { + if !l.can_raise { + return Err(illegal("raising is not allowed here")); + } + if req.kind == "bet" && self.st.cur_bet() > 0 { + return Err(illegal("bet is only valid when there is no bet, use raise")); + } + let to = req.to.ok_or_else(|| { + ApiError::new(422, "bad_amount", "`to` is required for bet/raise") + .with(json!({"min_to": l.min_raise_to, "max_to": l.max_raise_to})) + })?; + if to < l.min_raise_to as i64 || to > l.max_raise_to as i64 { + return Err(ApiError::new( + 422, + "bad_amount", + format!("`to` must be in [{}, {}]", l.min_raise_to, l.max_raise_to), + ) + .with(json!({"min_to": l.min_raise_to, "max_to": l.max_raise_to, "to": to}))); + } + Action::RaiseTo(to as i32) + } + _ => return Err(illegal("unknown action type")), + }) + } + + /// Timeout policy: check if free, else fold. + pub fn timeout_action(&self) -> Action { + if self.st.legal().can_check { + Action::Check + } else { + Action::Fold + } + } + + /// Apply an engine action for the seat to act. `think_ms` is recorded in the history. + pub fn apply(&mut self, action: Action, timeout: bool, think_ms: u64) -> Applied { + let idx = self.st.to_act().expect("apply on a live hand"); + let pre = self.st; + let street = pre.street(); + let mut st = self.st; + let step = st.apply(action); + self.st = st; + let added = (pre.stack(idx) - st.stack(idx)) as i64; + let kind = match action { + Action::Fold => "fold", + Action::Check => "check", + Action::Call => { + if added == 0 { + "check" + } else { + "call" + } + } + Action::RaiseTo(_) => { + if pre.cur_bet() == 0 { + "bet" + } else { + "raise" + } + } + }; + let to = match kind { + "fold" | "check" => 0, + _ => (pre.street_bet(idx) as i64) + added, + }; + let all_in = kind != "fold" && st.is_all_in(idx); + let next = st.to_act(); + let ev = self.mk_action( + street_name(street), idx, kind, to, added, all_in, false, timeout, + st.stack(idx) as i64, st.pot() as i64, st.cur_bet() as i64, + (st.cur_bet() + st.last_raise()) as i64, next, + ); + self.decision_times.insert(ev.action_id.clone(), think_ms); + self.ehist.push(Event { seat: idx as u8, street, action }); + self.pending = None; + let mut events = if self.setup.lean { Vec::new() } else { vec![Self::action_he(&ev)] }; + let mut reveals = Vec::new(); + match step { + Step::Continue => {} + Step::NewStreet(s) => { + self.reveal(s.board_len(), &mut events); + reveals.push(s.board_len()); + } + Step::Terminal => { + if st.showdown() { + self.runout(&mut events, &mut reveals); + } + } + } + Applied { events, action, pre, idx, reveals } + } + + fn reveal(&mut self, to: usize, events: &mut Vec) { + let from = self.board_len; + self.board_len = to; + let seq = self.next_seq(); + if self.setup.lean { + return; + } + events.push(HandEvent { + kind: "street", + seq: Some(seq), + to: None, + data: json!({ + "hand_id": self.setup.hand_id, "seq": seq, "street": street_for_len(to), + "board": self.board().iter().map(|&c| cstr(c)).collect::>(), + "new_cards": self.deal.board[from..to].iter().map(|&c| cstr(c)).collect::>(), + "pot": self.st.pot(), "pots": self.pots_json(), + }), + }); + } + + fn runout(&mut self, events: &mut Vec, reveals: &mut Vec) { + if !self.st.showdown() { + return; + } + while self.board_len < 5 { + let to = if self.board_len == 0 { 3 } else { self.board_len + 1 }; + self.reveal(to, events); + reveals.push(to); + } + } + + fn best5(&self, idx: usize) -> (String, Vec) { + let cs: Vec = self.deal.holes[idx].iter().chain(self.deal.board.iter()).copied().collect(); + let full = evaluate(cs.iter().fold(0, |m, &c| m | bit(c))); + let mut best: Vec = Vec::new(); + for a in 0..7 { + for b in a + 1..7 { + let pick: Vec = (0..7).filter(|&k| k != a && k != b).map(|k| cs[k]).collect(); + if evaluate(pick.iter().fold(0, |m, &c| m | bit(c))) == full { + best = pick; + break; + } + } + if !best.is_empty() { + break; + } + } + best.sort_by_key(|&c| std::cmp::Reverse(cards::rank_of(c))); + let name = format!("{:?}", category(full)).to_lowercase(); + (name, best.into_iter().map(cstr).collect()) + } + + /// Pots with winners and shares, computed like the engine's `payoffs` (odd chips left of the button). + fn pot_results(&mut self) -> Vec { + let n = self.n(); + let levels = self.pot_levels(); + let live: Vec = (0..n).filter(|&i| !self.st.is_folded(i)).collect(); + let mut rank = [0u32; MAX_PLAYERS]; + if self.st.showdown() { + let board = self.deal.board.iter().fold(0, |m, &c| m | bit(c)); + for &i in &live { + rank[i] = evaluate(bit(self.deal.holes[i][0]) | bit(self.deal.holes[i][1]) | board); + } + } + let first = if n == 2 { 1 } else { 0 }; + let mut out = Vec::new(); + for (amount, elig) in levels { + let best = elig.iter().map(|&i| rank[i]).max().unwrap_or(0); + let winners: Vec = (0..n) + .map(|k| (first + k) % n) + .filter(|i| elig.contains(i) && rank[*i] == best) + .collect(); + let w = winners.len().max(1) as i64; + let (share, odd) = (amount / w, (amount % w) as usize); + let shares: Vec = (0..winners.len()).map(|k| share + (k < odd) as i64).collect(); + let mut es: Vec = elig.iter().map(|&i| self.order[i] as u8).collect(); + es.sort_unstable(); + out.push(PotResult { + amount, + eligible_seats: es, + winners: winners.iter().map(|&i| self.order[i] as u8).collect(), + share: shares, + }); + } + out + } + + /// Settle a terminal hand: the `hand_end` event and the full history. + pub fn finish(&mut self, want_end: bool) -> (Vec, HandHistory) { + assert!(self.st.is_terminal()); + let n = self.n(); + let mut events = Vec::new(); + self.runout(&mut events, &mut Vec::new()); + let payoffs = self.st.payoffs(&self.deal); + let pots = self.pot_results(); + // Cross-check the per-pot split against the engine's payoffs. + let mut net = vec![0i64; n]; + for i in 0..n { + net[i] = -(self.st.contributed(i) as i64); + } + for p in &pots { + for (w, s) in p.winners.iter().zip(&p.share) { + let i = self.idx_of_seat(*w as usize).unwrap(); + net[i] += s; + } + } + for i in 0..n { + if net[i] != payoffs[i] as i64 { + self.anomalies.push(format!("pot split mismatch at seat {}: {} vs engine {}", self.order[i], net[i], payoffs[i])); + } + } + let results: Vec = { + let mut v: Vec = (0..n) + .map(|i| ResultRow { + seat: self.order[i] as u8, + player_id: self.info[i].player_id.clone(), + net: payoffs[i] as i64, + stack_end: self.info[i].stack + payoffs[i] as i64, + }) + .collect(); + v.sort_by_key(|r| r.seat); + v + }; + if results.iter().map(|r| r.net).sum::() != 0 { + self.anomalies.push("sum(net) != 0".into()); + } + let showdown = self.st.showdown(); + let mut sd = Vec::new(); + if showdown && want_end { + let mut live: Vec = (0..n).filter(|&i| !self.st.is_folded(i)).collect(); + live.sort_by_key(|&i| self.order[i]); + for i in live { + let (rank, best5) = self.best5(i); + sd.push(json!({"seat": self.order[i], "cards": pair(self.deal.holes[i]), "shown": true, + "hand_rank": rank, "best5": best5})); + } + } + let mut hole_cards: BTreeMap = BTreeMap::new(); + for i in 0..n { + hole_cards.insert(self.order[i] as u8, pair(self.deal.holes[i])); + } + let seq = self.next_seq(); + let ended_by = if showdown { "showdown" } else { "fold" }; + let runout: Vec = self.deal.board.iter().map(|&c| cstr(c)).collect(); + let deck_strs: Vec = self.setup.deck.iter().map(|&c| cstr(c)).collect(); + if want_end { + events.push(HandEvent { + kind: "hand_end", + seq: Some(seq), + to: None, + data: json!({ + "hand_id": self.setup.hand_id, "seq": seq, + "board": self.board().iter().map(|&c| cstr(c)).collect::>(), + "runout": runout, + "showdown": sd, + "hole_cards": hole_cards, + "pots": pots, "results": results, + "deck_reveal": {"deck": deck_strs, "salt": self.setup.salt}, + "ended_by": ended_by, + }), + }); + } + let s = &self.setup; + let mut players: Vec = self + .info + .iter() + .map(|p| HistPlayer { + seat: p.seat as u8, + player_id: p.player_id.clone(), + name: p.name.clone(), + kind: p.kind.clone(), + stack_start: p.stack, + }) + .collect(); + players.sort_by_key(|p| p.seat); + let ended_ms = crate::util::now_ms(); + let hist = HandHistory { + hand_id: s.hand_id.clone(), + hand_no: s.hand_no, + match_id: s.match_id.clone(), + table_id: s.table_id.clone(), + deal_no: s.deal_no, + rotation: s.rotation, + started_at: iso(s.started_ms), + ended_at: iso(ended_ms), + config: HistConfig { + small_blind: s.cfg.small_blind, + big_blind: s.cfg.big_blind, + ante: 0, + starting_stack: s.cfg.starting_stack, + stack_mode: format!("{:?}", s.cfg.stack_mode).to_lowercase(), + }, + button_seat: s.button_seat as u8, + sb_seat: self.sb_seat() as u8, + bb_seat: self.bb_seat() as u8, + players, + hole_cards, + board: self.board().iter().map(|&c| cstr(c)).collect(), + runout: self.deal.board.iter().map(|&c| cstr(c)).collect(), + deck: deck_strs_of(&s.deck), + deck_salt: s.salt.clone(), + actions: self.actions.clone(), + decision_times_ms: self.decision_times.clone(), + pots, + results, + ended_by: ended_by.into(), + anomalies: self.anomalies.clone(), + }; + (events, hist) + } +} + +fn deck_strs_of(d: &[Card]) -> Vec { + d.iter().map(|&c| cstr(c)).collect() +} + +/// Rebuild the engine view of a stored hand for replay (AIVAT): config, deal and the list of +/// voluntary actions per engine seat. Returns `(cfg, deal, order, actions)`. +pub fn replay_parts(h: &HandHistory) -> Res<(GameConfig, Deal, Vec, Vec)> { + let n = h.players.len(); + let max_seats = 6usize; + let occupied: Vec = h.players.iter().map(|p| p.seat as usize).collect(); + let button = h.button_seat as usize; + let order: Vec = if n == 2 { + let other = *occupied.iter().find(|&&s| s != button).ok_or_else(|| ApiError::internal("bad history"))?; + vec![button, other] + } else { + (1..=max_seats).map(|k| (button + k) % max_seats).filter(|s| occupied.contains(s)).collect() + }; + let stacks: Vec = order + .iter() + .map(|s| h.players.iter().find(|p| p.seat as usize == *s).map(|p| p.stack_start as i32).unwrap_or(0)) + .collect(); + let ecfg = GameConfig { + players: n, + stack: h.config.starting_stack as i32, + small_blind: h.config.small_blind as i32, + big_blind: h.config.big_blind as i32, + stacks: None, + ..GameConfig::new(2) + } + .with_stacks(&stacks); + let deck: Vec = h + .deck + .iter() + .map(|s| cards::parse_card(s).ok_or_else(|| ApiError::internal("bad card"))) + .collect::>()?; + let mut holes = [[0u8; 2]; MAX_PLAYERS]; + for (i, hh) in holes.iter_mut().enumerate().take(n) { + *hh = [deck[i], deck[n + i]]; + } + let deal = Deal { holes, board: [deck[2 * n + 1], deck[2 * n + 2], deck[2 * n + 3], deck[2 * n + 5], deck[2 * n + 7]] }; + let actions = h + .actions + .iter() + .filter(|a| !a.forced) + .map(|a| match a.kind.as_str() { + "fold" => Action::Fold, + "check" => Action::Check, + "call" => Action::Call, + _ => Action::RaiseTo(a.to as i32), + }) + .collect(); + Ok((ecfg, deal, order, actions)) +} diff --git a/arena/server/src/house.rs b/arena/server/src/house.rs new file mode 100644 index 00000000..0c3ddda1 --- /dev/null +++ b/arena/server/src/house.rs @@ -0,0 +1,130 @@ +//! House bots: server-side players built on the bench Policy API. + +use crate::config::ServerConfig; +use crate::error::Res; +use crate::model::PlayerRecord; +use crate::store::Store; +use crate::util::now_iso; +use bench::policy::PolicyFactory; +use std::collections::BTreeMap; +use std::sync::Arc; + +#[derive(Default)] +pub struct HouseRegistry { + pub bots: BTreeMap>, + /// sha256 of the first 4 MiB of the blueprint file plus its size; recorded with benchmark runs. + pub blueprint_fp: Option, +} + +pub fn house_id(key: &str) -> String { + format!("house:{key}") +} + +impl HouseRegistry { + pub fn build(cfg: &ServerConfig) -> Result { + let mut bots: BTreeMap> = BTreeMap::new(); + // (public name, bench builtin) + for (public, n) in [ + ("random", "random"), + ("calling_station", "station"), + ("tight_aggressive", "tag"), + ("nit", "nit"), + ("lag", "lag"), + ("maniac", "maniac"), + ] { + bots.insert(public.into(), bench::builtin::builtin(n).ok_or(format!("builtin {n}"))?); + } + for n in ["chart6", "chart6-loose", "chart6-tight"] { + bots.insert(n.into(), Arc::new(bench::chart::Chart6::by_name(n).ok_or(format!("chart {n}"))?)); + } + let mut blueprint_fp = None; + if let Some(path) = &cfg.blueprint { + blueprint_fp = Some(fingerprint(path)?); + let b = bench::bp::bucketer_by_name(&cfg.buckets).ok_or(format!("unknown bucketer {}", cfg.buckets))?; + let s = bench::bp::sizing_by_name(&cfg.sizing).ok_or(format!("unknown sizing {}", cfg.sizing))?; + let mut p = bench::compact::CompactPolicy::open(path, b, s)?; + // ARENA_TRACK=pre-sync-fix reproduces the translation used before the Nov 2026 fix + // (for A/B evaluation only). + if std::env::var("ARENA_TRACK").as_deref() == Ok("pre-sync-fix") { + p = p.with_opts(nlhe::abstraction::TrackOpts::PRE_SYNC_FIX); + } + bots.insert("sharingan-1".into(), Arc::new(p)); + } + Ok(HouseRegistry { bots, blueprint_fp }) + } + + /// Resolve `house:tight_aggressive` (also bare names and the short aliases `tag`, + /// `station`, `blueprint`) to a registry key. + pub fn key_of(&self, s: &str) -> Option { + let k = s.strip_prefix("house:").or_else(|| s.strip_prefix("house-")).unwrap_or(s); + let k = match k { + "tag" => "tight_aggressive", + "station" => "calling_station", + "blueprint" => "sharingan-1", + o => o, + }; + self.bots.contains_key(k).then(|| k.to_string()) + } + + /// True if `s` names a house bot (configured or not). + pub fn looks_like_house(s: &str) -> bool { + s.starts_with("house:") || s.starts_with("house-") + } + + /// Like `key_of` but with a clear error for unknown or unconfigured bots. + pub fn resolve(&self, s: &str) -> crate::error::Res { + self.key_of(s).ok_or_else(|| { + let k = s.trim_start_matches("house:").trim_start_matches("house-"); + if k == "sharingan-1" || k == "blueprint" { + crate::error::ApiError::bad_request("house:sharingan-1 is not available: no blueprint configured (set ARENA_BLUEPRINT)") + } else { + crate::error::ApiError::bad_request(format!( + "unknown house bot {s}; available: {}", + self.bots.keys().map(|k| format!("house:{k}")).collect::>().join(", ") + )) + } + }) + } + + /// The `ladder` field: random, calling_station, 2x tight_aggressive, sharingan-1. + pub fn ladder(&self) -> crate::error::Res> { + let v = ["random", "calling_station", "tight_aggressive", "tight_aggressive", "sharingan-1"]; + v.iter().map(|k| self.resolve(k).map(|k| house_id(&k))).collect() + } + + pub fn get(&self, key: &str) -> Option> { + self.bots.get(key).cloned() + } + + /// Make sure every house bot exists as a (token-less) player record. + pub fn register_players(&self, store: &dyn Store) -> Res<()> { + for k in self.bots.keys() { + let id = house_id(k); + if store.get_player(&id)?.is_none() { + store.put_player(&PlayerRecord { + player_id: id, + name: format!("house:{k}"), + kind: "bot".into(), + owner: Some("house".into()), + created_at: now_iso(), + house: true, + token_hash: String::new(), + webhook_url: None, + webhook_secret: None, + })?; + } + } + Ok(()) + } +} + +fn fingerprint(path: &std::path::Path) -> Result { + use std::io::Read; + let mut f = std::fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?; + let len = f.metadata().map_err(|e| e.to_string())?.len(); + let mut buf = vec![0u8; 4 << 20]; + let n = f.read(&mut buf).map_err(|e| e.to_string())?; + buf.truncate(n); + buf.extend_from_slice(&len.to_le_bytes()); + Ok(crate::util::sha256_hex(&buf)[..16].to_string()) +} diff --git a/arena/server/src/hub.rs b/arena/server/src/hub.rs new file mode 100644 index 00000000..e5c8bc77 --- /dev/null +++ b/arena/server/src/hub.rs @@ -0,0 +1,65 @@ +//! Registry of live WebSocket connections, by player. + +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Mutex; +use tokio::sync::mpsc::UnboundedSender; + +pub type ConnTx = UnboundedSender; + +#[derive(Default)] +pub struct Hub { + conns: Mutex>>, + next: AtomicU64, +} + +impl Hub { + pub fn register(&self, player_id: &str, tx: ConnTx) -> u64 { + let id = self.next.fetch_add(1, Ordering::Relaxed); + self.conns.lock().unwrap().entry(player_id.to_string()).or_default().push((id, tx)); + id + } + /// Register unless the player already has `max` live connections (`max == 0`: unlimited). + pub fn try_register(&self, player_id: &str, tx: ConnTx, max: usize) -> Option { + let mut g = self.conns.lock().unwrap(); + let v = g.entry(player_id.to_string()).or_default(); + v.retain(|(_, t)| !t.is_closed()); + if max > 0 && v.len() >= max { + if v.is_empty() { + g.remove(player_id); + } + return None; + } + let id = self.next.fetch_add(1, Ordering::Relaxed); + v.push((id, tx)); + Some(id) + } + /// Live connections of one player. + pub fn count(&self, player_id: &str) -> usize { + self.conns.lock().unwrap().get(player_id).map(|v| v.iter().filter(|(_, t)| !t.is_closed()).count()).unwrap_or(0) + } + /// Live connections of everybody. + pub fn total(&self) -> usize { + self.conns.lock().unwrap().values().map(|v| v.iter().filter(|(_, t)| !t.is_closed()).count()).sum() + } + pub fn unregister(&self, player_id: &str, conn_id: u64) { + let mut g = self.conns.lock().unwrap(); + if let Some(v) = g.get_mut(player_id) { + v.retain(|(i, _)| *i != conn_id); + if v.is_empty() { + g.remove(player_id); + } + } + } + pub fn connected(&self, player_id: &str) -> bool { + self.conns.lock().unwrap().get(player_id).map(|v| v.iter().any(|(_, t)| !t.is_closed())).unwrap_or(false) + } + /// Send a serialized envelope to every live connection of the player. + pub fn send(&self, player_id: &str, msg: &str) { + if let Some(v) = self.conns.lock().unwrap().get(player_id) { + for (_, tx) in v { + let _ = tx.send(msg.to_string()); + } + } + } +} diff --git a/arena/server/src/lib.rs b/arena/server/src/lib.rs new file mode 100644 index 00000000..f5326789 --- /dev/null +++ b/arena/server/src/lib.rs @@ -0,0 +1,151 @@ +//! Poker Sharingan arena table server. See README.md and docs/TABLE_API.md. + +pub mod api; +pub mod config; +pub mod deck; +pub mod error; +pub mod hand; +pub mod house; +pub mod hub; +pub mod limits; +pub mod matches; +pub mod model; +pub mod pgstore; +pub mod state; +pub mod stats; +pub mod store; +pub mod table; +pub mod util; +pub mod benchmarks; +pub mod webhook; +pub mod writer; +pub mod worker; +pub mod pipe_bot; +pub mod results; +pub mod ws; + +use config::ServerConfig; +use state::AppState; +use std::collections::HashMap; +use std::net::SocketAddr; +use std::sync::{Arc, RwLock}; + +pub fn build_state(cfg: ServerConfig) -> Result, String> { + let store: Arc = match &cfg.database_url { + Some(url) => Arc::new(pgstore::PgStore::open(url, cfg.database_schema.as_deref(), cfg.db_pool)?), + None => Arc::new(store::SqliteStore::open(&cfg.db_path).map_err(|e| e.to_string())?), + }; + let house = house::HouseRegistry::build(&cfg)?; + house.register_players(store.as_ref()).map_err(|e| e.to_string())?; + let n = store.abort_stale_matches().map_err(|e| e.to_string())?; + if n > 0 { + tracing::warn!("marked {n} stale running matches as aborted"); + } + let admin_token = cfg.admin_token.clone().unwrap_or_else(|| format!("adm_{}", util::random_hex())); + let (rate_rps, rate_burst, bots_per_day) = (cfg.rate_limit_rps, cfg.rate_limit_burst, cfg.bots_per_ip_per_day); + Ok(Arc::new(AppState { + cfg, + writer: writer::HandWriter::spawn(store.clone()), + store, + hub: Arc::new(hub::Hub::default()), + house: Arc::new(house), + admin_token, + limiter: limits::RateLimiter::new(rate_rps, rate_burst), + reg_limiter: limits::RateLimiter::new(bots_per_day / 86_400.0, bots_per_day), + human_reg_limiter: limits::RateLimiter::new(10.0 * bots_per_day / 86_400.0, 10.0 * bots_per_day), + lb_cache: Default::default(), + draining: std::sync::atomic::AtomicBool::new(false), + shutdown: tokio::sync::watch::channel(false).0, + tables: RwLock::new(HashMap::new()), + matches: RwLock::new(HashMap::new()), + })) +} + +pub struct RunningServer { + pub addr: SocketAddr, + pub app: Arc, + pub task: tokio::task::JoinHandle<()>, + stop: tokio::sync::watch::Sender, +} + +/// Bind and serve in the background (used by `main` and by the integration tests). +pub async fn start(cfg: ServerConfig) -> Result { + let bind = cfg.bind.clone(); + let app = build_state(cfg)?; + let listener = tokio::net::TcpListener::bind(&bind).await.map_err(|e| format!("bind {bind}: {e}"))?; + let addr = listener.local_addr().map_err(|e| e.to_string())?; + // Small frames per decision: Nagle + delayed ACK would add ~40 ms to every round trip. + use axum::serve::ListenerExt; + let listener = listener.tap_io(|tcp| { + let _ = tcp.set_nodelay(true); + }); + let router = api::router(app.clone()); + let (stop, mut stop_rx) = tokio::sync::watch::channel(false); + let task = tokio::spawn(async move { + let svc = router.into_make_service_with_connect_info::(); + let r = axum::serve(listener, svc) + .with_graceful_shutdown(async move { + let _ = stop_rx.wait_for(|v| *v).await; + }) + .await; + if let Err(e) = r { + tracing::error!("server error: {e}"); + } + }); + Ok(RunningServer { addr, app, task, stop }) +} + +impl RunningServer { + /// Graceful shutdown, in phases: + /// 1. drain: `/readyz` turns 503 and new tables, matches, runs and sockets are refused (503 `shutting_down`); + /// 2. wait up to `ARENA_SHUTDOWN_GRACE_MS` for running matches to finish (REST stays up so clients can read results); + /// 3. abort what is left (partial results are kept), flush hand histories to the database; + /// 4. close tables and sockets (close frame), stop accepting connections, wait for in-flight requests. + pub async fn shutdown(self) { + let app = self.app.clone(); + app.draining.store(true, std::sync::atomic::Ordering::SeqCst); + let grace = std::time::Duration::from_millis(app.cfg.shutdown_grace_ms); + let running = || -> Vec> { + app.matches + .read() + .unwrap() + .values() + .filter(|m| m.state.lock().unwrap().rec.status == "running") + .cloned() + .collect() + }; + let t0 = std::time::Instant::now(); + while !running().is_empty() && t0.elapsed() < grace { + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + } + let left = running(); + if !left.is_empty() { + tracing::warn!("shutdown: aborting {} unfinished matches", left.len()); + for rt in &left { + { + let mut s = rt.state.lock().unwrap(); + s.abort = true; + } + matches::wake_all(&app, rt); + } + let t1 = std::time::Instant::now(); + while !running().is_empty() && t1.elapsed() < std::time::Duration::from_secs(10) { + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + } + } + app.writer.flush().await; + let tables: Vec<_> = app.tables.read().unwrap().values().cloned().collect(); + for t in tables { + let _ = t.tx.send(table::TableCmd::Close); + t.wake.notify_one(); + } + let _ = app.shutdown.send(true); + let _ = self.stop.send(true); + let mut task = self.task; + if tokio::time::timeout(std::time::Duration::from_secs(5), &mut task).await.is_err() { + task.abort(); + } + app.writer.flush().await; + tracing::info!("shutdown complete"); + } +} diff --git a/arena/server/src/limits.rs b/arena/server/src/limits.rs new file mode 100644 index 00000000..25cafdcb --- /dev/null +++ b/arena/server/src/limits.rs @@ -0,0 +1,90 @@ +//! Abuse limits: a per-key token-bucket rate limiter (key = bearer token, else client IP). +//! Per-player caps (tables, matches, websockets) and size limits live next to the code they guard +//! and read their values from `ServerConfig`. + +use std::collections::HashMap; +use std::sync::Mutex; +use std::time::Instant; + +struct Bucket { + tokens: f64, + last: Instant, +} + +pub struct RateLimiter { + rps: f64, + burst: f64, + buckets: Mutex>, +} + +const MAX_KEYS: usize = 50_000; + +impl RateLimiter { + /// `rps <= 0` disables limiting. `burst` is the bucket size (at least 1). + pub fn new(rps: f64, burst: f64) -> Self { + RateLimiter { rps, burst: burst.max(1.0), buckets: Mutex::new(HashMap::new()) } + } + + pub fn enabled(&self) -> bool { + self.rps > 0.0 + } + + /// `Ok(())` if a request may proceed, else the number of milliseconds until one may. + pub fn check(&self, key: &str) -> Result<(), u64> { + if !self.enabled() { + return Ok(()); + } + let now = Instant::now(); + let mut g = self.buckets.lock().unwrap_or_else(|e| e.into_inner()); + if g.len() >= MAX_KEYS && !g.contains_key(key) { + // Forget buckets that have fully refilled; they carry no information. + let (rps, burst) = (self.rps, self.burst); + g.retain(|_, b| b.tokens + now.duration_since(b.last).as_secs_f64() * rps < burst); + if g.len() >= MAX_KEYS { + g.clear(); + } + } + let b = g.entry(key.to_string()).or_insert(Bucket { tokens: self.burst, last: now }); + b.tokens = (b.tokens + now.duration_since(b.last).as_secs_f64() * self.rps).min(self.burst); + b.last = now; + if b.tokens >= 1.0 { + b.tokens -= 1.0; + Ok(()) + } else { + Err((((1.0 - b.tokens) / self.rps) * 1000.0).ceil() as u64) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn burst_then_block_then_independent_keys() { + let l = RateLimiter::new(1.0, 3.0); + for _ in 0..3 { + assert!(l.check("a").is_ok()); + } + let wait = l.check("a").unwrap_err(); + assert!(wait > 0 && wait <= 1000, "{wait}"); + assert!(l.check("b").is_ok()); + } + + #[test] + fn refills_over_time() { + let l = RateLimiter::new(1000.0, 1.0); + assert!(l.check("a").is_ok()); + assert!(l.check("a").is_err()); + std::thread::sleep(std::time::Duration::from_millis(5)); + assert!(l.check("a").is_ok()); + } + + #[test] + fn zero_disables() { + let l = RateLimiter::new(0.0, 1.0); + for _ in 0..100 { + assert!(l.check("a").is_ok()); + } + } +} diff --git a/arena/server/src/main.rs b/arena/server/src/main.rs new file mode 100644 index 00000000..de156de7 --- /dev/null +++ b/arena/server/src/main.rs @@ -0,0 +1,65 @@ +use arena_server::config::ServerConfig; + +fn usage() -> ! { + eprintln!("usage: sharingan-arena [--port N] [--bind HOST:PORT] [--db PATH] [--database-url postgres://...] (env: see arena/server/README.md)\n sharingan-arena run --bot \"\" --track ladder-v1 ... (headless match worker, see `run --help`)"); + std::process::exit(2) +} + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + match args.first().map(|s| s.as_str()) { + Some("run") => std::process::exit(arena_server::worker::cli_run(args[1..].to_vec())), + Some("pipe-house") => std::process::exit(arena_server::pipe_bot::cli_pipe_house(args[1..].to_vec())), + _ => {} + } + tokio::runtime::Builder::new_multi_thread().enable_all().build().expect("tokio runtime").block_on(serve()); +} + +async fn serve() { + tracing_subscriber::fmt() + .with_env_filter(tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into())) + .init(); + let mut cfg = ServerConfig::from_env(); + let mut args = std::env::args().skip(1); + while let Some(a) = args.next() { + let mut val = || args.next().unwrap_or_else(|| usage()); + match a.as_str() { + "--port" => { + let p: u16 = val().parse().unwrap_or_else(|_| usage()); + let host = cfg.bind.rsplit_once(':').map(|x| x.0.to_string()).unwrap_or("127.0.0.1".into()); + cfg.bind = format!("{host}:{p}"); + } + "--bind" => cfg.bind = val(), + "--db" => cfg.db_path = val(), + "--database-url" => cfg.database_url = Some(val()), + _ => usage(), + } + } + let generated = cfg.admin_token.is_none(); + let srv = match arena_server::start(cfg).await { + Ok(s) => s, + Err(e) => { + eprintln!("error: {e}"); + std::process::exit(1); + } + }; + tracing::info!("sharingan-arena listening on http://{}", srv.addr); + if generated { + tracing::info!("admin token (generated, set ARENA_ADMIN_TOKEN to fix it): {}", srv.app.admin_token); + } + wait_for_signal().await; + tracing::info!("shutdown requested: draining (a second signal exits immediately)"); + tokio::select! { + _ = srv.shutdown() => {} + _ = wait_for_signal() => { tracing::warn!("second signal: exiting now"); } + } +} + +async fn wait_for_signal() { + use tokio::signal::unix::{signal, SignalKind}; + let mut term = signal(SignalKind::terminate()).expect("SIGTERM handler"); + tokio::select! { + _ = term.recv() => {} + _ = tokio::signal::ctrl_c() => {} + } +} diff --git a/arena/server/src/matches.rs b/arena/server/src/matches.rs new file mode 100644 index 00000000..1d18c9cb --- /dev/null +++ b/arena/server/src/matches.rs @@ -0,0 +1,618 @@ +//! Matches: a planned series of hands at one table, optionally duplicate (TABLE_API.md section 7). +//! +//! Duplicate schedule. Deal `i` has the deck `deal_deck(seed, i)` and its button at physical seat +//! `i mod 6`. In rotation `r` participant `p` sits in seat `(p + r) mod 6`, so every participant +//! plays every seat with the same cards. To keep a bot from recognising a repeated deal, deals +//! are played in blocks of `block_deals` (default 12): rotation 0 of every deal in the block, +//! then rotation 1 of the block, and so on. `hand_start` carries `deal_no` and `rotation`. + +use crate::model::*; +use crate::state::AppState; +use crate::stats::Builder; +use crate::store::Store; +use crate::util::*; +use bench::aivat::{EquityEstimator, Mode, Query, Scratch, Tracker, ValueEstimator}; +use bench::mix; +use bench::policy::{Event, Player, View}; +use nlhe::{Action, State, Step}; +use rayon::prelude::*; +use serde_json::{json, Value}; +use std::collections::HashMap; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::{Arc, Mutex}; + +#[derive(Clone, Debug)] +pub struct HandPlan { + pub hand_no: u32, + pub deal_no: Option, + pub rotation: Option, + /// `None` = choose the next button (free tables). + pub button: usize, + /// Player id per physical seat (matches reseat every hand). + pub assignment: Option>, + /// Physical seats dealt in. + pub dealt: Vec, + pub deck_index: u64, + pub crn_key: u64, + pub seed: String, + pub match_id: Option, + pub hide_cards: bool, +} + +pub enum MatchPoll { + Play(HandPlan), + Wait, + /// This lane has nothing left to play (`"finished"` or `"aborted"`). + Finished(&'static str), +} + +pub struct HandRec { + pub hand_no: u32, + pub nets: [i64; 6], +} + +pub struct MatchState { + pub rec: MatchRecord, + pub recs: Vec, + pub aivat: Option>, + pub abort: bool, + /// Hands played per lane. + pub cursors: Vec, +} + +/// Link from a match to the benchmark run it belongs to. +#[derive(Clone, Debug)] +pub struct BenchLink { + pub run_id: String, + pub track: String, + pub player_id: String, +} + +pub struct MatchRuntime { + pub id: String, + pub table_id: String, + pub table_ids: Vec, + pub participants: Vec, + pub duplicate: bool, + pub seed: String, + pub planned: u32, + pub block_deals: u32, + pub hide_cards: bool, + pub bb: i64, + pub names: HashMap, + pub lanes: usize, + pub bench: Option, + pub update_every: u32, + pub lane_done: AtomicU32, + pub state: Mutex, +} + +impl MatchRuntime { + pub fn new(rec: MatchRecord, names: HashMap, block_deals: u32, hide_cards: bool, bench: Option) -> Self { + let lanes = rec.table_ids.len().max(1); + let planned = rec.hands_planned; + MatchRuntime { + id: rec.match_id.clone(), + table_id: rec.table_id.clone(), + table_ids: rec.table_ids.clone(), + participants: rec.participants.clone(), + duplicate: rec.duplicate.is_some(), + seed: rec.seed.clone(), + planned, + block_deals: block_deals.max(1), + hide_cards, + bb: rec.table_config.big_blind, + names, + lanes, + update_every: if bench.is_some() { (planned / 100).max(50) } else { 50 }, + bench, + lane_done: AtomicU32::new(0), + state: Mutex::new(MatchState { rec, recs: Vec::new(), aivat: None, abort: false, cursors: vec![0; lanes] }), + } + } + + pub fn record(&self) -> MatchRecord { + self.state.lock().unwrap().rec.clone() + } + + /// Deal number and rotation of the `hand_no`-th hand (1-based). See [`locate`]. + fn locate(&self, hand_no: u32) -> (Option, u32) { + locate(self.duplicate, self.planned, self.block_deals, hand_no) + } + + /// The `c`-th (0-based) hand of a lane. See [`lane_hand_no`]. + fn lane_hand_no(&self, lane: usize, c: u32) -> Option { + lane_hand_no(self.duplicate, self.planned, self.block_deals, self.lanes, lane, c) + } + + /// Player at each physical seat for `hand_no` (participant `p` sits in seat `(p + r) mod 6`). + fn seat_players(&self, rotation: u32) -> impl Iterator + '_ { + (0..6usize).map(move |s| &self.participants[(s + 6 - rotation as usize) % 6]) + } + + pub fn plan_for(&self, hand_no: u32) -> HandPlan { + let (deal_no, r) = self.locate(hand_no); + let k = hand_no - 1; + let (button, deck_index, crn) = match deal_no { + Some(d) => ((d % 6) as usize, d as u64, d as u64), + None => ((k % 6) as usize, k as u64, hand_no as u64), + }; + HandPlan { + hand_no, + deal_no, + rotation: deal_no.map(|_| r), + button, + assignment: Some(self.seat_players(r).cloned().collect()), + dealt: (0..6).collect(), + deck_index, + crn_key: crn, + seed: self.seed.clone(), + match_id: Some(self.id.clone()), + hide_cards: self.hide_cards, + } + } + + pub fn poll(&self, lane: usize) -> MatchPoll { + let s = self.state.lock().unwrap(); + if s.abort { + return MatchPoll::Finished("aborted"); + } + let Some(h) = self.lane_hand_no(lane, s.cursors[lane]) else { return MatchPoll::Finished("finished") }; + if s.rec.status == "running" { + drop(s); + MatchPoll::Play(self.plan_for(h)) + } else { + MatchPoll::Wait + } + } + + /// Account a finished hand. Returns a `match_update` payload (and, for benchmark runs, a + /// progress payload) every `update_every` hands. + pub fn record_hand(&self, lane: usize, h: &HandHistory, store: &dyn Store) -> Option<(Value, Option)> { + let mut nets = [0i64; 6]; + for r in &h.results { + nets[r.seat as usize] = r.net; + } + let mut s = self.state.lock().unwrap(); + s.recs.push(HandRec { hand_no: h.hand_no, nets }); + s.cursors[lane] += 1; + s.rec.hands_played += 1; + let hp = s.rec.hands_played; + if hp % 100 == 0 { + let _ = store.put_match(&s.rec); + } + if hp % self.update_every == 0 { + let standings = self.build(&s).0; + let progress = self.bench.as_ref().map(|b| self.progress_value(b, &s, &standings)); + return Some((json!({"match_id": self.id, "hands_played": hp, "standings": standings}), progress)); + } + None + } + + fn progress_value(&self, b: &BenchLink, s: &MatchState, standings: &[Standing]) -> Value { + let me = standings.iter().find(|x| x.player_id == b.player_id); + json!({ + "run_id": b.run_id, "track": b.track, "match_id": self.id, "status": s.rec.status, + "hands_done": s.rec.hands_played, "hands_total": self.planned, + "mbb_per_game": me.map(|m| m.mbb_per_game), "ci95_mbb": me.map(|m| m.ci95_mbb), + "method": me.map(|m| m.method.clone()), "deals_done": me.map(|m| m.deals), + }) + } + + /// Live progress of a benchmark run. + pub fn progress(&self) -> Option { + let b = self.bench.as_ref()?; + let s = self.state.lock().unwrap(); + let st = self.build(&s).0; + Some(self.progress_value(b, &s, &st)) + } + + fn slot_keys(&self) -> Vec { + slot_keys_of(&self.participants) + } + + fn build(&self, s: &MatchState) -> (Vec, Vec<(String, StoredResult)>) { + build_standings(&self.slot_keys(), &self.participants, &self.names, self.bb, self.duplicate, self.planned, self.block_deals, &s.recs, s.aivat.as_ref()) + } + + pub fn standings(&self) -> Vec { + let s = self.state.lock().unwrap(); + self.build(&s).0 + } + + pub fn set_status(&self, status: &str) { + self.state.lock().unwrap().rec.status = status.to_string(); + } +} + +/// Deal number and rotation of the `hand_no`-th hand (1-based). Duplicate hands are numbered +/// block-major: within a block of `block_deals` deals, rotation 0 of every deal, then rotation 1, ... +/// Shared by the table server and the headless match worker (`worker.rs`). +pub fn locate(duplicate: bool, planned: u32, block_deals: u32, hand_no: u32) -> (Option, u32) { + if !duplicate { + return (None, 0); + } + let k = hand_no - 1; + let deals = planned / 6; + let b = block_deals; + let blk = k / (6 * b); + let within = k % (6 * b); + let blk_deals = b.min(deals - blk * b); + (Some(blk * b + within % blk_deals), within / blk_deals) +} + +/// The `c`-th (0-based) hand of a lane. Lane `L` of `N` plays blocks `L, L+N, L+2N, ...`. +pub fn lane_hand_no(duplicate: bool, planned: u32, block_deals: u32, lanes: usize, lane: usize, c: u32) -> Option { + if !duplicate { + return (c < planned).then_some(c + 1); + } + let deals = planned / 6; + let nblocks = (deals + block_deals - 1) / block_deals; + let (mut rem, mut b) = (c, lane as u32); + while b < nblocks { + let sz = 6 * block_deals.min(deals - b * block_deals); + if rem < sz { + return Some(b * 6 * block_deals + rem + 1); + } + rem -= sz; + b += lanes as u32; + } + None +} + +/// The `c`-th (0-based) hand of rotation `rot` for a lane (the headless worker plays rotation-major): lane `L` of `N` +/// plays rotation `rot` of the deals in blocks `L, L+N, ...`. Over one rotation every deal appears exactly once. +pub fn lane_rotation_hand_no(planned: u32, block_deals: u32, lanes: usize, lane: usize, rot: u32, c: u32) -> Option { + let deals = planned / 6; + let nblocks = (deals + block_deals - 1) / block_deals; + let (mut rem, mut b) = (c, lane as u32); + while b < nblocks { + let sz = block_deals.min(deals - b * block_deals); + if rem < sz { + return Some(b * 6 * block_deals + rot * sz + rem + 1); + } + rem -= sz; + b += lanes as u32; + } + None +} + +/// Standings from per-hand nets (and AIVAT-corrected payoffs when available). `keys` are the stats +/// keys per participant slot (see `MatchRuntime::slot_keys`). +#[allow(clippy::too_many_arguments)] +pub fn build_standings( + keys: &[String], + participants: &[String], + names: &HashMap, + bb: i64, + duplicate: bool, + planned: u32, + block_deals: u32, + recs: &[HandRec], + aivat: Option<&HashMap>, +) -> (Vec, Vec<(String, StoredResult)>) { + let mut b = Builder::new(bb, duplicate); + for rec in recs { + let (deal, r) = locate(duplicate, planned, block_deals, rec.hand_no); + let key = deal.unwrap_or(rec.hand_no); + b.add_hand(key); + let av = aivat.and_then(|m| m.get(&rec.hand_no)); + for seat in 0..6usize { + let slot = (seat + 6 - r as usize) % 6; + b.add(&keys[slot], key, rec.nets[seat], av.map(|a| a[seat])); + } + } + let names: HashMap = + keys.iter().enumerate().map(|(i, k)| (k.clone(), names.get(&participants[i]).cloned().unwrap_or_default())).collect(); + let (mut st, rows) = b.finish(&names); + for x in st.iter_mut() { + x.slot = keys.iter().position(|k| *k == x.player_id).unwrap_or(0) as u8; + if let Some((p, _)) = x.player_id.split_once('#') { + x.player_id = p.to_string(); + } + } + // stored results only for the first occurrence of each player id + let rows = rows.into_iter().filter(|(k, _)| !k.contains('#')).collect(); + (st, rows) +} + +/// Stats key per participant slot: the player id, with `#slot` on repeats (a house bot may fill +/// several seats), so every slot is scored separately and the first occurrence keeps the plain id. +pub fn slot_keys_of(participants: &[String]) -> Vec { + let mut seen: Vec<&String> = Vec::new(); + participants + .iter() + .enumerate() + .map(|(i, p)| { + if seen.contains(&p) { + format!("{p}#{i}") + } else { + seen.push(p); + p.clone() + } + }) + .collect() +} + +pub struct NewMatch { + pub owner: String, + pub cfg: TableConfig, + pub participants: Vec, + pub hands: u32, + pub duplicate: Option, + pub seed: String, + pub aivat: String, + pub block_deals: u32, + pub hide_cards: bool, + pub lanes: usize, + pub bench: Option, +} + +/// Register a match and spawn one table task per lane (lanes only apply to duplicate matches). +pub fn create(app: &Arc, n: NewMatch) -> crate::error::Res> { + let mut names = HashMap::new(); + for p in &n.participants { + let rec = app.store.get_player(p)?.ok_or_else(|| crate::error::ApiError::not_found(&format!("participant {p}")))?; + names.insert(rec.player_id.clone(), rec.name.clone()); + } + let block = n.block_deals.max(1); + let lanes = if n.duplicate.is_some() { + let blocks = ((n.hands / 6) + block - 1) / block; + n.lanes.clamp(1, 32).min(blocks.max(1) as usize) + } else { + 1 + }; + let table_ids: Vec = (0..lanes).map(|_| new_id("t")).collect(); + let mut cfg = n.cfg.clone(); + cfg.seed = None; + let rec = MatchRecord { + match_id: new_id("m"), + table_id: table_ids[0].clone(), + participants: n.participants.clone(), + hands_planned: n.hands, + duplicate: n.duplicate.clone(), + seed: n.seed.clone(), + status: "scheduled".into(), + hands_played: 0, + created_at: now_iso(), + started_at: None, + finished_at: None, + table_config: cfg.clone(), + aivat: n.aivat.clone(), + table_ids: table_ids.clone(), + lanes: lanes as u32, + run_id: n.bench.as_ref().map(|b| b.run_id.clone()), + }; + app.store.put_match(&rec)?; + let id = rec.match_id.clone(); + let rt = Arc::new(MatchRuntime::new(rec, names, block, n.hide_cards, n.bench)); + app.matches.write().unwrap().insert(id, rt.clone()); + for (lane, tid) in table_ids.into_iter().enumerate() { + crate::table::spawn_table(app, tid, n.owner.clone(), cfg.clone(), Some(rt.clone()), lane); + } + Ok(rt) +} + +/// Start (or resume) a scheduled/paused match and wake its lane tables. +pub fn start(app: &AppState, rt: &MatchRuntime) -> crate::error::Res<()> { + { + let mut s = rt.state.lock().unwrap(); + match s.rec.status.as_str() { + "scheduled" => { + s.rec.status = "running".into(); + s.rec.started_at = Some(now_iso()); + } + "paused" => s.rec.status = "running".into(), + "running" => {} + _ => return Err(crate::error::ApiError::conflict("match_not_running", format!("match is {}", s.rec.status))), + } + app.store.put_match(&s.rec)?; + } + wake_all(app, rt); + Ok(()) +} + +pub fn wake_all(app: &AppState, rt: &MatchRuntime) { + let tables = app.tables.read().unwrap(); + for id in &rt.table_ids { + if let Some(t) = tables.get(id) { + t.wake.notify_one(); + } + } +} + +/// A lane has run out of hands; the last lane to finish finalizes the match. +pub async fn lane_finished(app: Arc, rt: Arc, status: &'static str) { + if rt.lane_done.fetch_add(1, Ordering::SeqCst) + 1 == rt.lanes as u32 { + finalize(app, rt, status).await; + } +} + +/// End of a match: AIVAT pass, standings, stored results, final status. +pub async fn finalize(app: Arc, rt: Arc, status: &'static str) { + let t0 = std::time::Instant::now(); + app.writer.flush().await; + let (mode, played) = { + let s = rt.state.lock().unwrap(); + (s.rec.aivat.clone(), s.rec.hands_played) + }; + if played > 0 && mode != "off" { + let (a2, r2, m2) = (app.clone(), rt.clone(), mode.clone()); + match tokio::task::spawn_blocking(move || compute_aivat(&a2, &r2, &m2)).await { + Ok(Ok(m)) => rt.state.lock().unwrap().aivat = Some(m), + Ok(Err(e)) => tracing::error!("match {}: aivat failed: {e}", rt.id), + Err(e) => tracing::error!("match {}: aivat join: {e}", rt.id), + } + } + let (standings, rows, rec) = { + let mut s = rt.state.lock().unwrap(); + let (st, rows) = rt.build(&s); + s.rec.status = status.to_string(); + s.rec.finished_at = Some(now_iso()); + (st, rows, s.rec.clone()) + }; + tracing::info!("match {} finalized ({status}, {played} hands) in {:?}", rt.id, t0.elapsed()); + let rows: Vec = rows + .into_iter() + .map(|(_, mut r)| { + r.match_id = rt.id.clone(); + r + }) + .collect(); + if let Err(e) = app.store.put_results(&rt.id, &rows).and_then(|_| app.store.put_match(&rec)) { + tracing::error!("match {}: store results: {e}", rt.id); + } + app.leaderboard_changed(); + if let Some(b) = &rt.bench { + match app.store.get_run(&b.run_id) { + Ok(Some(mut run)) => { + let me = standings.iter().find(|x| x.player_id == b.player_id); + run.status = status.to_string(); + run.hands_done = played; + run.finished_at = rec.finished_at.clone(); + run.mbb_per_game = me.map(|m| m.mbb_per_game); + run.ci95_mbb = me.map(|m| m.ci95_mbb); + run.method = me.map(|m| m.method.clone()); + if let Err(e) = app.store.put_run(&run) { + tracing::error!("run {}: {e}", b.run_id); + } + app.leaderboard_changed(); + let prog = json!({"run_id": b.run_id, "track": b.track, "match_id": rt.id, "status": status, + "hands_done": played, "hands_total": rt.planned, "mbb_per_game": run.mbb_per_game, + "ci95_mbb": run.ci95_mbb, "method": run.method, "verified": run.verified}); + let env = json!({"v": 1, "type": "benchmark_progress", "t_ms": now_ms(), "data": prog}); + app.hub.send(&b.player_id, &env.to_string()); + } + Ok(None) => {} + Err(e) => tracing::error!("run {}: {e}", b.run_id), + } + } + let table = app.tables.read().unwrap().get(&rt.table_id).cloned(); + if let Some(t) = table { + t.emit(&app.hub, None, "match_update", None, None, json!({"match_id": rt.id, "status": status, "hands_played": played, "standings": standings})); + } +} + +fn compute_aivat(app: &AppState, rt: &MatchRuntime, mode: &str) -> Result, String> { + let mode = if mode == "cards" { Mode::CardsOnly } else { Mode::Full }; + let est = EquityEstimator::default(); + let mut out = HashMap::new(); + let mut after = 0u32; + loop { + let page = app.store.list_hands(&rt.id, after, 500).map_err(|e| e.to_string())?; + if page.is_empty() { + break; + } + after = page.last().unwrap().hand_no; + let res: Vec<(u32, Option<[f64; 6]>)> = + page.par_iter().map(|h| (h.hand_no, aivat_hand(&app.house, h, &est, mode))).collect(); + for (n, v) in res { + if let Some(v) = v { + out.insert(n, v); + } + } + } + Ok(out) +} + +/// Replay one stored hand through the bench AIVAT tracker. House bots that expose their action +/// probabilities get decision-node corrections; everyone gets chance-node corrections. +/// Returns the corrected payoff per physical seat. +pub fn aivat_hand(house: &crate::house::HouseRegistry, h: &HandHistory, est: &dyn ValueEstimator, mode: Mode) -> Option<[f64; 6]> { + let (ecfg, deal, order, actions) = crate::hand::replay_parts(h).ok()?; + let n = order.len(); + let seed = seed64(&h.hand_id); + let mut players: Vec>> = (0..n) + .map(|i| { + let pid = &h.players.iter().find(|p| p.seat as usize == order[i])?.player_id; + let key = house.key_of(pid)?; + let p = house.get(&key)?.new_player(i, &ecfg, mix(seed, i as u64)); + p.exposes_probs().then_some(p) + }) + .collect(); + let mut sc = Scratch::new(mix(seed, 2)); + let mut tr = Tracker::new(est, &mut sc, mode, deal); + let mut st = State::new(&ecfg); + tr.start(&st); + let mut len = 0usize; + let mut hist: Vec = Vec::new(); + for a in actions { + if st.is_terminal() { + return None; + } + let seat = st.to_act()?; + if let Some(p) = players[seat].as_mut() { + let view = View { cfg: &ecfg, state: &st, board: &deal.board[..len], history: &hist, seat }; + let d = p.dist(&view, deal.holes[seat]); + if let Some(i) = d.actions().iter().position(|x| *x == a) { + tr.decision(&st, len, &d, i); + } + } + let pre = st; + let street = st.street(); + let step = st.apply(a); + hist.push(Event { seat: seat as u8, street, action: a }); + for p in players.iter_mut().flatten() { + p.observe(&pre, seat, a); + } + let reveal = |to: usize, st: &State, len: &mut usize, tr: &mut Tracker, players: &mut Vec>>| { + tr.chance(st, *len, to); + *len = to; + for p in players.iter_mut().flatten() { + p.observe_board(&deal.board[..to]); + } + }; + match step { + Step::Continue => {} + Step::NewStreet(s) => reveal(s.board_len(), &st, &mut len, &mut tr, &mut players), + Step::Terminal => { + if st.showdown() { + while len < 5 { + let to = if len == 0 { 3 } else { len + 1 }; + reveal(to, &st, &mut len, &mut tr, &mut players); + } + } + } + } + } + if !st.is_terminal() { + return None; + } + let payoffs = st.payoffs(&deal); + let q = Query { state: &st, holes: &tr.deal.holes, board: &tr.deal.board[..len.max(if st.showdown() { 5 } else { 0 })] }; + let v = tr.est.value(&q, tr.sc); + let mut out = [0.0f64; 6]; + for i in 0..n { + let u = if st.showdown() || st.live_count() == 1 { v[i] } else { payoffs[i] as f64 }; + out[order[i]] = u + tr.corr[i]; + } + let _ = Action::Fold; + Some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rotation_major_lanes_cover_every_hand_once_and_never_repeat_a_deal_within_a_rotation() { + for (planned, lanes) in [(20_004u32, 4usize), (20_004, 8), (600, 3), (144, 2), (6, 1), (78, 5)] { + let mut seen = vec![false; planned as usize + 1]; + for rot in 0..6u32 { + let mut deals_this_rot = std::collections::HashSet::new(); + for lane in 0..lanes { + let mut c = 0; + while let Some(h) = lane_rotation_hand_no(planned, 12, lanes, lane, rot, c) { + c += 1; + assert!(!seen[h as usize], "hand {h} played twice"); + seen[h as usize] = true; + let (deal, r) = locate(true, planned, 12, h); + assert_eq!(r, rot, "hand {h} belongs to rotation {r}, not {rot}"); + assert!(deals_this_rot.insert(deal.unwrap()), "deal {deal:?} twice in rotation {rot}"); + } + } + } + assert!(seen[1..].iter().all(|&x| x), "{planned}/{lanes}: every hand is played"); + } + } +} diff --git a/arena/server/src/model.rs b/arena/server/src/model.rs new file mode 100644 index 00000000..05fedc78 --- /dev/null +++ b/arena/server/src/model.rs @@ -0,0 +1,429 @@ +//! Wire and storage types (TABLE_API.md sections 2, 5, 8, 9). Chips are integers. + +use crate::error::{ApiError, Res}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +fn d_variant() -> String { + "nlhe".into() +} +fn d_seats() -> u8 { + 6 +} +fn d_sb() -> i64 { + 50 +} +fn d_bb() -> i64 { + 100 +} +fn d_stack() -> i64 { + 10_000 +} +fn d_time() -> u64 { + 5000 +} +fn d_timeout_action() -> String { + "check_fold".into() +} +fn d_min_players() -> u8 { + 6 +} +fn d_odd() -> String { + "first_left_of_button".into() +} +fn d_show() -> String { + "standard".into() +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Default)] +#[serde(rename_all = "snake_case")] +pub enum StackMode { + #[default] + Reset, + Carry, +} + +#[derive(Clone, Debug, Serialize, Deserialize, Default)] +pub struct Rake { + #[serde(default)] + pub percent: u32, + #[serde(default)] + pub cap: u32, +} + +/// Scripted dealing for `mode:"sandbox"` tables (conformance vectors). +#[derive(Clone, Debug, Serialize, Deserialize, Default)] +pub struct Sandbox { + /// Deck prefixes, one per hand in order (e.g. `["Ah","Kd",...]`); the rest of each deck follows the seeded order. + #[serde(default)] + pub decks: Vec>, + /// Fixed button seat for every hand. + #[serde(default)] + pub button_seat: Option, + /// Starting stacks per seat for the first hand only (stack_mode reset otherwise applies). + #[serde(default)] + pub stacks: Option>, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct TableConfig { + #[serde(default = "d_variant")] + pub variant: String, + #[serde(default = "d_seats")] + pub max_seats: u8, + #[serde(default = "d_sb")] + pub small_blind: i64, + #[serde(default = "d_bb")] + pub big_blind: i64, + #[serde(default)] + pub ante: i64, + #[serde(default)] + pub straddle: bool, + #[serde(default = "d_stack")] + pub starting_stack: i64, + #[serde(default)] + pub stack_mode: StackMode, + #[serde(default = "d_time")] + pub decision_time_ms: u64, + #[serde(default)] + pub time_bank_ms: u64, + #[serde(default = "d_timeout_action")] + pub timeout_action: String, + #[serde(default)] + pub rake: Rake, + #[serde(default = "d_min_players")] + pub min_players_to_deal: u8, + #[serde(default = "d_odd")] + pub odd_chip_rule: String, + #[serde(default = "d_show")] + pub show_mode: String, + /// `"sandbox"` enables scripted decks; omitted/`"normal"` otherwise. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mode: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub sandbox: Option, + /// Table seed (free tables); matches use the match seed. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub seed: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, + /// Pause between hands on free tables (default from server config). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub hand_delay_ms: Option, +} + +impl Default for TableConfig { + fn default() -> Self { + serde_json::from_value(serde_json::json!({})).unwrap() + } +} + +impl TableConfig { + pub fn validate(&self) -> Res<()> { + let bad = |m: &str| Err(ApiError::bad_request(m.to_string())); + if self.variant != "nlhe" { + return bad("variant must be nlhe"); + } + if !(2..=6).contains(&self.max_seats) { + return bad("max_seats must be 2..6"); + } + if self.small_blind <= 0 || self.big_blind < self.small_blind { + return bad("blinds must satisfy 0 < small_blind <= big_blind"); + } + if self.ante != 0 || self.straddle { + return bad("ante and straddle are not supported (ante=0, straddle=false)"); + } + if self.starting_stack < self.big_blind || self.starting_stack > 1_000_000_000 { + return bad("starting_stack must be in [big_blind, 1e9]"); + } + if self.rake.percent != 0 || self.rake.cap != 0 { + return bad("rake is not supported"); + } + if self.timeout_action != "check_fold" { + return bad("timeout_action must be check_fold"); + } + if self.decision_time_ms == 0 || self.decision_time_ms > 3_600_000 { + return bad("decision_time_ms must be in 1..3600000"); + } + if self.min_players_to_deal < 2 || self.min_players_to_deal > self.max_seats { + return bad("min_players_to_deal must be in 2..max_seats"); + } + if let Some(m) = &self.mode { + if m != "sandbox" && m != "ranked" && m != "benchmark" && m != "normal" { + return bad("mode must be sandbox, ranked or benchmark"); + } + } + if self.sandbox.is_some() && !self.is_sandbox() { + return bad("sandbox options require mode=sandbox"); + } + Ok(()) + } + pub fn is_benchmark(&self) -> bool { + self.mode.as_deref() == Some("benchmark") + } + pub fn is_sandbox(&self) -> bool { + self.mode.as_deref() == Some("sandbox") + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct DuplicateConfig { + pub enabled: bool, + #[serde(default = "d_rot")] + pub rotations: u8, + #[serde(default = "d_deck_from")] + pub deck_from: String, +} +fn d_rot() -> u8 { + 6 +} +fn d_deck_from() -> String { + "seed".into() +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct PlayerRecord { + pub player_id: String, + pub name: String, + pub kind: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub owner: Option, + pub created_at: String, + #[serde(default)] + pub house: bool, + #[serde(skip)] + pub token_hash: String, + #[serde(skip)] + pub webhook_url: Option, + #[serde(skip)] + pub webhook_secret: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct MatchRecord { + pub match_id: String, + pub table_id: String, + pub participants: Vec, + pub hands_planned: u32, + pub duplicate: Option, + pub seed: String, + pub status: String, + pub hands_played: u32, + pub created_at: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub started_at: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub finished_at: Option, + pub table_config: TableConfig, + /// "full" | "cards" | "off" + pub aivat: String, + /// One table per lane; lanes play disjoint blocks of deals in parallel. + #[serde(default)] + pub table_ids: Vec, + #[serde(default)] + pub lanes: u32, + /// Set for benchmark-track runs. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub run_id: Option, +} + +/// A benchmark-track run of one bot against a frozen panel. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct RunRecord { + pub run_id: String, + pub track: String, + pub panel_version: String, + pub panel: Vec, + pub player_id: String, + pub name: String, + pub match_id: String, + pub seed: String, + /// Hosted worker results only: `"frozen"` (played on the track's public seed) or `"fresh"` (a secret per-run seed + /// the bot could not know in advance). Absent on server-played runs (always the track seed). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub deals: Option, + pub hands_planned: u32, + pub hands_done: u32, + /// "running" | "finished" | "aborted" + pub status: String, + /// True only when the server itself ran the bot (house/hosted bots); remote bots are unverified. + pub verified: bool, + /// Set by the trusted runner (`ARENA_RUNNER_TOKEN`): the bot ran on infrastructure the arena operator controls. + #[serde(default)] + pub hosted: bool, + pub mbb_per_game: Option, + pub ci95_mbb: Option, + pub method: Option, + pub blueprint_fingerprint: Option, + pub created_at: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub finished_at: Option, +} + +#[derive(Clone, Debug, Serialize)] +pub struct VsCell { + pub mbb: f64, + pub ci95_mbb: f64, + pub hands: u32, +} + +#[derive(Clone, Debug, Serialize)] +pub struct TrackCell { + pub run_id: String, + pub mbb_per_game: f64, + pub ci95_mbb: f64, + pub hands: u32, + pub verified: bool, + pub method: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct ActionEvent { + pub hand_id: String, + pub seq: u32, + pub action_id: String, + pub street: String, + pub seat: u8, + #[serde(rename = "type")] + pub kind: String, + pub to: i64, + pub added: i64, + pub all_in: bool, + pub forced: bool, + pub timeout: bool, + pub stack: i64, + pub pot: i64, + pub current_bet: i64, + pub min_raise_to: i64, + pub next_to_act: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct PotResult { + pub amount: i64, + pub eligible_seats: Vec, + pub winners: Vec, + pub share: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct ResultRow { + pub seat: u8, + pub player_id: String, + pub net: i64, + pub stack_end: i64, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct HistPlayer { + pub seat: u8, + pub player_id: String, + pub name: String, + pub kind: String, + pub stack_start: i64, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct HistConfig { + pub small_blind: i64, + pub big_blind: i64, + pub ante: i64, + pub starting_stack: i64, + pub stack_mode: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct HandHistory { + pub hand_id: String, + pub hand_no: u32, + pub match_id: Option, + pub table_id: String, + pub deal_no: Option, + pub rotation: Option, + pub started_at: String, + pub ended_at: String, + pub config: HistConfig, + pub button_seat: u8, + pub sb_seat: u8, + pub bb_seat: u8, + pub players: Vec, + pub hole_cards: BTreeMap, + pub board: Vec, + pub runout: Vec, + pub deck: Vec, + pub deck_salt: String, + pub actions: Vec, + pub decision_times_ms: BTreeMap, + pub pots: Vec, + pub results: Vec, + pub ended_by: String, + pub anomalies: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Standing { + pub player_id: String, + /// Participant slot (a house bot may fill several). + #[serde(default)] + pub slot: u8, + pub name: String, + pub hands: u64, + pub net_chips: i64, + pub bb_per_100: f64, + pub mbb_per_hand: f64, + pub ci95_bb_per_100: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub duplicate_bb_per_100: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub duplicate_mbb_per_hand: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub duplicate_ci95_mbb_per_hand: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub aivat_mbb_per_hand: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub aivat_ci95_mbb_per_hand: Option, + /// How `score_mbb_per_hand` was produced: "aivat" | "duplicate" | "raw". + pub method: String, + pub score_mbb_per_hand: f64, + pub score_ci95_mbb_per_hand: f64, + /// Same as `score_mbb_per_hand` / `score_ci95_mbb_per_hand` (SDK-facing names). + pub mbb_per_game: f64, + pub ci95_mbb: f64, + pub deals: u64, +} + +/// One stored per-match, per-player result (feeds the leaderboard). +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct StoredResult { + pub match_id: String, + pub player_id: String, + pub hands: u64, + pub deals: u64, + pub net_chips: i64, + pub score_mbb: f64, + pub se_mbb: f64, + pub method: String, +} + +#[derive(Clone, Debug, Serialize)] +pub struct LeaderboardRow { + pub rank: usize, + pub player_id: String, + pub name: String, + pub house: bool, + pub matches: u64, + pub hands: u64, + /// General (all matches) luck-corrected score; null if the bot has not reached the hands threshold. + pub score_mbb_per_hand: Option, + pub ci95_mbb_per_hand: Option, + pub score_bb_per_100: Option, + pub methods: Vec, + /// Blended mbb/game vs the `ladder-v1` panel (latest finished run), if any. + pub vs_ladder_v1: Option, + /// Same for the `sharingan-1` panel. + pub vs_sharingan_1: Option, + /// True if the displayed track results were run by the server itself (house/hosted bots). + pub verified: bool, + /// One cell per benchmark track (latest finished run). + pub tracks: std::collections::BTreeMap, +} diff --git a/arena/server/src/pgstore.rs b/arena/server/src/pgstore.rs new file mode 100644 index 00000000..c34ce493 --- /dev/null +++ b/arena/server/src/pgstore.rs @@ -0,0 +1,357 @@ +//! Postgres implementation of [`Store`], selected by `ARENA_DATABASE_URL=postgres://...`. +//! +//! The `Store` trait is synchronous (like the SQLite one). The blocking `postgres` client owns an +//! internal tokio runtime and must not be called from a tokio worker thread, so every connection +//! lives on its own plain OS thread and callers hand it a closure over a channel (a small fixed pool, +//! `ARENA_DB_POOL`, default 8). Callers block until the reply arrives, exactly as they do on SQLite's mutex. +//! +//! Migrations are embedded (`migrations/*.sql`), applied in order under an advisory lock and +//! recorded in `arena_migrations`, so several server replicas can start against one database. +//! `ARENA_DATABASE_SCHEMA` puts all tables in a named schema (used by the tests for isolation). + +use crate::error::{ApiError, Res}; +use crate::model::*; +use crate::store::{parse, Store}; +use postgres::types::ToSql; +use postgres::{Client, Config, NoTls}; +use serde_json::Value; +use std::sync::mpsc::{channel, sync_channel, Receiver, Sender}; +use std::sync::{Arc, Mutex}; + +type Job = Box; + +pub struct PgStore { + tx: Sender, +} + +/// Embedded migrations, in order. Never edit an applied one; append a new file. +const MIGRATIONS: &[(i32, &str, &str)] = &[(1, "init", include_str!("../migrations/0001_init.sql"))]; + +impl From for ApiError { + fn from(e: postgres::Error) -> Self { + ApiError::internal(format!("storage: {e}")) + } +} + +fn connect(cfg: &Config) -> Result { + if matches!(cfg.get_ssl_mode(), postgres::config::SslMode::Disable) { + return cfg.connect(NoTls).map_err(|e| e.to_string()); + } + let roots = rustls::RootCertStore { roots: webpki_roots::TLS_SERVER_ROOTS.to_vec() }; + let tls = rustls::ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider())) + .with_safe_default_protocol_versions() + .map_err(|e| e.to_string())? + .with_root_certificates(roots) + .with_no_client_auth(); + cfg.connect(tokio_postgres_rustls::MakeRustlsConnect::new(tls)).map_err(|e| e.to_string()) +} + +impl PgStore { + pub fn open(url: &str, schema: Option<&str>, pool: usize) -> Result { + let mut cfg: Config = url.parse().map_err(|e: postgres::Error| format!("ARENA_DATABASE_URL: {e}"))?; + if let Some(s) = schema { + if s.is_empty() || !s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { + return Err("ARENA_DATABASE_SCHEMA must match [A-Za-z0-9_]+".into()); + } + // Create the schema over a throwaway connection, then pin every pooled connection to it. + let url2 = url.to_string(); + let s2 = s.to_string(); + std::thread::spawn(move || -> Result<(), String> { + let c: Config = url2.parse().map_err(|e: postgres::Error| e.to_string())?; + let mut cl = connect(&c)?; + cl.batch_execute(&format!("CREATE SCHEMA IF NOT EXISTS \"{s2}\"")).map_err(|e| e.to_string()) + }) + .join() + .map_err(|_| "schema thread panicked".to_string())??; + cfg.options(&format!("-c search_path={s}")); + } + let (tx, rx) = channel::(); + let rx: Arc>> = Arc::new(Mutex::new(rx)); + let n = pool.clamp(1, 64); + let (ready_tx, ready_rx) = sync_channel::>(n); + for i in 0..n { + let (rx, cfg, ready) = (rx.clone(), cfg.clone(), ready_tx.clone()); + std::thread::Builder::new() + .name(format!("pg-{i}")) + .spawn(move || { + let mut client = match connect(&cfg) { + Ok(c) => { + let _ = ready.send(Ok(())); + c + } + Err(e) => { + let _ = ready.send(Err(e)); + return; + } + }; + loop { + let job = { rx.lock().unwrap_or_else(|e| e.into_inner()).recv() }; + match job { + Ok(j) => j(&mut client), + Err(_) => break, + } + } + }) + .map_err(|e| e.to_string())?; + } + for _ in 0..n { + ready_rx.recv().map_err(|_| "postgres worker died".to_string())?.map_err(|e| format!("postgres connect: {e}"))?; + } + let st = PgStore { tx }; + st.run(migrate).map_err(|e| format!("postgres migrate: {e}"))?; + Ok(st) + } + + fn run(&self, f: impl FnOnce(&mut Client) -> Res + Send + 'static) -> Res { + let (rtx, rrx) = sync_channel(1); + self.tx + .send(Box::new(move |c| { + let _ = rtx.send(f(c)); + })) + .map_err(|_| ApiError::internal("storage: pool closed"))?; + rrx.recv().map_err(|_| ApiError::internal("storage: worker died"))? + } +} + +fn migrate(c: &mut Client) -> Res<()> { + let mut tx = c.transaction()?; + tx.batch_execute("SELECT pg_advisory_xact_lock(727274001)")?; + tx.batch_execute("CREATE TABLE IF NOT EXISTS arena_migrations(version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at TIMESTAMPTZ NOT NULL DEFAULT now())")?; + for (v, name, sql) in MIGRATIONS { + let done = tx.query_opt("SELECT 1 FROM arena_migrations WHERE version=$1", &[v])?.is_some(); + if !done { + tx.batch_execute(sql)?; + tx.execute("INSERT INTO arena_migrations(version,name) VALUES($1,$2)", &[v, name])?; + tracing::info!("postgres: applied migration {v:04} {name}"); + } + } + tx.commit()?; + Ok(()) +} + +const PCOLS: &str = "player_id,name,kind,owner,house,token_hash,webhook_url,webhook_secret,created_at"; +const RCOLS: &str = "match_id,player_id,hands,deals,net_chips,score_mbb,se_mbb,method"; + +fn player_from_row(r: &postgres::Row) -> PlayerRecord { + PlayerRecord { + player_id: r.get(0), + name: r.get(1), + kind: r.get(2), + owner: r.get(3), + house: r.get(4), + token_hash: r.get(5), + webhook_url: r.get(6), + webhook_secret: r.get(7), + created_at: r.get(8), + } +} + +fn result_from_row(r: &postgres::Row) -> StoredResult { + StoredResult { + match_id: r.get(0), + player_id: r.get(1), + hands: r.get::<_, i64>(2) as u64, + deals: r.get::<_, i64>(3) as u64, + net_chips: r.get(4), + score_mbb: r.get(5), + se_mbb: r.get(6), + method: r.get(7), + } +} + +fn texts(rows: Vec) -> Vec { + rows.iter().map(|r| r.get::<_, String>(0)).collect() +} + +impl Store for PgStore { + fn ping(&self) -> Res<()> { + self.run(|c| c.query_one("SELECT 1", &[]).map(|_| ()).map_err(Into::into)) + } + + fn put_player(&self, p: &PlayerRecord) -> Res<()> { + let p = p.clone(); + self.run(move |c| { + c.execute( + "INSERT INTO players(player_id,name,kind,owner,house,token_hash,webhook_url,webhook_secret,created_at) + VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9) + ON CONFLICT(player_id) DO UPDATE SET name=$2,kind=$3,owner=$4,house=$5,token_hash=$6,webhook_url=$7,webhook_secret=$8", + &[&p.player_id, &p.name, &p.kind, &p.owner, &p.house, &p.token_hash, &p.webhook_url, &p.webhook_secret, &p.created_at], + )?; + Ok(()) + }) + } + fn get_player(&self, id: &str) -> Res> { + let id = id.to_string(); + self.run(move |c| Ok(c.query_opt(&format!("SELECT {PCOLS} FROM players WHERE player_id=$1"), &[&id])?.as_ref().map(player_from_row))) + } + fn player_by_token_hash(&self, hash: &str) -> Res> { + if hash.is_empty() { + return Ok(None); + } + let h = hash.to_string(); + self.run(move |c| Ok(c.query_opt(&format!("SELECT {PCOLS} FROM players WHERE token_hash=$1"), &[&h])?.as_ref().map(player_from_row))) + } + fn list_players(&self, limit: u32) -> Res> { + self.run(move |c| { + let rows = c.query(&format!("SELECT {PCOLS} FROM players ORDER BY created_seq LIMIT $1"), &[&(limit as i64)])?; + Ok(rows.iter().map(player_from_row).collect()) + }) + } + + fn put_match(&self, m: &MatchRecord) -> Res<()> { + let body = serde_json::to_string(m)?; + let (id, status) = (m.match_id.clone(), m.status.clone()); + self.run(move |c| { + c.execute( + "INSERT INTO matches(match_id,status,body) VALUES($1,$2,$3) ON CONFLICT(match_id) DO UPDATE SET status=$2, body=$3", + &[&id, &status, &body], + )?; + Ok(()) + }) + } + fn get_match(&self, id: &str) -> Res> { + let id = id.to_string(); + let s = self.run(move |c| Ok(c.query_opt("SELECT body FROM matches WHERE match_id=$1", &[&id])?.map(|r| r.get::<_, String>(0))))?; + s.map(parse).transpose() + } + fn list_matches(&self, limit: u32) -> Res> { + let rows = self.run(move |c| Ok(texts(c.query("SELECT body FROM matches ORDER BY created_seq DESC LIMIT $1", &[&(limit as i64)])?)))?; + rows.into_iter().map(parse).collect() + } + fn abort_stale_matches(&self) -> Res { + let ids = self.run(|c| Ok(texts(c.query("SELECT match_id FROM matches WHERE status IN ('scheduled','running','paused')", &[])?)))?; + for id in &ids { + if let Some(mut m) = self.get_match(id)? { + m.status = "aborted".into(); + self.put_match(&m)?; + } + } + Ok(ids.len() as u64) + } + + fn append_hand(&self, h: &HandHistory, events: &[Value]) -> Res<()> { + self.append_hands(&[(h.clone(), events.to_vec())]) + } + fn append_hands(&self, items: &[(HandHistory, Vec)]) -> Res<()> { + let mut rows = Vec::with_capacity(items.len()); + for (h, e) in items { + let ev = if e.is_empty() { "[]".to_string() } else { serde_json::to_string(e)? }; + rows.push((h.hand_id.clone(), h.match_id.clone(), h.hand_no as i64, serde_json::to_string(h)?, ev)); + } + self.run(move |c| { + let mut tx = c.transaction()?; + let st = tx.prepare( + "INSERT INTO hands(hand_id,match_id,hand_no,body,events) VALUES($1,$2,$3,$4,$5) + ON CONFLICT(hand_id) DO UPDATE SET match_id=$2,hand_no=$3,body=$4,events=$5", + )?; + for r in &rows { + tx.execute(&st, &[&r.0, &r.1, &r.2, &r.3, &r.4])?; + } + tx.commit()?; + Ok(()) + }) + } + fn get_hand(&self, id: &str) -> Res> { + let id = id.to_string(); + let s = self.run(move |c| Ok(c.query_opt("SELECT body FROM hands WHERE hand_id=$1", &[&id])?.map(|r| r.get::<_, String>(0))))?; + s.map(parse).transpose() + } + fn get_hand_events(&self, id: &str) -> Res>> { + let id = id.to_string(); + let s = self.run(move |c| Ok(c.query_opt("SELECT events FROM hands WHERE hand_id=$1", &[&id])?.map(|r| r.get::<_, String>(0))))?; + s.map(parse).transpose() + } + fn list_hands(&self, match_id: &str, after: u32, limit: u32) -> Res> { + let m = match_id.to_string(); + let rows = self.run(move |c| { + Ok(texts(c.query("SELECT body FROM hands WHERE match_id=$1 AND hand_no>$2 ORDER BY hand_no LIMIT $3", &[&m, &(after as i64), &(limit as i64)])?)) + })?; + rows.into_iter().map(parse).collect() + } + fn count_hands(&self, match_id: &str) -> Res { + let m = match_id.to_string(); + self.run(move |c| Ok(c.query_one("SELECT COUNT(*) FROM hands WHERE match_id=$1", &[&m])?.get::<_, i64>(0) as u64)) + } + + fn put_run(&self, r: &RunRecord) -> Res<()> { + let body = serde_json::to_string(r)?; + let (id, track, pid) = (r.run_id.clone(), r.track.clone(), r.player_id.clone()); + self.run(move |c| { + c.execute( + "INSERT INTO benchmark_runs(run_id,track,player_id,body) VALUES($1,$2,$3,$4) ON CONFLICT(run_id) DO UPDATE SET body=$4", + &[&id, &track, &pid, &body], + )?; + Ok(()) + }) + } + fn get_run(&self, id: &str) -> Res> { + let id = id.to_string(); + let s = self.run(move |c| Ok(c.query_opt("SELECT body FROM benchmark_runs WHERE run_id=$1", &[&id])?.map(|r| r.get::<_, String>(0))))?; + s.map(parse).transpose() + } + fn list_runs(&self, track: Option<&str>, player_id: Option<&str>, limit: u32) -> Res> { + let (t, p) = (track.map(str::to_string), player_id.map(str::to_string)); + let rows = self.run(move |c| { + let args: [&(dyn ToSql + Sync); 3] = [&t, &p, &(limit as i64)]; + Ok(texts(c.query( + "SELECT body FROM benchmark_runs WHERE ($1::text IS NULL OR track=$1) AND ($2::text IS NULL OR player_id=$2) ORDER BY created_seq DESC LIMIT $3", + &args, + )?)) + })?; + rows.into_iter().map(parse).collect() + } + + fn put_results(&self, match_id: &str, rows: &[StoredResult]) -> Res<()> { + let m = match_id.to_string(); + let rows = rows.to_vec(); + self.run(move |c| { + let mut tx = c.transaction()?; + tx.execute("DELETE FROM match_results WHERE match_id=$1", &[&m])?; + for r in &rows { + tx.execute( + "INSERT INTO match_results(match_id,player_id,hands,deals,net_chips,score_mbb,se_mbb,method) VALUES($1,$2,$3,$4,$5,$6,$7,$8)", + &[&r.match_id, &r.player_id, &(r.hands as i64), &(r.deals as i64), &r.net_chips, &r.score_mbb, &r.se_mbb, &r.method], + )?; + } + tx.commit()?; + Ok(()) + }) + } + fn all_results(&self) -> Res> { + self.run(|c| Ok(c.query(&format!("SELECT {RCOLS} FROM match_results"), &[])?.iter().map(result_from_row).collect())) + } + fn results_of_player(&self, player_id: &str) -> Res> { + let p = player_id.to_string(); + self.run(move |c| Ok(c.query(&format!("SELECT {RCOLS} FROM match_results WHERE player_id=$1"), &[&p])?.iter().map(result_from_row).collect())) + } + + fn delete_match_data(&self, match_id: &str) -> Res<()> { + let m = match_id.to_string(); + self.run(move |c| { + let mut tx = c.transaction()?; + tx.execute("DELETE FROM hands WHERE match_id=$1", &[&m])?; + tx.execute("DELETE FROM match_results WHERE match_id=$1", &[&m])?; + tx.execute("DELETE FROM matches WHERE match_id=$1", &[&m])?; + tx.commit()?; + Ok(()) + }) + } + fn delete_run(&self, run_id: &str) -> Res<()> { + let r = run_id.to_string(); + self.run(move |c| { + c.execute("DELETE FROM benchmark_runs WHERE run_id=$1", &[&r])?; + Ok(()) + }) + } + fn delete_player(&self, player_id: &str) -> Res<()> { + let p = player_id.to_string(); + self.run(move |c| { + let mut tx = c.transaction()?; + tx.execute("DELETE FROM match_results WHERE player_id=$1", &[&p])?; + tx.execute("DELETE FROM benchmark_runs WHERE player_id=$1", &[&p])?; + tx.execute("DELETE FROM players WHERE player_id=$1", &[&p])?; + tx.commit()?; + Ok(()) + }) + } +} diff --git a/arena/server/src/pipe_bot.rs b/arena/server/src/pipe_bot.rs new file mode 100644 index 00000000..e4c0d1e8 --- /dev/null +++ b/arena/server/src/pipe_bot.rs @@ -0,0 +1,137 @@ +//! `sharingan-arena pipe-house `: a house bot (random, calling_station, tight_aggressive, ..., +//! sharingan-1 with ARENA_BLUEPRINT) that speaks the PIPE protocol (TABLE_API.md section 14) on +//! stdin/stdout. It rebuilds the engine state from each `your_turn` (players + history), so it is a +//! faithful reference implementation of a stateless pipe bot and the "Rust house bot" of the +//! throughput benchmark: `sharingan-arena run --bot "sharingan-arena pipe-house tight_aggressive" ...`. + +use crate::config::ServerConfig; +use crate::house::HouseRegistry; +use crate::util::seed64; +use bench::mix; +use bench::policy::{Event, View}; +use nlhe::{Action, GameConfig, State, Step}; +use serde_json::{json, Value}; +use std::io::{BufRead, Write}; + +fn parse_action(kind: &str, to: i64) -> Action { + match kind { + "fold" => Action::Fold, + "check" => Action::Check, + "call" => Action::Call, + _ => Action::RaiseTo(to as i32), + } +} + +/// Decide a `your_turn` `data` object; returns the `act` data. +pub fn decide(house: &HouseRegistry, key: &str, data: &Value) -> Option { + let factory = house.get(key)?; + let hand_id = data["hand_id"].as_str().unwrap_or(""); + let players = data["players"].as_array()?; + let n = players.len(); + let button = data["button_seat"].as_u64()? as usize; + let me = data["seat"].as_u64()? as usize; + let occupied: Vec = players.iter().filter_map(|p| p["seat"].as_u64().map(|s| s as usize)).collect(); + let order: Vec = if n == 2 { + vec![button, *occupied.iter().find(|&&s| s != button)?] + } else { + (1..=6).map(|k| (button + k) % 6).filter(|s| occupied.contains(s)).collect() + }; + let stack_of = |seat: usize| players.iter().find(|p| p["seat"].as_u64() == Some(seat as u64)).and_then(|p| p["stack_start"].as_i64()).unwrap_or(0); + let stacks: Vec = order.iter().map(|&s| stack_of(s) as i32).collect(); + let ecfg = GameConfig { + players: n, + stack: stacks.iter().copied().max().unwrap_or(10_000), + small_blind: data["small_blind"].as_i64()? as i32, + big_blind: data["big_blind"].as_i64()? as i32, + stacks: None, + ..GameConfig::new(2) + } + .with_stacks(&stacks); + let idx = order.iter().position(|&s| s == me)?; + let board: Vec = data["board"].as_array()?.iter().filter_map(|c| c.as_str().and_then(cards::parse_card)).collect(); + let hc = data["hole_cards"].as_array()?; + let hole = [cards::parse_card(hc.first()?.as_str()?)?, cards::parse_card(hc.get(1)?.as_str()?)?]; + let hseed = seed64(hand_id); + let mut p = factory.new_player(idx, &ecfg, mix(hseed, idx as u64)); + let mut st = State::new(&ecfg); + let mut hist: Vec = Vec::new(); + for a in data["history"].as_array()? { + if a["forced"].as_bool() == Some(true) { + continue; + } + let seat = a["seat"].as_u64()? as usize; + let ai = order.iter().position(|&s| s == seat)?; + if st.to_act() != Some(ai) { + return None; + } + let act = parse_action(a["type"].as_str()?, a["to"].as_i64().unwrap_or(0)); + let pre = st; + let street = st.street(); + let step = st.apply(act); + hist.push(Event { seat: ai as u8, street, action: act }); + p.observe(&pre, ai, act); + if let Step::NewStreet(s) = step { + p.observe_board(&board[..s.board_len().min(board.len())]); + } + } + if st.to_act() != Some(idx) { + return None; + } + let u = cards::Rng::new(mix(hseed, hist.len() as u64)).f64(); + let action = { + let view = View { cfg: &ecfg, state: &st, board: &board, history: &hist, seat: idx }; + p.act(&view, hole, u) + }; + let (kind, to) = match action { + Action::Fold => ("fold", None), + Action::Check => ("check", None), + Action::Call => ("call", None), + Action::RaiseTo(t) => (if st.cur_bet() == 0 { "bet" } else { "raise" }, Some(t)), + }; + let mut out = json!({"hand_id": hand_id, "decision_id": data["decision_id"], "type": kind}); + if let Some(t) = to { + out["to"] = json!(t); + } + Some(out) +} + +pub fn cli_pipe_house(args: Vec) -> i32 { + let Some(name) = args.first() else { + eprintln!("usage: sharingan-arena pipe-house "); + return 2; + }; + let house = match HouseRegistry::build(&ServerConfig::from_env()) { + Ok(h) => h, + Err(e) => { + eprintln!("pipe-house: {e}"); + return 1; + } + }; + let Some(key) = house.key_of(name) else { + eprintln!("pipe-house: unknown house bot {name}"); + return 2; + }; + let stdin = std::io::stdin(); + let mut out = std::io::BufWriter::new(std::io::stdout().lock()); + let hello = json!({"v": 1, "type": "hello", "data": {"client": format!("sharingan-pipe-house/{}", env!("CARGO_PKG_VERSION")), "protocol": 1, "bot": key}}); + let _ = writeln!(out, "{hello}"); + let _ = out.flush(); + for line in stdin.lock().lines() { + let Ok(line) = line else { break }; + let Ok(v) = serde_json::from_str::(&line) else { continue }; + match v["type"].as_str() { + Some("your_turn") => { + let act = decide(&house, &key, &v["data"]).unwrap_or_else(|| { + json!({"hand_id": v["data"]["hand_id"], "decision_id": v["data"]["decision_id"], "type": "fold"}) + }); + let env = json!({"v": 1, "type": "act", "table_id": v["table_id"], "t_ms": crate::util::now_ms(), "data": act}); + if writeln!(out, "{env}").is_err() || out.flush().is_err() { + break; + } + } + Some("bye") => break, + _ => {} + } + } + 0 +} diff --git a/arena/server/src/results.rs b/arena/server/src/results.rs new file mode 100644 index 00000000..f1bf8102 --- /dev/null +++ b/arena/server/src/results.rs @@ -0,0 +1,133 @@ +//! Control-plane intake of match-worker results: `POST /v1/results` (TABLE_API.md 14.8). +//! +//! A worker (`sharingan-arena run --sign-key-file`) plays a benchmark on operator-controlled +//! infrastructure and signs its `result.json` with HMAC-SHA256. The runner/admin posts it here; if the +//! signature matches one of `ARENA_WORKER_KEYS` and the result is for the track's frozen panel and seed, +//! it is stored as a finished benchmark run with `verified: true, hosted: true` +//! (`deals: "frozen"` on the track seed, `"fresh"` on a per-run `run:` seed), which the leaderboard +//! picks up like any other run. + +use crate::benchmarks; +use crate::error::{ApiError, Res}; +use crate::house::{house_id, HouseRegistry}; +use crate::model::RunRecord; +use crate::state::{AppState, Principal}; +use crate::util::*; +use crate::worker::{verify_result, RESULT_SCHEMA}; +use axum::extract::State; +use axum::http::{HeaderMap, StatusCode}; +use axum::Json; +use serde_json::{json, Value}; +use std::sync::Arc; + +pub const MIN_RUN_SEED_HEX: usize = 32; +pub const MAX_RUN_SEED_HEX: usize = 128; + +/// A per-run secret seed of a hosted run: `run:` + 32..128 hex characters. The runner draws it fresh for every job and +/// keeps it from the bot until the run is over, so the deals cannot be known (or tabulated) in advance. +pub fn is_run_seed(s: &str) -> bool { + match s.strip_prefix("run:") { + Some(h) => (MIN_RUN_SEED_HEX..=MAX_RUN_SEED_HEX).contains(&h.len()) && h.bytes().all(|b| b.is_ascii_hexdigit()), + None => false, + } +} + +fn bad(m: impl Into) -> ApiError { + ApiError::bad_request(m) +} + +pub async fn post_result(State(app): State>, headers: HeaderMap, Json(body): Json) -> Res<(StatusCode, Json)> { + app.ensure_accepting()?; + match app.authenticate_any(&headers)? { + Principal::Admin | Principal::Runner => {} + Principal::Player(_) => return Err(ApiError::forbidden("only the runner token (ARENA_RUNNER_TOKEN) or an admin can post worker results")), + } + // Either the raw result.json, or {"result": {...}, "player_id": "..."}. + let (result, wrapper_pid) = match (body.get("result"), body.get("schema")) { + (Some(r), None) if r.is_object() => (r.clone(), body.get("player_id").and_then(|p| p.as_str()).map(String::from)), + _ => (body.clone(), None), + }; + let key_id = verify_result(&result, &app.cfg.worker_keys).map_err(|m| ApiError::new(401, "invalid_signature", m))?; + + if result["schema"] != RESULT_SCHEMA { + return Err(bad(format!("schema must be {RESULT_SCHEMA}"))); + } + let t = benchmarks::track(result["track"].as_str().unwrap_or(""))?; + if result["panel_version"].as_str() != Some(t.version) { + return Err(bad(format!("panel_version must be {} (the current version of {})", t.version, t.id))); + } + let panel: Vec = t.panel.iter().map(|k| house_id(k)).collect(); + if result["panel"] != json!(panel) { + return Err(bad("panel is not the track's frozen panel")); + } + let track_seed = benchmarks::seed_of(t); + let seed = result["seed"].as_str().unwrap_or("").to_string(); + let deals = if seed == track_seed { + "frozen" + } else if is_run_seed(&seed) { + "fresh" + } else { + return Err(bad(format!( + "seed must be the track seed {track_seed} (frozen deals) or a per-run seed run:<{MIN_RUN_SEED_HEX}-{MAX_RUN_SEED_HEX} hex characters> (fresh secret deals)" + ))); + }; + let run_id = result["run_id"].as_str().unwrap_or(""); + if !(8..=64).contains(&run_id.len()) || !run_id.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') { + return Err(bad("run_id must be 8-64 characters of [A-Za-z0-9_-]")); + } + if app.store.get_run(run_id)?.is_some() { + return Err(ApiError::conflict("duplicate_result", "a result with this run_id was already accepted")); + } + let pid_raw = match (wrapper_pid.as_deref(), result["player_id"].as_str()) { + (Some(a), Some(b)) if a != b => return Err(bad("player_id differs from the signed player_id")), + (Some(a), _) | (None, Some(a)) => a.to_string(), + (None, None) => return Err(bad("player_id required (signed in the result via --player-id, or wrapper field)")), + }; + let pid = if HouseRegistry::looks_like_house(&pid_raw) { house_id(&app.house.resolve(&pid_raw)?) } else { pid_raw }; + let player = app.store.get_player(&pid)?.ok_or_else(|| ApiError::not_found("player"))?; + let (hands, planned) = (result["hands"].as_u64().unwrap_or(0) as u32, result["hands_planned"].as_u64().unwrap_or(0) as u32); + if hands < 6 || hands != planned { + return Err(bad("hands must equal hands_planned (>= 6): incomplete results are not accepted")); + } + let (mbb, ci) = (result["mbb_per_game"].as_f64(), result["ci95_mbb"].as_f64()); + let (Some(mbb), Some(ci)) = (mbb, ci) else { return Err(bad("mbb_per_game and ci95_mbb must be numbers")) }; + if !mbb.is_finite() || !ci.is_finite() { + return Err(bad("mbb_per_game and ci95_mbb must be finite")); + } + let fp = result["blueprint_fingerprint"].as_str().map(String::from); + if let Some(server_fp) = &app.house.blueprint_fp { + if fp.as_ref() != Some(server_fp) { + return Err(ApiError::conflict("blueprint_mismatch", "the worker used a different blueprint than this arena's SHARINGAN-1") + .with(json!({"server": server_fp, "result": fp}))); + } + } + let run = RunRecord { + run_id: run_id.to_string(), + track: t.id.into(), + panel_version: t.version.into(), + panel, + player_id: player.player_id.clone(), + name: player.name.clone(), + match_id: format!("worker:{run_id}"), + seed, + deals: Some(deals.into()), + hands_planned: planned, + hands_done: hands, + status: "finished".into(), + verified: true, + hosted: true, + mbb_per_game: Some(mbb), + ci95_mbb: Some(ci), + method: result["method"].as_str().map(String::from), + blueprint_fingerprint: fp, + created_at: now_iso(), + finished_at: Some(result["finished_at"].as_str().map(String::from).unwrap_or_else(now_iso)), + }; + app.store.put_run(&run)?; + app.leaderboard_changed(); + let mut v = serde_json::to_value(&run).unwrap(); + v["hands_total"] = json!(run.hands_planned); + v["key_id"] = json!(key_id); + v["forfeit_hands"] = result["forfeit_hands"].clone(); + Ok((StatusCode::CREATED, Json(v))) +} diff --git a/arena/server/src/state.rs b/arena/server/src/state.rs new file mode 100644 index 00000000..1093560d --- /dev/null +++ b/arena/server/src/state.rs @@ -0,0 +1,155 @@ +//! Shared application state. + +use crate::config::ServerConfig; +use crate::error::{ApiError, Res}; +use crate::house::HouseRegistry; +use crate::hub::Hub; +use crate::matches::MatchRuntime; +use crate::model::PlayerRecord; +use crate::store::Store; +use crate::table::TableShared; +use crate::writer::HandWriter; +use crate::util::{ct_eq, sha256_hex}; +use axum::http::HeaderMap; +use std::collections::HashMap; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, RwLock}; + +pub struct AppState { + pub cfg: ServerConfig, + pub store: Arc, + pub hub: Arc, + pub house: Arc, + pub writer: HandWriter, + pub admin_token: String, + pub limiter: crate::limits::RateLimiter, + /// Bot registrations per client address (see `ServerConfig::bots_per_ip_per_day`). + pub reg_limiter: crate::limits::RateLimiter, + /// Human registrations (the browser play page) per client address: 10x the bot allowance, so people behind one + /// address (a carrier NAT, an office) can still play. + pub human_reg_limiter: crate::limits::RateLimiter, + /// `GET /v1/leaderboard` answers by query, kept 2 s. + pub lb_cache: std::sync::Mutex>, + /// Set when shutdown starts: readiness fails and new tables/matches/runs/sockets are refused. + pub draining: AtomicBool, + /// `true` once sockets must close (last phase of shutdown). + pub shutdown: tokio::sync::watch::Sender, + pub tables: RwLock>>, + pub matches: RwLock>>, +} + +#[derive(Clone, Debug)] +pub enum Principal { + Admin, + /// The trusted eval runner (`ARENA_RUNNER_TOKEN`); only valid on the hosted-attestation / run endpoints. + Runner, + Player(PlayerRecord), +} + +impl Principal { + pub fn is_admin(&self) -> bool { + matches!(self, Principal::Admin) + } + /// Id used as table/match owner. + pub fn owner_id(&self) -> String { + match self { + Principal::Admin => "admin".into(), + Principal::Runner => "runner".into(), + Principal::Player(p) => p.player_id.clone(), + } + } +} + +pub fn bearer(headers: &HeaderMap) -> Option { + let v = headers.get("authorization")?.to_str().ok()?; + let t = v.strip_prefix("Bearer ").or_else(|| v.strip_prefix("bearer "))?; + Some(t.trim().to_string()) +} + +impl AppState { + /// A run or result was written (or deleted): the next leaderboard answer is computed fresh. + pub fn leaderboard_changed(&self) { + self.lb_cache.lock().unwrap().clear(); + } + + pub fn authenticate_token(&self, token: &str) -> Res { + if ct_eq(token, &self.admin_token) { + return Ok(Principal::Admin); + } + if let Some(rt) = &self.cfg.runner_token { + if ct_eq(token, rt) { + return Ok(Principal::Runner); + } + } + match self.store.player_by_token_hash(&sha256_hex(token.as_bytes()))? { + Some(p) => Ok(Principal::Player(p)), + None => Err(ApiError::unauthorized()), + } + } + /// Admin or bot token. The runner token is refused (403): it may only call the run/attestation endpoints. + pub fn authenticate(&self, headers: &HeaderMap) -> Res { + match self.authenticate_any(headers)? { + Principal::Runner => Err(ApiError::forbidden("the runner token is only valid for benchmark runs and /v1/runner/*")), + p => Ok(p), + } + } + /// Like `authenticate`, but also accepts the runner token. + pub fn authenticate_any(&self, headers: &HeaderMap) -> Res { + let t = bearer(headers).ok_or_else(ApiError::unauthorized)?; + self.authenticate_token(&t) + } + pub fn is_draining(&self) -> bool { + self.draining.load(Ordering::SeqCst) + } + /// 503 while shutting down; call at the top of every handler that starts new work. + pub fn ensure_accepting(&self) -> Res<()> { + if self.is_draining() { + Err(ApiError::shutting_down()) + } else { + Ok(()) + } + } + /// Free (non-match) tables that are open and that the player owns or sits at. + pub fn open_tables_of(&self, player_id: &str) -> usize { + self.tables + .read() + .unwrap() + .values() + .filter(|t| { + let i = t.inner.lock().unwrap(); + i.match_id.is_none() + && i.status != "closed" + && (i.owner == player_id || i.seats.iter().any(|s| s.player_id.as_deref() == Some(player_id))) + }) + .count() + } + /// Matches (including benchmark runs) owned by `owner` that have not ended. + pub fn live_matches_of(&self, owner: &str) -> usize { + self.matches + .read() + .unwrap() + .values() + .filter(|m| { + let s = m.state.lock().unwrap(); + !matches!(s.rec.status.as_str(), "finished" | "aborted") + && self.tables.read().unwrap().get(&m.table_id).map(|t| t.inner.lock().unwrap().owner == owner).unwrap_or(false) + }) + .count() + } + pub fn table(&self, id: &str) -> Res> { + self.tables.read().unwrap().get(id).cloned().ok_or_else(|| ApiError::not_found("table")) + } + pub fn match_rt(&self, id: &str) -> Res> { + self.matches.read().unwrap().get(id).cloned().ok_or_else(|| ApiError::not_found("match")) + } + /// Tables where the player holds a seat. + pub fn tables_of(&self, player_id: &str) -> Vec> { + self.tables + .read() + .unwrap() + .values() + .filter(|t| t.inner.lock().unwrap().seats.iter().any(|s| s.player_id.as_deref() == Some(player_id))) + .cloned() + .collect() + } +} diff --git a/arena/server/src/stats.rs b/arena/server/src/stats.rs new file mode 100644 index 00000000..a158d1c5 --- /dev/null +++ b/arena/server/src/stats.rs @@ -0,0 +1,292 @@ +//! Standings and leaderboard statistics. +//! +//! Unit of independence: the deal. In a duplicate match one deal is six hands (every rotation); +//! a player's sample for a deal is the mean payoff over its seats in those six hands (AIVAT +//! corrected when available). Non-duplicate matches use the hand itself as the sample. Scores +//! are mbb/hand with a 95% interval from the sample standard error. + +use crate::model::*; +use bench::stats::Acc; +use std::collections::{BTreeMap, HashMap}; + +#[derive(Default)] +struct PlayerAcc { + hands: u64, + net: i64, + per_hand: Acc, + /// sample key -> (sum raw, sum av, count, av missing) + samples: BTreeMap, +} + +pub struct Builder { + accs: BTreeMap, + key_hands: HashMap, + bb: f64, + duplicate: bool, + /// hands per sample key for it to count as complete (6 duplicate, 1 otherwise) + need: u32, +} + +impl Builder { + pub fn new(bb: i64, duplicate: bool) -> Self { + Builder { accs: BTreeMap::new(), key_hands: HashMap::new(), bb: bb as f64, duplicate, need: if duplicate { 6 } else { 1 } } + } + /// Count a hand toward its sample key; call once per hand before `add`. + pub fn add_hand(&mut self, key: u32) { + *self.key_hands.entry(key).or_default() += 1; + } + pub fn add(&mut self, pid: &str, key: u32, net: i64, av: Option) { + let a = self.accs.entry(pid.to_string()).or_default(); + a.hands += 1; + a.net += net; + a.per_hand.add(net as f64); + let e = a.samples.entry(key).or_insert((0.0, 0.0, 0, false)); + e.0 += net as f64; + match av { + Some(v) => e.1 += v, + None => e.3 = true, + } + e.2 += 1; + } + + pub fn finish(self, names: &HashMap) -> (Vec, Vec<(String, StoredResult)>) { + let bb = self.bb; + let mut st = Vec::new(); + let mut rows = Vec::new(); + for (pid, a) in &self.accs { + let n = a.hands as f64; + let mean = a.per_hand.mean(); + let se = a.per_hand.se(); + let (mut raw, mut av) = (Acc::default(), Acc::default()); + let mut av_ok = true; + for (k, (r, v, c, miss)) in &a.samples { + if self.key_hands.get(k).copied().unwrap_or(0) < self.need { + continue; + } + raw.add(r / *c as f64); + av.add(v / *c as f64); + av_ok &= !miss; + } + let deals = raw.n; + let has_av = av_ok && av.n > 0; + let (method, sc_mean, sc_se) = if has_av { + ("aivat", av.mean(), av.se()) + } else if self.duplicate && deals > 0 { + ("duplicate", raw.mean(), raw.se()) + } else { + ("raw", mean, se) + }; + let mbb = |x: f64| x / bb * 1000.0; + st.push(Standing { + player_id: pid.clone(), + slot: 0, + name: names.get(pid).cloned().unwrap_or_default(), + hands: a.hands, + net_chips: a.net, + bb_per_100: mean / bb * 100.0, + mbb_per_hand: mbb(mean), + ci95_bb_per_100: 1.96 * se / bb * 100.0, + duplicate_bb_per_100: (self.duplicate && deals > 0).then(|| raw.mean() / bb * 100.0), + duplicate_mbb_per_hand: (self.duplicate && deals > 0).then(|| mbb(raw.mean())), + duplicate_ci95_mbb_per_hand: (self.duplicate && deals > 0).then(|| mbb(1.96 * raw.se())), + aivat_mbb_per_hand: has_av.then(|| mbb(av.mean())), + aivat_ci95_mbb_per_hand: has_av.then(|| mbb(1.96 * av.se())), + method: method.into(), + score_mbb_per_hand: mbb(sc_mean), + score_ci95_mbb_per_hand: mbb(1.96 * sc_se), + mbb_per_game: mbb(sc_mean), + ci95_mbb: mbb(1.96 * sc_se), + deals, + }); + let _ = n; + let samples = if method == "raw" { a.hands } else { deals }; + rows.push(( + pid.clone(), + StoredResult { + match_id: String::new(), + player_id: pid.clone(), + hands: a.hands, + deals: samples, + net_chips: a.net, + score_mbb: mbb(sc_mean), + se_mbb: mbb(sc_se), + method: method.into(), + }, + )); + } + (st, rows) + } +} + +/// Combine per-match results into one score per player: inverse-variance weighted mean. +/// Rows without a usable standard error (fewer than two samples) carry no weight. +/// Benchmark-track cells are the latest finished run per (player, track); a verified run counts only with at least +/// `ranked_min_hands` hands. `track` filters and sorts by that column. +pub fn leaderboard( + results: &[StoredResult], + players: &HashMap, + runs: &[RunRecord], + min_hands: u64, + ranked_min_hands: u64, + include_house: bool, + track: Option<&str>, +) -> Vec { + struct A { + w: f64, + wm: f64, + hands: u64, + matches: u64, + methods: Vec, + } + let mut by: BTreeMap<&str, A> = BTreeMap::new(); + for r in results { + let a = by.entry(&r.player_id).or_insert(A { w: 0.0, wm: 0.0, hands: 0, matches: 0, methods: vec![] }); + a.hands += r.hands; + a.matches += 1; + if !a.methods.contains(&r.method) { + a.methods.push(r.method.clone()); + } + if r.se_mbb > 0.0 && r.se_mbb.is_finite() { + let w = 1.0 / (r.se_mbb * r.se_mbb); + a.w += w; + a.wm += w * r.score_mbb; + } + } + // One cell per (player, track): the latest VERIFIED finished run; an unverified run only while there is no verified one. + // Aborted runs never count: a partial score could be stopped while it happens to look good. Keyed (verified, finished_at). + // Short verified runs never count either: many cheap runs with wide intervals could fish for a lucky one. + let mut cells: HashMap<&str, BTreeMap> = HashMap::new(); + for r in runs.iter().filter(|r| r.status == "finished" && !(r.verified && u64::from(r.hands_done) < ranked_min_hands)) { + let (Some(m), Some(c)) = (r.mbb_per_game, r.ci95_mbb) else { continue }; + let key = (r.verified, r.finished_at.clone().unwrap_or_default()); + let e = cells.entry(&r.player_id).or_default(); + if e.get(&r.track).map(|(k, _)| *k < key).unwrap_or(true) { + e.insert( + r.track.clone(), + (key, TrackCell { run_id: r.run_id.clone(), mbb_per_game: m, ci95_mbb: c, hands: r.hands_done, verified: r.verified, method: r.method.clone().unwrap_or_default() }), + ); + } + } + let mut ids: Vec<&str> = by.keys().copied().collect(); + for k in cells.keys() { + if !ids.contains(k) { + ids.push(k); + } + } + let mut rows: Vec = ids + .into_iter() + .filter_map(|pid| { + let p = players.get(pid)?; + if p.house && !include_house { + return None; + } + let tracks: BTreeMap = cells.get(pid).map(|m| m.iter().map(|(k, v)| (k.clone(), v.1.clone())).collect()).unwrap_or_default(); + if let Some(t) = track { + if !tracks.contains_key(t) { + return None; + } + } + let a = by.get(pid); + let general = a.filter(|a| a.hands >= min_hands && a.w > 0.0); + if general.is_none() && tracks.is_empty() { + return None; + } + let score = general.map(|a| a.wm / a.w); + Some(LeaderboardRow { + rank: 0, + player_id: pid.to_string(), + name: p.name.clone(), + house: p.house, + matches: a.map(|a| a.matches).unwrap_or(0), + // own benchmark hands when there are runs (match results also count a house bot's seats in other bots' panels) + hands: if tracks.is_empty() { a.map(|a| a.hands).unwrap_or(0) } else { tracks.values().map(|c| c.hands as u64).sum::() }, + score_mbb_per_hand: score, + ci95_mbb_per_hand: general.map(|a| 1.96 / a.w.sqrt()), + score_bb_per_100: score.map(|s| s / 10.0), + methods: a.map(|a| a.methods.clone()).unwrap_or_default(), + vs_ladder_v1: tracks.get("ladder-v1").map(|c| VsCell { mbb: c.mbb_per_game, ci95_mbb: c.ci95_mbb, hands: c.hands }), + vs_sharingan_1: tracks.get("sharingan-1").map(|c| VsCell { mbb: c.mbb_per_game, ci95_mbb: c.ci95_mbb, hands: c.hands }), + verified: !tracks.is_empty() && tracks.values().all(|c| c.verified), + tracks, + }) + }) + .collect(); + // With a track: that track's score. Without: like the site, sharingan-1 first, then ladder-v1, then the match score. + // Verified cells rank above every unverified one: an unverified run (the bot ran elsewhere) never outranks a verified. + let cell = |r: &LeaderboardRow, t: &str| r.tracks.get(t).map(|c| c.mbb_per_game).unwrap_or(f64::NEG_INFINITY); + let ver = |r: &LeaderboardRow, t: &str| if r.tracks.get(t).map(|c| c.verified).unwrap_or(false) { 1.0 } else { 0.0 }; + let key = |r: &LeaderboardRow| -> [f64; 4] { + match track { + Some(t) => [ver(r, t), cell(r, t), 0.0, 0.0], + None => [ver(r, "sharingan-1"), cell(r, "sharingan-1"), cell(r, "ladder-v1"), r.score_mbb_per_hand.unwrap_or(f64::NEG_INFINITY)], + } + }; + rows.sort_by(|a, b| key(b).partial_cmp(&key(a)).unwrap_or(std::cmp::Ordering::Equal)); + for (i, r) in rows.iter_mut().enumerate() { + r.rank = i + 1; + } + rows +} + +#[cfg(test)] +mod tests { + use super::*; + + fn run(id: &str, verified: bool, status: &str, fin: &str, mbb: f64) -> RunRecord { + RunRecord { + run_id: id.into(), track: "sharingan-1".into(), panel_version: "1".into(), panel: vec![], player_id: "p_x".into(), name: "x".into(), + match_id: "m".into(), seed: "s".into(), deals: None, hands_planned: 20004, hands_done: 20004, status: status.into(), verified, hosted: verified, + mbb_per_game: Some(mbb), ci95_mbb: Some(10.0), method: Some("aivat".into()), blueprint_fingerprint: None, created_at: fin.into(), + finished_at: Some(fin.into()), + } + } + + #[test] + fn verified_score_is_never_replaced_by_an_unverified_or_aborted_run() { + let p = PlayerRecord { player_id: "p_x".into(), name: "x".into(), kind: "bot".into(), owner: None, created_at: "t".into(), house: false, + token_hash: String::new(), webhook_url: None, webhook_secret: None }; + let players: HashMap = [("p_x".to_string(), p)].into_iter().collect(); + let cell = |runs: &[RunRecord]| { + let rows = leaderboard(&[], &players, runs, 0, 0, true, None); + let c = rows[0].tracks.get("sharingan-1").unwrap(); + (c.run_id.clone(), c.verified) + }; + let v1 = run("v1", true, "finished", "2026-11-01T00:00:00Z", -100.0); + let u = run("u", false, "finished", "2026-11-02T00:00:00Z", 500.0); + let ab = run("ab", true, "aborted", "2026-11-03T00:00:00Z", 900.0); + let v2 = run("v2", true, "finished", "2026-11-04T00:00:00Z", -50.0); + assert_eq!(cell(&[v1.clone(), u.clone()]), ("v1".into(), true), "a later unverified run does not replace a verified one"); + assert_eq!(cell(&[v1.clone(), ab.clone()]), ("v1".into(), true), "an aborted (partial) run never counts"); + assert_eq!(cell(&[v1.clone(), u.clone(), v2.clone()]), ("v2".into(), true), "the latest verified run wins"); + assert_eq!(cell(&[u.clone()]), ("u".into(), false), "unverified shows while there is nothing verified"); + } + + #[test] + fn verified_rows_rank_above_unverified_ones() { + let mk = |id: &str| PlayerRecord { player_id: id.into(), name: id.into(), kind: "bot".into(), owner: None, created_at: "t".into(), house: false, + token_hash: String::new(), webhook_url: None, webhook_secret: None }; + let players: HashMap = ["p_v", "p_u"].iter().map(|p| (p.to_string(), mk(p))).collect(); + let mut v = run("v", true, "finished", "2026-11-01T00:00:00Z", -50.0); + v.player_id = "p_v".into(); + let mut u = run("u", false, "finished", "2026-11-01T00:00:00Z", 900.0); + u.player_id = "p_u".into(); + for t in [None, Some("sharingan-1")] { + let rows = leaderboard(&[], &players, &[u.clone(), v.clone()], 0, 0, true, t); + assert_eq!(rows.iter().map(|r| r.player_id.as_str()).collect::>(), ["p_v", "p_u"], "track {t:?}"); + } + } + + #[test] + fn short_verified_runs_never_set_the_score() { + let p = PlayerRecord { player_id: "p_x".into(), name: "x".into(), kind: "bot".into(), owner: None, created_at: "t".into(), house: false, + token_hash: String::new(), webhook_url: None, webhook_secret: None }; + let players: HashMap = [("p_x".to_string(), p)].into_iter().collect(); + let full = run("full", true, "finished", "2026-11-01T00:00:00Z", -100.0); + let mut short = run("short", true, "finished", "2026-11-02T00:00:00Z", 1500.0); + short.hands_done = 600; + let cell = |runs: &[RunRecord]| leaderboard(&[], &players, runs, 0, 20004, true, None).first().and_then(|r| r.tracks.get("sharingan-1").map(|c| c.run_id.clone())); + assert_eq!(cell(&[full.clone(), short.clone()]), Some("full".into()), "a later short run does not replace a full one"); + assert_eq!(cell(&[short.clone()]), None, "a bot with only short runs is not on the board"); + assert_eq!(leaderboard(&[], &players, &[full, short], 0, 0, true, None)[0].tracks["sharingan-1"].run_id, "short", "0 = any length"); + } +} diff --git a/arena/server/src/store.rs b/arena/server/src/store.rs new file mode 100644 index 00000000..1f1c8250 --- /dev/null +++ b/arena/server/src/store.rs @@ -0,0 +1,318 @@ +//! Storage behind a small trait: SQLite here (the default; one connection behind a mutex, WAL mode) +//! and Postgres in `pgstore.rs` (`ARENA_DATABASE_URL`). Values that are not queried are stored as JSON. + +use crate::error::{ApiError, Res}; +use crate::model::*; +use rusqlite::{params, Connection, OptionalExtension}; +use serde_json::Value; +use std::sync::Mutex; + +pub trait Store: Send + Sync { + /// Cheap liveness check of the backing database (readiness probe). + fn ping(&self) -> Res<()>; + + fn put_player(&self, p: &PlayerRecord) -> Res<()>; + fn get_player(&self, id: &str) -> Res>; + fn player_by_token_hash(&self, hash: &str) -> Res>; + fn list_players(&self, limit: u32) -> Res>; + + fn put_match(&self, m: &MatchRecord) -> Res<()>; + fn get_match(&self, id: &str) -> Res>; + fn list_matches(&self, limit: u32) -> Res>; + /// Mark matches left `scheduled`/`running`/`paused` by a previous process as `aborted` (their runtime lived in that + /// process: without this a never-started match stays `scheduled` and answers 404 to start and abort forever). + fn abort_stale_matches(&self) -> Res; + + fn append_hand(&self, h: &HandHistory, events: &[Value]) -> Res<()>; + /// Insert many hands in one transaction. + fn append_hands(&self, items: &[(HandHistory, Vec)]) -> Res<()> { + for (h, e) in items { + self.append_hand(h, e)?; + } + Ok(()) + } + fn get_hand(&self, id: &str) -> Res>; + fn get_hand_events(&self, id: &str) -> Res>>; + fn list_hands(&self, match_id: &str, after_hand_no: u32, limit: u32) -> Res>; + fn count_hands(&self, match_id: &str) -> Res; + + fn put_run(&self, r: &RunRecord) -> Res<()>; + fn get_run(&self, id: &str) -> Res>; + /// Newest first. + fn list_runs(&self, track: Option<&str>, player_id: Option<&str>, limit: u32) -> Res>; + + fn put_results(&self, match_id: &str, rows: &[StoredResult]) -> Res<()>; + fn all_results(&self) -> Res>; + fn results_of_player(&self, player_id: &str) -> Res>; + + /// Admin cleanup: remove a match with its hands and results. + fn delete_match_data(&self, match_id: &str) -> Res<()>; + fn delete_run(&self, run_id: &str) -> Res<()>; + fn delete_player(&self, player_id: &str) -> Res<()>; +} + +pub struct SqliteStore { + conn: Mutex, +} + +const SCHEMA: &str = r#" +CREATE TABLE IF NOT EXISTS players( + player_id TEXT PRIMARY KEY, name TEXT NOT NULL, kind TEXT NOT NULL, owner TEXT, + house INTEGER NOT NULL DEFAULT 0, token_hash TEXT NOT NULL DEFAULT '', + webhook_url TEXT, webhook_secret TEXT, created_at TEXT NOT NULL, created_seq INTEGER +); +CREATE INDEX IF NOT EXISTS players_token ON players(token_hash); +CREATE TABLE IF NOT EXISTS matches( + match_id TEXT PRIMARY KEY, status TEXT NOT NULL, body TEXT NOT NULL, created_seq INTEGER +); +CREATE TABLE IF NOT EXISTS hands( + hand_id TEXT PRIMARY KEY, match_id TEXT, hand_no INTEGER NOT NULL, body TEXT NOT NULL, events TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS hands_match ON hands(match_id, hand_no); +CREATE TABLE IF NOT EXISTS match_results( + match_id TEXT NOT NULL, player_id TEXT NOT NULL, hands INTEGER NOT NULL, deals INTEGER NOT NULL, + net_chips INTEGER NOT NULL, score_mbb REAL NOT NULL, se_mbb REAL NOT NULL, method TEXT NOT NULL, + PRIMARY KEY(match_id, player_id) +); +CREATE INDEX IF NOT EXISTS results_player ON match_results(player_id); +CREATE TABLE IF NOT EXISTS benchmark_runs( + run_id TEXT PRIMARY KEY, track TEXT NOT NULL, player_id TEXT NOT NULL, body TEXT NOT NULL, created_seq INTEGER +); +CREATE INDEX IF NOT EXISTS runs_track ON benchmark_runs(track, player_id); +"#; + +impl SqliteStore { + /// `path` may be a file or `:memory:`. + pub fn open(path: &str) -> Res { + let conn = Connection::open(path)?; + conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA foreign_keys=ON;")?; + conn.execute_batch(SCHEMA)?; + Ok(SqliteStore { conn: Mutex::new(conn) }) + } + fn c(&self) -> std::sync::MutexGuard<'_, Connection> { + self.conn.lock().unwrap_or_else(|e| e.into_inner()) + } +} + +fn player_from_row(r: &rusqlite::Row) -> rusqlite::Result { + Ok(PlayerRecord { + player_id: r.get(0)?, + name: r.get(1)?, + kind: r.get(2)?, + owner: r.get(3)?, + house: r.get::<_, i64>(4)? != 0, + token_hash: r.get(5)?, + webhook_url: r.get(6)?, + webhook_secret: r.get(7)?, + created_at: r.get(8)?, + }) +} + +const PCOLS: &str = "player_id,name,kind,owner,house,token_hash,webhook_url,webhook_secret,created_at"; + +pub(crate) fn parse(s: String) -> Res { + serde_json::from_str(&s).map_err(|e| ApiError::internal(format!("corrupt row: {e}"))) +} + +impl Store for SqliteStore { + fn ping(&self) -> Res<()> { + self.c().query_row("SELECT 1", [], |r| r.get::<_, i64>(0))?; + Ok(()) + } + fn put_player(&self, p: &PlayerRecord) -> Res<()> { + self.c().execute( + "INSERT INTO players(player_id,name,kind,owner,house,token_hash,webhook_url,webhook_secret,created_at,created_seq) + VALUES(?1,?2,?3,?4,?5,?6,?7,?8,?9,(SELECT COALESCE(MAX(created_seq),0)+1 FROM players)) + ON CONFLICT(player_id) DO UPDATE SET name=?2,kind=?3,owner=?4,house=?5,token_hash=?6,webhook_url=?7,webhook_secret=?8", + params![p.player_id, p.name, p.kind, p.owner, p.house as i64, p.token_hash, p.webhook_url, p.webhook_secret, p.created_at], + )?; + Ok(()) + } + fn get_player(&self, id: &str) -> Res> { + Ok(self + .c() + .query_row(&format!("SELECT {PCOLS} FROM players WHERE player_id=?1"), [id], player_from_row) + .optional()?) + } + fn player_by_token_hash(&self, hash: &str) -> Res> { + if hash.is_empty() { + return Ok(None); + } + Ok(self + .c() + .query_row(&format!("SELECT {PCOLS} FROM players WHERE token_hash=?1"), [hash], player_from_row) + .optional()?) + } + fn list_players(&self, limit: u32) -> Res> { + let c = self.c(); + let mut st = c.prepare(&format!("SELECT {PCOLS} FROM players ORDER BY created_seq LIMIT ?1"))?; + let rows = st.query_map([limit], player_from_row)?.collect::, _>>()?; + Ok(rows) + } + + fn put_match(&self, m: &MatchRecord) -> Res<()> { + let body = serde_json::to_string(m)?; + self.c().execute( + "INSERT INTO matches(match_id,status,body,created_seq) VALUES(?1,?2,?3,(SELECT COALESCE(MAX(created_seq),0)+1 FROM matches)) + ON CONFLICT(match_id) DO UPDATE SET status=?2, body=?3", + params![m.match_id, m.status, body], + )?; + Ok(()) + } + fn get_match(&self, id: &str) -> Res> { + let s: Option = + self.c().query_row("SELECT body FROM matches WHERE match_id=?1", [id], |r| r.get(0)).optional()?; + s.map(parse).transpose() + } + fn list_matches(&self, limit: u32) -> Res> { + let c = self.c(); + let mut st = c.prepare("SELECT body FROM matches ORDER BY created_seq DESC LIMIT ?1")?; + let rows = st.query_map([limit], |r| r.get::<_, String>(0))?.collect::, _>>()?; + rows.into_iter().map(parse).collect() + } + fn abort_stale_matches(&self) -> Res { + let ids: Vec = { + let c = self.c(); + let mut st = c.prepare("SELECT match_id FROM matches WHERE status IN ('scheduled','running','paused')")?; + let v = st.query_map([], |r| r.get(0))?.collect::, _>>()?; + v + }; + for id in &ids { + if let Some(mut m) = self.get_match(id)? { + m.status = "aborted".into(); + self.put_match(&m)?; + } + } + Ok(ids.len() as u64) + } + + fn append_hand(&self, h: &HandHistory, events: &[Value]) -> Res<()> { + let body = serde_json::to_string(h)?; + let ev = serde_json::to_string(events)?; + self.c().execute( + "INSERT OR REPLACE INTO hands(hand_id,match_id,hand_no,body,events) VALUES(?1,?2,?3,?4,?5)", + params![h.hand_id, h.match_id, h.hand_no, body, ev], + )?; + Ok(()) + } + fn append_hands(&self, items: &[(HandHistory, Vec)]) -> Res<()> { + let mut c = self.c(); + let tx = c.transaction()?; + { + let mut st = tx.prepare_cached("INSERT OR REPLACE INTO hands(hand_id,match_id,hand_no,body,events) VALUES(?1,?2,?3,?4,?5)")?; + for (h, e) in items { + let body = serde_json::to_string(h)?; + let ev = if e.is_empty() { "[]".to_string() } else { serde_json::to_string(e)? }; + st.execute(params![h.hand_id, h.match_id, h.hand_no, body, ev])?; + } + } + tx.commit()?; + Ok(()) + } + fn put_run(&self, r: &RunRecord) -> Res<()> { + let body = serde_json::to_string(r)?; + self.c().execute( + "INSERT INTO benchmark_runs(run_id,track,player_id,body,created_seq) VALUES(?1,?2,?3,?4,(SELECT COALESCE(MAX(created_seq),0)+1 FROM benchmark_runs)) + ON CONFLICT(run_id) DO UPDATE SET body=?4", + params![r.run_id, r.track, r.player_id, body], + )?; + Ok(()) + } + fn get_run(&self, id: &str) -> Res> { + let s: Option = self.c().query_row("SELECT body FROM benchmark_runs WHERE run_id=?1", [id], |r| r.get(0)).optional()?; + s.map(parse).transpose() + } + fn list_runs(&self, track: Option<&str>, player_id: Option<&str>, limit: u32) -> Res> { + let c = self.c(); + let mut st = c.prepare("SELECT body FROM benchmark_runs WHERE (?1 IS NULL OR track=?1) AND (?2 IS NULL OR player_id=?2) ORDER BY created_seq DESC LIMIT ?3")?; + let rows = st.query_map(params![track, player_id, limit], |r| r.get::<_, String>(0))?.collect::, _>>()?; + rows.into_iter().map(parse).collect() + } + fn get_hand(&self, id: &str) -> Res> { + let s: Option = + self.c().query_row("SELECT body FROM hands WHERE hand_id=?1", [id], |r| r.get(0)).optional()?; + s.map(parse).transpose() + } + fn get_hand_events(&self, id: &str) -> Res>> { + let s: Option = + self.c().query_row("SELECT events FROM hands WHERE hand_id=?1", [id], |r| r.get(0)).optional()?; + s.map(parse).transpose() + } + fn list_hands(&self, match_id: &str, after: u32, limit: u32) -> Res> { + let c = self.c(); + let mut st = c.prepare("SELECT body FROM hands WHERE match_id=?1 AND hand_no>?2 ORDER BY hand_no LIMIT ?3")?; + let rows = st.query_map(params![match_id, after, limit], |r| r.get::<_, String>(0))?.collect::, _>>()?; + rows.into_iter().map(parse).collect() + } + fn count_hands(&self, match_id: &str) -> Res { + Ok(self.c().query_row("SELECT COUNT(*) FROM hands WHERE match_id=?1", [match_id], |r| r.get::<_, i64>(0))? as u64) + } + + fn put_results(&self, match_id: &str, rows: &[StoredResult]) -> Res<()> { + let mut c = self.c(); + let tx = c.transaction()?; + tx.execute("DELETE FROM match_results WHERE match_id=?1", [match_id])?; + for r in rows { + tx.execute( + "INSERT INTO match_results(match_id,player_id,hands,deals,net_chips,score_mbb,se_mbb,method) VALUES(?1,?2,?3,?4,?5,?6,?7,?8)", + params![r.match_id, r.player_id, r.hands as i64, r.deals as i64, r.net_chips, r.score_mbb, r.se_mbb, r.method], + )?; + } + tx.commit()?; + Ok(()) + } + fn all_results(&self) -> Res> { + self.results_where("") + } + fn results_of_player(&self, player_id: &str) -> Res> { + let c = self.c(); + let mut st = c.prepare("SELECT match_id,player_id,hands,deals,net_chips,score_mbb,se_mbb,method FROM match_results WHERE player_id=?1")?; + let rows = st.query_map([player_id], result_from_row)?.collect::, _>>()?; + Ok(rows) + } + + fn delete_match_data(&self, match_id: &str) -> Res<()> { + let mut c = self.c(); + let tx = c.transaction()?; + tx.execute("DELETE FROM hands WHERE match_id=?1", [match_id])?; + tx.execute("DELETE FROM match_results WHERE match_id=?1", [match_id])?; + tx.execute("DELETE FROM matches WHERE match_id=?1", [match_id])?; + tx.commit()?; + Ok(()) + } + fn delete_run(&self, run_id: &str) -> Res<()> { + self.c().execute("DELETE FROM benchmark_runs WHERE run_id=?1", [run_id])?; + Ok(()) + } + fn delete_player(&self, player_id: &str) -> Res<()> { + let mut c = self.c(); + let tx = c.transaction()?; + tx.execute("DELETE FROM match_results WHERE player_id=?1", [player_id])?; + tx.execute("DELETE FROM benchmark_runs WHERE player_id=?1", [player_id])?; + tx.execute("DELETE FROM players WHERE player_id=?1", [player_id])?; + tx.commit()?; + Ok(()) + } +} + +fn result_from_row(r: &rusqlite::Row) -> rusqlite::Result { + Ok(StoredResult { + match_id: r.get(0)?, + player_id: r.get(1)?, + hands: r.get::<_, i64>(2)? as u64, + deals: r.get::<_, i64>(3)? as u64, + net_chips: r.get(4)?, + score_mbb: r.get(5)?, + se_mbb: r.get(6)?, + method: r.get(7)?, + }) +} + +impl SqliteStore { + fn results_where(&self, _w: &str) -> Res> { + let c = self.c(); + let mut st = c.prepare("SELECT match_id,player_id,hands,deals,net_chips,score_mbb,se_mbb,method FROM match_results")?; + let rows = st.query_map([], result_from_row)?.collect::, _>>()?; + Ok(rows) + } +} diff --git a/arena/server/src/table.rs b/arena/server/src/table.rs new file mode 100644 index 00000000..704487ac --- /dev/null +++ b/arena/server/src/table.rs @@ -0,0 +1,813 @@ +//! Tables: shared state (readable by REST/WS handlers) and the per-table task that deals hands. +//! +//! Each table is one tokio task that owns the running `HandRunner`. Seat controllers are either +//! house bots (the bench Policy API, answered inline), remote players over WebSocket (answers +//! arrive as `TableCmd::Act`), or remote players with a webhook. A decision that is not answered +//! before its deadline is played as check-if-free-else-fold with `timeout: true`. + +use crate::deck; +use crate::error::{ApiError, Res}; +use crate::hand::*; +use crate::hub::{ConnTx, Hub}; +use crate::matches::{self, HandPlan, MatchPoll, MatchRuntime}; +use crate::model::*; +use crate::state::AppState; +use crate::util::*; +use bench::mix; +use bench::policy::{Player, View}; +use nlhe::Action; +use serde_json::{json, Value}; +use std::collections::{HashMap, HashSet}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; +use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender}; +use tokio::sync::Notify; +use tokio::time::{sleep, timeout_at, Instant}; + +#[derive(Clone, Debug)] +pub struct SeatState { + pub player_id: Option, + pub name: Option, + pub kind: String, + pub house: bool, + pub stack: i64, + pub stand_up: bool, +} + +impl SeatState { + pub fn empty() -> Self { + SeatState { player_id: None, name: None, kind: "bot".into(), house: false, stack: 0, stand_up: false } + } +} + +pub struct TableInner { + pub config: TableConfig, + pub status: String, + pub seats: Vec, + pub button_seat: Option, + pub hand_id: Option, + pub table_seq: u64, + pub hand: Option, + pub holes: HashMap, + pub match_id: Option, + pub owner: String, + pub created_at: String, + pub in_hand: bool, + /// Messages delivered so far per recipient: `table_seq` is gap-free per recipient. + pub rseq: HashMap, +} + +pub enum TableCmd { + Act { player_id: String, data: Value, conn: ConnTx }, + Resume { player_id: String, conn: ConnTx }, + Leave { player_id: String }, + /// A seated player skips the pause between hands (`next_hand` over the socket). + Ready { player_id: String }, + Close, +} + +pub struct TableShared { + pub id: String, + pub inner: Mutex, + pub tx: UnboundedSender, + pub wake: Notify, +} + +impl TableShared { + pub fn new(id: String, owner: String, config: TableConfig, match_id: Option) -> (Arc, UnboundedReceiver) { + let (tx, rx) = unbounded_channel(); + let seats = vec![SeatState::empty(); config.max_seats as usize]; + let inner = TableInner { + config, + status: "waiting".into(), + seats, + button_seat: None, + hand_id: None, + table_seq: 0, + hand: None, + holes: HashMap::new(), + match_id, + owner, + created_at: now_iso(), + in_hand: false, + rseq: HashMap::new(), + }; + (Arc::new(TableShared { id, inner: Mutex::new(inner), tx, wake: Notify::new() }), rx) + } + + pub fn seat_json(inner: &TableInner, seat: usize, hub: &Hub) -> Value { + let s = &inner.seats[seat]; + let status = match &s.player_id { + None => "empty", + Some(_) if s.stand_up => "sitting_out", + Some(p) if !s.house && !hub.connected(p) => "disconnected", + Some(_) => "seated", + }; + json!({"seat": seat, "player_id": s.player_id, "name": s.name, "stack": s.stack, "status": status, + "kind": s.kind, "house": s.house}) + } + + fn table_value(inner: &TableInner, id: &str, hub: &Hub) -> Value { + json!({ + "table_id": id, "config": inner.config, "status": inner.status, + "seats": (0..inner.seats.len()).map(|i| Self::seat_json(inner, i, hub)).collect::>(), + "button_seat": inner.button_seat, "hand_id": inner.hand_id, "table_seq": inner.table_seq, + "match_id": inner.match_id, "owner": inner.owner, "created_at": inner.created_at, + }) + } + + /// `Table` plus the current public `HandState` (no hole cards). + pub fn table_json(&self, hub: &Hub) -> Value { + let inner = self.inner.lock().unwrap(); + let mut v = Self::table_value(&inner, &self.id, hub); + v["hand"] = inner.hand.clone().unwrap_or(Value::Null); + v + } + + /// Full snapshot message for one player (their hole cards included). + pub fn snapshot_msg(&self, hub: &Hub, player_id: &str) -> String { + let inner = self.inner.lock().unwrap(); + let mut d = Self::table_value(&inner, &self.id, hub); + d["hand"] = inner.hand.clone().unwrap_or(Value::Null); + let mut mine = serde_json::Map::new(); + for (seat, s) in inner.seats.iter().enumerate() { + if s.player_id.as_deref() == Some(player_id) { + if let Some(c) = inner.holes.get(&seat) { + mine.insert(seat.to_string(), json!(c)); + } + } + } + d["hole_cards"] = Value::Object(mine); + let mine_seq = inner.rseq.get(player_id).copied().unwrap_or(0); + d["table_seq"] = json!(mine_seq); + let mut env = json!({"v": 1, "type": "table_snapshot", "table_id": self.id, "table_seq": mine_seq, + "t_ms": now_ms(), "data": d}); + if let Some(h) = &inner.hand_id { + env["hand_id"] = json!(h); + } + env.to_string() + } + + /// Deliver a table event. Every recipient gets its own gap-free `table_seq` (events private to + /// another seat do not consume its numbers). The returned envelope carries the table-wide + /// counter and is what the hand event log stores. + pub fn emit(&self, hub: &Hub, hand_id: Option<&str>, kind: &str, seq: Option, to: Option, data: Value) -> Value { + let mut inner = self.inner.lock().unwrap(); + inner.table_seq += 1; + let mut env = json!({"v": 1, "type": kind, "table_id": self.id, "table_seq": inner.table_seq, + "t_ms": now_ms(), "data": data}); + if let Some(h) = hand_id { + env["hand_id"] = json!(h); + } + if let Some(s) = seq { + env["seq"] = json!(s); + } + let mut rec: Vec = match to { + Some(seat) => inner.seats.get(seat).filter(|s| !s.house).and_then(|s| s.player_id.clone()).into_iter().collect(), + None => inner.seats.iter().filter(|s| !s.house).filter_map(|s| s.player_id.clone()).collect(), + }; + rec.sort(); + rec.dedup(); + let mut out = Vec::with_capacity(rec.len()); + for p in rec { + let c = inner.rseq.entry(p.clone()).or_insert(0); + *c += 1; + env["table_seq"] = json!(*c); + out.push((p, env.to_string())); + } + // Private events log (and resend) the recipient's own number; broadcasts the table-wide one. + if to.is_none() || out.len() != 1 { + env["table_seq"] = json!(inner.table_seq); + } + drop(inner); + for (p, s) in out { + hub.send(&p, &s); + } + env + } + + pub fn emit_seat_update(&self, hub: &Hub, seat: usize) { + let d = { + let inner = self.inner.lock().unwrap(); + Self::seat_json(&inner, seat, hub) + }; + self.emit(hub, None, "seat_update", None, None, d); + } +} + +/// Create and register a table and spawn its task. +pub fn spawn_table(app: &Arc, id: String, owner: String, config: TableConfig, plan: Option>, lane: usize) -> Arc { + let match_id = plan.as_ref().map(|p| p.id.clone()); + let seed = config.seed.clone().unwrap_or_else(random_hex); + let (shared, rx) = TableShared::new(id.clone(), owner, config, match_id); + app.tables.write().unwrap().insert(id, shared.clone()); + let task = TableTask { + app: app.clone(), + shared: shared.clone(), + rx, + plan, + lane, + hand_counter: 0, + banks: HashMap::new(), + answered: HashSet::new(), + seed, + players: HashMap::new(), + closed: false, + absent_since: None, + abandon_after: Duration::from_millis( + std::env::var("ARENA_TABLE_ABANDON_MS").ok().and_then(|v| v.parse().ok()).unwrap_or(ABANDON_MS), + ), + }; + tokio::spawn(task.run()); + shared +} + +struct TableTask { + app: Arc, + shared: Arc, + rx: UnboundedReceiver, + plan: Option>, + lane: usize, + hand_counter: u32, + banks: HashMap, + answered: HashSet, + seed: String, + players: HashMap, + closed: bool, + /// Since when no human seat of this free table has a socket (None while one is connected). + absent_since: Option, + abandon_after: Duration, +} + +/// A free table that no human has been connected to for this long closes itself +/// (`ARENA_TABLE_ABANDON_MS` overrides). Without it a closed browser tab would leave its table, and its +/// slot in the owner's `ARENA_MAX_TABLES_PER_PLAYER`, behind forever. +const ABANDON_MS: u64 = 30 * 60 * 1000; +/// A human seat that drops mid-hand (page reload) gets at least this long to come back before the +/// timeout policy plays for it. Bots keep the short `reconnect_grace_ms`. +const HUMAN_GRACE_MS: u64 = 20_000; + +enum Decision { + Act(Action, u64), + Timeout(u64), +} + +pub(crate) fn engine_legal(st: &nlhe::State, a: Action) -> bool { + let l = st.legal(); + match a { + Action::Fold => l.can_fold, + Action::Check => l.can_check, + Action::Call => !l.can_check, + Action::RaiseTo(t) => l.can_raise && t >= l.min_raise_to && t <= l.max_raise_to, + } +} + +impl TableTask { + fn hub(&self) -> &Hub { + &self.app.hub + } + + async fn run(mut self) { + loop { + if self.closed { + break; + } + let Some(plan) = self.next_plan().await else { break }; + if let Err(e) = self.play_hand(plan).await { + tracing::error!("table {}: hand failed: {}", self.shared.id, e); + sleep(Duration::from_millis(500)).await; + } + } + let mut inner = self.shared.inner.lock().unwrap(); + inner.status = "closed".into(); + inner.hand = None; + drop(inner); + } + + async fn next_plan(&mut self) -> Option { + loop { + if self.closed { + return None; + } + if self.plan.is_none() && self.abandoned() { + tracing::info!("table {}: abandoned (no connected human), closing", self.shared.id); + self.closed = true; + return None; + } + if let Some(rt) = self.plan.clone() { + match rt.poll(self.lane) { + MatchPoll::Play(p) => return Some(p), + MatchPoll::Finished(status) => { + self.closed = true; + matches::lane_finished(self.app.clone(), rt, status).await; + return None; + } + MatchPoll::Wait => {} + } + } else if let Some(p) = self.free_plan() { + return Some(p); + } + tokio::select! { + _ = self.shared.wake.notified() => {} + cmd = self.rx.recv() => match cmd { + Some(c) => self.handle_idle(c), + None => return None, + }, + _ = sleep(Duration::from_millis(250)) => {} + } + } + } + + /// True once no human seat has been connected for `abandon_after`. A table nobody sat at counts as absent too. + fn abandoned(&mut self) -> bool { + let connected = { + let inner = self.shared.inner.lock().unwrap(); + inner.seats.iter().any(|s| !s.house && s.player_id.as_deref().is_some_and(|p| self.app.hub.connected(p))) + }; + if connected { + self.absent_since = None; + return false; + } + self.absent_since.get_or_insert_with(Instant::now).elapsed() >= self.abandon_after + } + + fn handle_idle(&mut self, cmd: TableCmd) { + match cmd { + TableCmd::Act { conn, data, .. } => { + self.send_error(&conn, ApiError::conflict("not_your_turn", "no decision is pending"), data["decision_id"].as_str()); + } + TableCmd::Resume { .. } | TableCmd::Ready { .. } => {} + TableCmd::Leave { player_id } => self.leave(&player_id), + TableCmd::Close => self.closed = true, + } + } + + fn leave(&mut self, player_id: &str) { + let mut changed = Vec::new(); + { + let mut inner = self.shared.inner.lock().unwrap(); + let in_hand = inner.in_hand; + for (i, s) in inner.seats.iter_mut().enumerate() { + if s.player_id.as_deref() == Some(player_id) { + if in_hand { + s.stand_up = true; + } else { + *s = SeatState::empty(); + } + changed.push(i); + } + } + } + for i in changed { + self.shared.emit_seat_update(self.hub(), i); + } + } + + fn send_error(&self, conn: &ConnTx, e: ApiError, decision_id: Option<&str>) { + let mut d = json!({"code": e.code, "message": e.message, "details": e.details}); + if let Some(id) = decision_id { + d["decision_id"] = json!(id); + } + let env = json!({"v": 1, "type": "error", "table_id": self.shared.id, "t_ms": now_ms(), "data": d}); + let _ = conn.send(env.to_string()); + } + + /// Seats that would be dealt in the next free-table hand. + fn free_plan(&mut self) -> Option { + let inner = self.shared.inner.lock().unwrap(); + let cfg = &inner.config; + let eligible: Vec = inner + .seats + .iter() + .enumerate() + .filter(|(_, s)| match &s.player_id { + Some(p) => !s.stand_up && (s.house || self.app.hub.connected(p)), + None => false, + }) + .map(|(i, _)| i) + .collect(); + if eligible.len() < cfg.min_players_to_deal as usize || !eligible.iter().any(|&i| !inner.seats[i].house) { + return None; + } + let forced = cfg.sandbox.as_ref().and_then(|s| s.button_seat).filter(|b| eligible.contains(b)); + let max = cfg.max_seats as usize; + let button = forced.unwrap_or_else(|| match inner.button_seat { + Some(prev) => (1..=max).map(|k| (prev + k) % max).find(|s| eligible.contains(s)).unwrap(), + None => eligible[0], + }); + let hand_no = self.hand_counter + 1; + Some(HandPlan { + hand_no, + deal_no: None, + rotation: None, + button, + assignment: None, + dealt: eligible, + deck_index: self.hand_counter as u64, + crn_key: hand_no as u64, + seed: self.seed.clone(), + match_id: None, + hide_cards: false, + }) + } + + fn player(&mut self, pid: &str) -> Res { + if let Some(p) = self.players.get(pid) { + return Ok(p.clone()); + } + let p = self.app.store.get_player(pid)?.ok_or_else(|| ApiError::not_found("player"))?; + self.players.insert(pid.to_string(), p.clone()); + Ok(p) + } + + fn emit_evs(&self, hand_id: &str, evs: Vec, log: &mut Vec, hide: bool) -> Vec { + let mut out = Vec::new(); + for mut e in evs { + if hide && e.kind == "hand_end" { + redact_hand_end(&mut e.data); + } + let env = self.shared.emit(self.hub(), Some(hand_id), e.kind, e.seq, e.to, e.data); + log.push(env.clone()); + out.push(env); + } + out + } + + fn publish_view(&self, r: &HandRunner) { + let mut inner = self.shared.inner.lock().unwrap(); + inner.hand = Some(r.public_state()); + } + + async fn play_hand(&mut self, plan: HandPlan) -> Res<()> { + let started_ms = now_ms(); + let cfg = self.shared.inner.lock().unwrap().config.clone(); + let lean = cfg.is_benchmark(); + if let Some(assign) = &plan.assignment { + for (s, pid) in assign.iter().enumerate() { + let rec = self.player(pid)?; + let mut inner = self.shared.inner.lock().unwrap(); + inner.seats[s] = SeatState { + player_id: Some(rec.player_id.clone()), + name: Some(rec.name.clone()), + kind: rec.kind.clone(), + house: rec.house, + stack: cfg.starting_stack, + stand_up: false, + }; + } + } + let first_hand = self.hand_counter == 0; + let (seats, sitting_out) = { + let mut inner = self.shared.inner.lock().unwrap(); + let mut seats = Vec::new(); + let mut out = Vec::new(); + for (i, s) in inner.seats.iter_mut().enumerate() { + let Some(pid) = s.player_id.clone() else { continue }; + if plan.dealt.contains(&i) { + let mut stack = match cfg.stack_mode { + StackMode::Reset => cfg.starting_stack, + StackMode::Carry if s.stack > 0 => s.stack, + StackMode::Carry => cfg.starting_stack, + }; + if first_hand { + if let Some(v) = cfg.sandbox.as_ref().and_then(|b| b.stacks.as_ref()).and_then(|v| v.get(i)) { + stack = *v; + } + } + s.stack = stack; + seats.push(SeatInfo { seat: i, player_id: pid, name: s.name.clone().unwrap_or_default(), kind: s.kind.clone(), stack }); + } else { + out.push(SeatInfo { seat: i, player_id: pid, name: s.name.clone().unwrap_or_default(), kind: s.kind.clone(), stack: s.stack }); + } + } + inner.button_seat = Some(plan.button); + inner.in_hand = true; + inner.status = "running".into(); + (seats, out) + }; + // Deck: seeded, optionally with a sandbox prefix. + let mut dk = deck::deal_deck(&plan.seed, plan.deck_index); + if cfg.is_sandbox() { + if let Some(pre) = cfg.sandbox.as_ref().and_then(|s| s.decks.get(plan.deck_index as usize)) { + let parsed: Option> = pre.iter().map(|c| cards::parse_card(c)).collect(); + match parsed { + Some(p) if p.iter().collect::>().len() == p.len() && p.len() <= 52 => dk = deck::with_prefix(&dk, &p), + _ => tracing::warn!("table {}: invalid sandbox deck prefix ignored", self.shared.id), + } + } + } + let owner = plan.match_id.clone().unwrap_or_else(|| self.shared.id.clone()); + let setup = HandSetup { + table_id: self.shared.id.clone(), + hand_id: format!("{owner}-h{}", plan.hand_no), + match_id: plan.match_id.clone(), + hand_no: plan.hand_no, + deal_no: plan.deal_no, + rotation: plan.rotation, + cfg: cfg.clone(), + button_seat: plan.button, + seats, + sitting_out, + deck: dk, + salt: random_hex(), + started_ms, + lean, + }; + let hand_id = setup.hand_id.clone(); + let (mut runner, opening) = match HandRunner::new(setup) { + Ok(x) => x, + Err(e) => { + self.shared.inner.lock().unwrap().in_hand = false; + return Err(e); + } + }; + self.hand_counter += 1; + { + let mut inner = self.shared.inner.lock().unwrap(); + inner.hand_id = Some(hand_id.clone()); + if !lean { + inner.holes = (0..runner.n()).filter_map(|i| runner.hole_cards_of_seat(runner.seat_of(i)).map(|c| (runner.seat_of(i), c))).collect(); + } + } + // House players. + let seed64 = seed64(&plan.seed); + let mut houses: Vec>> = Vec::new(); + for idx in 0..runner.n() { + let pid = runner.info[idx].player_id.clone(); + let is_house = self.player(&pid)?.house; + let p = is_house + .then(|| self.app.house.key_of(&pid)) + .flatten() + .and_then(|k| self.app.house.get(&k)) + .map(|f| f.new_player(idx, &runner.ecfg, mix(mix(seed64, plan.hand_no as u64), idx as u64))); + houses.push(p); + } + let has_remote = houses.iter().any(|h| h.is_none()); + let mut crn = cards::Rng::new(mix(seed64, plan.crn_key)); + let mut log: Vec = Vec::new(); + self.emit_evs(&hand_id, opening, &mut log, false); + if !lean { + self.publish_view(&runner); + } + + while !runner.is_over() { + let idx = runner.to_act_idx().unwrap(); + let seat = runner.seat_of(idx); + let applied = if houses[idx].is_some() { + if !lean { + let turn = runner.begin_turn(0, 0).unwrap().event.clone(); + self.emit_evs(&hand_id, vec![turn], &mut log, false); + } + let u = crn.f64(); + let hole = runner.deal.holes[idx]; + let action = { + let view = View { cfg: &runner.ecfg, state: &runner.st, board: runner.board(), history: &runner.ehist, seat: idx }; + houses[idx].as_mut().unwrap().act(&view, hole, u) + }; + let (action, timeout) = if engine_legal(&runner.st, action) { + (action, false) + } else { + runner.anomalies.push(format!("house bot at seat {seat} chose an illegal action {action:?}")); + (runner.timeout_action(), true) + }; + runner.apply(action, timeout, 0) + } else { + match self.remote_decision(&mut runner, &hand_id, &mut log, plan.hide_cards).await { + Decision::Act(a, think) => runner.apply(a, false, think), + Decision::Timeout(think) => { + let a = runner.timeout_action(); + runner.apply(a, true, think) + } + } + }; + for p in houses.iter_mut().flatten() { + p.observe(&applied.pre, applied.idx, applied.action); + for &l in &applied.reveals { + p.observe_board(&runner.deal.board[..l]); + } + } + self.emit_evs(&hand_id, applied.events, &mut log, false); + if !lean { + self.publish_view(&runner); + } + if self.closed { + break; + } + } + if !runner.is_over() { + // Table closed mid-hand: abandon without recording. + let mut inner = self.shared.inner.lock().unwrap(); + inner.in_hand = false; + inner.hand = None; + return Ok(()); + } + for p in houses.iter_mut().flatten() { + p.finish(&runner.deal, &runner.ehist, &runner.st); + } + let (end_events, hist) = runner.finish(!lean || has_remote); + self.emit_evs(&hand_id, end_events, &mut log, plan.hide_cards); + // Settle seats. + let mut gone = Vec::new(); + { + let mut inner = self.shared.inner.lock().unwrap(); + for r in &hist.results { + inner.seats[r.seat as usize].stack = r.stack_end; + } + for (i, s) in inner.seats.iter_mut().enumerate() { + if s.stand_up && plan.assignment.is_none() { + *s = SeatState::empty(); + gone.push(i); + } + } + inner.in_hand = false; + inner.hand = None; + inner.hand_id = None; + inner.holes.clear(); + inner.status = if self.plan.is_some() { "running".into() } else { "waiting".into() }; + } + for i in gone { + self.shared.emit_seat_update(self.hub(), i); + } + if self.plan.is_some() || self.app.cfg.save_free_hands { + // Batched, off the hand loop; benchmark hands keep no event log. + let events = if lean { Vec::new() } else { log }; + if let Some(rt) = &self.plan { + let up = rt.record_hand(self.lane, &hist, self.app.store.as_ref()); + self.app.writer.push(hist, events); + if let Some((d, progress)) = up { + self.shared.emit(self.hub(), None, "match_update", None, None, d); + if let (Some(p), Some(b)) = (progress, &rt.bench) { + let env = json!({"v": 1, "type": "benchmark_progress", "t_ms": now_ms(), "data": p}); + self.app.hub.send(&b.player_id, &env.to_string()); + } + } + } else { + self.app.writer.push(hist, events); + } + } else if let Some(rt) = &self.plan { + let _ = rt.record_hand(self.lane, &hist, self.app.store.as_ref()); + } + if self.plan.is_none() && !lean { + let delay = cfg.hand_delay_ms.unwrap_or(self.app.cfg.hand_delay_ms); + if delay > 0 { + self.pause_between_hands(Duration::from_millis(delay)).await; + } + } + // Never starve other tasks on this worker when every seat is a house bot. + tokio::task::yield_now().await; + Ok(()) + } + + /// The pause after a hand on a free table. A seated player can end it early with `next_hand` + /// (so a UI can hold the table as long as the player wants to read the result). + async fn pause_between_hands(&mut self, delay: Duration) { + let until = Instant::now() + delay; + loop { + match timeout_at(until, self.rx.recv()).await { + Err(_) | Ok(None) => return, + Ok(Some(TableCmd::Ready { player_id })) => { + let seated = self.shared.inner.lock().unwrap().seats.iter().any(|s| s.player_id.as_deref() == Some(player_id.as_str())); + if seated { + return; + } + } + Ok(Some(TableCmd::Leave { player_id })) => self.leave(&player_id), + Ok(Some(TableCmd::Close)) => { + self.closed = true; + return; + } + Ok(Some(TableCmd::Resume { .. })) => {} + Ok(Some(TableCmd::Act { conn, data, .. })) => { + self.send_error(&conn, ApiError::conflict("not_your_turn", "no decision is pending"), data["decision_id"].as_str()); + } + } + } + } + + /// Ask a remote seat for its action; returns when it answers or its deadline passes. + async fn remote_decision(&mut self, runner: &mut HandRunner, hand_id: &str, log: &mut Vec, hide: bool) -> Decision { + let idx = runner.to_act_idx().unwrap(); + let pid = runner.info[idx].player_id.clone(); + let cfg_time = runner.setup.cfg.decision_time_ms; + let bank0 = *self.banks.entry(pid.clone()).or_insert(runner.setup.cfg.time_bank_ms); + let base = Duration::from_millis(cfg_time); + let start = Instant::now(); + let hard = start + base + Duration::from_millis(bank0); + let deadline_ms = now_ms() + cfg_time + bank0; + let turn = runner.begin_turn(deadline_ms, bank0).unwrap().clone(); + let decision_id = turn.decision_id.clone(); + let env = self.emit_evs(hand_id, vec![turn.event.clone()], log, hide).remove(0); + let env_str = env.to_string(); + + let account = |this: &mut Self, elapsed: u64, timed_out: bool| { + let over = elapsed.saturating_sub(cfg_time); + let b = this.banks.entry(pid.clone()).or_insert(0); + *b = if timed_out { 0 } else { b.saturating_sub(over) }; + }; + + // Webhook seats are asked over HTTP instead of the socket. + if self.app.cfg.enable_webhooks && !self.app.hub.connected(&pid) { + if let Ok(rec) = self.player(&pid) { + if let (Some(url), Some(secret)) = (rec.webhook_url.clone(), rec.webhook_secret.clone()) { + let remaining = hard.saturating_duration_since(Instant::now()); + let res = crate::webhook::ask(url, secret, env_str.clone(), remaining).await; + let elapsed = start.elapsed().as_millis() as u64; + if let Ok((req, _)) = res { + if let Ok(a) = runner.validate(&req) { + account(self, elapsed, false); + return Decision::Act(a, elapsed); + } + } + account(self, elapsed, true); + return Decision::Timeout(elapsed); + } + } + } + + let mut grace = Duration::from_millis(self.app.cfg.reconnect_grace_ms); + if self.plan.is_none() && self.player(&pid).map(|p| p.kind == "human").unwrap_or(false) { + grace = grace.max(Duration::from_millis(HUMAN_GRACE_MS)); + } + let mut wait_until = if self.app.hub.connected(&pid) { hard } else { hard.min(Instant::now() + grace) }; + loop { + let cmd = match timeout_at(wait_until, self.rx.recv()).await { + Err(_) | Ok(None) => { + let elapsed = start.elapsed().as_millis() as u64; + account(self, elapsed, true); + return Decision::Timeout(elapsed); + } + Ok(Some(c)) => c, + }; + match cmd { + TableCmd::Close => { + self.closed = true; + let elapsed = start.elapsed().as_millis() as u64; + return Decision::Timeout(elapsed); + } + TableCmd::Leave { player_id } => self.leave(&player_id), + TableCmd::Ready { .. } => {} + TableCmd::Resume { player_id, conn } => { + if player_id == pid { + let _ = conn.send(env_str.clone()); + wait_until = hard; + } + } + TableCmd::Act { player_id, data, conn } => { + let did = data["decision_id"].as_str().unwrap_or("").to_string(); + if player_id != pid { + self.send_error(&conn, ApiError::conflict("not_your_turn", "it is not your turn"), Some(&did)); + continue; + } + if data["hand_id"].as_str().map(|h| h != hand_id).unwrap_or(false) { + self.send_error(&conn, ApiError::conflict("stale_decision", "hand_id does not match the current hand"), Some(&did)); + continue; + } + if did != decision_id { + if self.answered.contains(&did) { + continue; // duplicate act: idempotent + } + self.send_error(&conn, ApiError::conflict("stale_decision", "unknown or expired decision_id"), Some(&did)); + continue; + } + let Some(kind) = data["type"].as_str() else { + self.send_error(&conn, ApiError::new(422, "illegal_action", "`type` is required"), Some(&did)); + continue; + }; + let req = ActReq { kind: kind.to_string(), to: data["to"].as_i64() }; + match runner.validate(&req) { + Ok(a) => { + let elapsed = start.elapsed().as_millis() as u64; + self.answered.insert(did); + if self.answered.len() > 4096 { + self.answered.clear(); + } + account(self, elapsed, false); + return Decision::Act(a, elapsed); + } + Err(e) => { + self.send_error(&conn, e, Some(&did)); + // fresh your_turn with the same decision_id while time remains + self.app.hub.send(&pid, &env_str); + } + } + } + } + } + } +} + +/// Drop hole cards, runout and deck from a `hand_end` payload (match `reveal: "match_end"`): +/// only the cards shown at showdown stay public. +pub(crate) fn redact_hand_end(d: &mut Value) { + let shown: Vec<(String, Value)> = d["showdown"] + .as_array() + .map(|a| a.iter().filter(|x| x["shown"] == json!(true)).map(|x| (x["seat"].to_string(), x["cards"].clone())).collect()) + .unwrap_or_default(); + let mut m = serde_json::Map::new(); + for (k, v) in shown { + m.insert(k, v); + } + d["hole_cards"] = Value::Object(m); + d["runout"] = json!([]); + d["deck_reveal"] = Value::Null; +} diff --git a/arena/server/src/util.rs b/arena/server/src/util.rs new file mode 100644 index 00000000..a459eed5 --- /dev/null +++ b/arena/server/src/util.rs @@ -0,0 +1,76 @@ +//! Small helpers: clocks, ids, hashing, hex. + +use hmac::{Hmac, Mac}; +use sha2::{Digest, Sha256}; +use std::time::{SystemTime, UNIX_EPOCH}; + +pub fn now_ms() -> u64 { + SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0) +} + +/// ISO-8601 UTC with millisecond precision, from epoch millis. +pub fn iso(ms: u64) -> String { + let secs = (ms / 1000) as i64; + let days = secs.div_euclid(86_400); + let rem = secs.rem_euclid(86_400); + // civil-from-days (Howard Hinnant) + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let y = yoe + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = if m <= 2 { y + 1 } else { y }; + format!( + "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}.{:03}Z", + y, + m, + d, + rem / 3600, + (rem % 3600) / 60, + rem % 60, + ms % 1000 + ) +} + +pub fn now_iso() -> String { + iso(now_ms()) +} + +/// Short random id with a prefix, e.g. `t_3f9a1c22b7d4`. +pub fn new_id(prefix: &str) -> String { + let u = uuid::Uuid::new_v4().simple().to_string(); + format!("{prefix}_{}", &u[..12]) +} + +/// 256 bits of OS randomness as hex. +pub fn random_hex() -> String { + format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple()) +} + +pub fn sha256_hex(data: &[u8]) -> String { + hex::encode(Sha256::digest(data)) +} + +pub fn hmac_sha256(key: &[u8], msg: &[u8]) -> Vec { + let mut m = as Mac>::new_from_slice(key).expect("hmac accepts any key length"); + m.update(msg); + m.finalize().into_bytes().to_vec() +} + +/// First 8 bytes of sha256(s) as a u64 (stable seed derivation for the bench RNGs). +pub fn seed64(s: &str) -> u64 { + let d = Sha256::digest(s.as_bytes()); + u64::from_le_bytes(d[..8].try_into().unwrap()) +} + +pub fn ct_eq(a: &str, b: &str) -> bool { + let (a, b) = (a.as_bytes(), b.as_bytes()); + if a.len() != b.len() { + return false; + } + a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 +} diff --git a/arena/server/src/webhook.rs b/arena/server/src/webhook.rs new file mode 100644 index 00000000..29739aad --- /dev/null +++ b/arena/server/src/webhook.rs @@ -0,0 +1,29 @@ +//! Webhook mode (TABLE_API.md section 11): POST the `your_turn` envelope, signed with +//! `X-Sharingan-Signature: sha256=HMAC(secret, body)`, and read the `act` data from the response. + +use crate::hand::ActReq; +use crate::util::hmac_sha256; +use serde_json::Value; +use std::time::Duration; + +pub async fn ask(url: String, secret: String, body: String, timeout: Duration) -> Result<(ActReq, Option), String> { + let r = tokio::task::spawn_blocking(move || { + let sig = format!("sha256={}", hex::encode(hmac_sha256(secret.as_bytes(), body.as_bytes()))); + let resp = ureq::post(&url) + .timeout(timeout) + .set("content-type", "application/json") + .set("x-sharingan-signature", &sig) + .send_string(&body) + .map_err(|e| e.to_string())?; + let v: Value = resp.into_json().map_err(|e| e.to_string())?; + Ok::(v) + }) + .await + .map_err(|e| e.to_string())??; + // Accept either the bare act data or a full `act` envelope. + let data = if r.get("data").is_some() { r["data"].clone() } else { r }; + let kind = data["type"].as_str().ok_or("response has no `type`")?.to_string(); + let to = data["to"].as_i64(); + let decision = data["decision_id"].as_str().map(|s| s.to_string()); + Ok((ActReq { kind, to }, decision)) +} diff --git a/arena/server/src/worker.rs b/arena/server/src/worker.rs new file mode 100644 index 00000000..157e93b0 --- /dev/null +++ b/arena/server/src/worker.rs @@ -0,0 +1,1257 @@ +//! Headless match worker: `sharingan-arena run --bot "" --track ladder-v1 ...`. +//! +//! No HTTP server, no database. The worker plays the duplicate benchmark of a track (same frozen +//! panel, seed, deal schedule, house-bot randomness and AIVAT as the server's benchmark runs) against +//! a bot that runs as a SUBPROCESS and talks newline-delimited JSON over its stdin/stdout (the "pipe +//! protocol", TABLE_API.md section 14). One bot process per lane; lanes are OS threads. +//! +//! Failure policy (documented in TABLE_API.md 14.6): +//! * a decision that does not arrive in `decision_timeout_ms` is played as check-if-free-else-fold +//! (`timeout:true`), the process group is killed and a fresh process takes over (up to `max_restarts` +//! per lane, then the lane is dead); +//! * a crash (exit, EOF, protocol garbage, `bye`) kills the lane: the bot folds (or checks when free) +//! every remaining decision, i.e. the remaining hands of that lane are FORFEITS. They are still +//! dealt, played and AIVAT-scored (so `hands` == `hands_planned`), and counted in `forfeit_hands`. +//! +//! The result is signed with HMAC-SHA256 over its canonical JSON (`--sign-key-file`), see +//! `sign_result` / `verify_result`; `POST /v1/results` (results.rs) accepts it as verified. + +use crate::benchmarks::{self, Track}; +use crate::config::ServerConfig; +use crate::deck; +use crate::hand::{ActReq, HandRunner, HandSetup, SeatInfo}; +use crate::house::{house_id, HouseRegistry}; +use crate::matches::{self, HandRec}; +use crate::model::*; +use crate::util::*; +use bench::aivat::{EquityEstimator, Mode}; +use bench::mix; +use bench::policy::Player; +use nlhe::Action; +use serde_json::{json, Value}; +use std::collections::HashMap; +use std::io::{self, Write}; +use std::os::unix::io::{AsRawFd, RawFd}; +use std::os::unix::process::CommandExt; +use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio}; +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; +use std::time::{Duration, Instant}; + +pub const PROTOCOL: u32 = 1; +pub const RESULT_SCHEMA: &str = "sharingan-worker-result/1"; +pub const BOT_ID: &str = "bot"; +const BLOCK_DEALS: u32 = 12; +const MAX_LINE: usize = 4 << 20; + +#[derive(Clone, Debug)] +pub struct WorkerOpts { + pub bot_cmd: String, + pub track: String, + pub hands: u32, + pub lanes: usize, + /// `None` = the track's frozen seed (comparable with server runs). A secret per-run seed (`run:`, from `--seed-file`) + /// gives fresh deals; it never reaches the bot (see `hand_prefix`). + pub seed: Option, + pub decision_timeout_ms: u64, + pub startup_timeout_ms: u64, + pub max_restarts: u32, + pub player_id: Option, + /// "full" (default, as the server), "cards" or "off". + pub aivat: String, + pub quiet: bool, + /// Write one JSON line per hand (hand_no, deal_no, rotation, deck digest, nets) here. + pub hands_out: Option, + /// House-bot configuration (blueprint, buckets, sizing); `None` = from the environment (`ARENA_BLUEPRINT`, ...). + pub house_cfg: Option, + /// Isolation for duplicate deals (`--rotation-uids`, the hosted runner always sets it): rotation r's bot processes run + /// as uid `rotation_uids[r]` (the worker must be root), and `scrub_cmd UID` ends everything that uid left behind + /// (processes, files, IPC) before the next rotation starts. Each deal appears once per rotation, so with this no bot + /// process can remember a deal it saw from another seat. + pub rotation_uids: Option<[u32; 6]>, + pub scrub_cmd: String, +} + +impl Default for WorkerOpts { + fn default() -> Self { + WorkerOpts { + bot_cmd: String::new(), + track: "ladder-v1".into(), + hands: benchmarks::DEFAULT_HANDS, + lanes: std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4).min(8), + seed: None, + decision_timeout_ms: 5000, + startup_timeout_ms: 30_000, + max_restarts: 3, + player_id: None, + aivat: "full".into(), + rotation_uids: None, + scrub_cmd: "sharingan-scrub".into(), + quiet: false, + hands_out: None, + house_cfg: None, + } + } +} + +// ------------------------------------------------------------------------------------ pipe IO + +#[derive(Debug)] +pub enum IoErr { + Timeout, + Eof, + Broken(String), +} + +fn remaining_ms(deadline: Instant) -> Option { + let d = deadline.checked_duration_since(Instant::now())?; + if d.is_zero() { + return None; + } + Some(((d.as_micros() + 999) / 1000).min(i32::MAX as u128) as i32) +} + +fn set_nonblocking(fd: RawFd) { + unsafe { + let fl = libc::fcntl(fd, libc::F_GETFL); + libc::fcntl(fd, libc::F_SETFL, fl | libc::O_NONBLOCK); + } +} + +fn poll_fd(fd: RawFd, events: i16, deadline: Instant) -> Result<(), IoErr> { + let Some(ms) = remaining_ms(deadline) else { return Err(IoErr::Timeout) }; + let mut p = libc::pollfd { fd, events, revents: 0 }; + let r = unsafe { libc::poll(&mut p, 1, ms) }; + if r == 0 { + return Err(IoErr::Timeout); + } + Ok(()) +} + +/// Copy a bot's stderr into the worker's, line by line, up to 1 MiB per process (the rest is drained and dropped), so +/// the bot's own prints still reach the job log. The thread ends when the last holder of the pipe exits. +fn forward_stderr(err: std::process::ChildStderr) { + std::thread::spawn(move || { + use std::io::{Read, Write}; + // reads in chunks (a line without an end can't grow memory); lines over 4 KiB are cut + let (mut left, mut cut) = (1usize << 20, false); + let (mut r, mut buf, mut line) = (err, [0u8; 8192], Vec::with_capacity(4096)); + let mut emit = |line: &mut Vec, left: &mut usize, cut: &mut bool| { + if line.len() < *left { + *left -= line.len() + 1; + let mut e = io::stderr().lock(); + let _ = e.write_all(line); + let _ = e.write_all(b"\n"); + } else if !*cut { + *cut = true; + let _ = writeln!(io::stderr(), "[bot stderr cut at 1 MiB]"); + } + line.clear(); + }; + loop { + let n = match r.read(&mut buf) { + Ok(0) | Err(_) => break, + Ok(n) => n, + }; + for &b in &buf[..n] { + if b == b'\n' { + emit(&mut line, &mut left, &mut cut); + } else if line.len() < 4096 { + line.push(b); + } + } + } + if !line.is_empty() { + emit(&mut line, &mut left, &mut cut); + } + }); +} + +/// A bot subprocess. Both pipes are non-blocking and driven with `poll` against a deadline, so a bot +/// that stops reading or never answers can never hang the lane thread. +pub struct BotProc { + child: Child, + _stdin: ChildStdin, + _stdout: ChildStdout, + wfd: RawFd, + rfd: RawFd, + buf: Vec, + start: usize, +} + +impl BotProc { + pub fn spawn(cmd: &str, lane: usize, lanes: usize) -> io::Result { + let mut c = Command::new("sh"); + c.arg("-c").arg(cmd); + // stderr: a pipe of its own, copied into ours (`forward_stderr`). Never our stderr itself: a bot that shares the + // worker's log file could read or measure what an earlier rotation wrote there. + c.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()); + // the bot must not inherit the operator's secrets (or a seed) from the worker's environment + for k in ["ARENA_ADMIN_TOKEN", "ARENA_RUNNER_TOKEN", "ARENA_WORKER_KEYS", "ARENA_DATABASE_URL", "ARENA_SEED", "SHARINGAN_SEED"] { + c.env_remove(k); + } + c.env("SHARINGAN_PIPE", "1").env("SHARINGAN_LANE", lane.to_string()).env("SHARINGAN_LANES", lanes.to_string()); + c.process_group(0); + let mut child = c.spawn()?; + if let Some(err) = child.stderr.take() { + forward_stderr(err); + } + let stdin = child.stdin.take().unwrap(); + let stdout = child.stdout.take().unwrap(); + let (wfd, rfd) = (stdin.as_raw_fd(), stdout.as_raw_fd()); + set_nonblocking(wfd); + set_nonblocking(rfd); + Ok(BotProc { child, _stdin: stdin, _stdout: stdout, wfd, rfd, buf: Vec::with_capacity(1 << 16), start: 0 }) + } + + pub fn send(&mut self, line: &str, deadline: Instant) -> Result<(), IoErr> { + let mut data = Vec::with_capacity(line.len() + 1); + data.extend_from_slice(line.as_bytes()); + data.push(b'\n'); + let mut off = 0; + while off < data.len() { + let n = unsafe { libc::write(self.wfd, data[off..].as_ptr() as *const libc::c_void, data.len() - off) }; + if n >= 0 { + off += n as usize; + continue; + } + let e = io::Error::last_os_error(); + match e.kind() { + io::ErrorKind::WouldBlock => poll_fd(self.wfd, libc::POLLOUT, deadline)?, + io::ErrorKind::Interrupted => {} + io::ErrorKind::BrokenPipe => return Err(IoErr::Eof), + _ => return Err(IoErr::Broken(e.to_string())), + } + } + Ok(()) + } + + pub fn recv(&mut self, deadline: Instant) -> Result { + let mut scan = self.start; + loop { + if let Some(p) = self.buf[scan..].iter().position(|&b| b == b'\n') { + let end = scan + p; + let line = String::from_utf8_lossy(&self.buf[self.start..end]).into_owned(); + self.start = end + 1; + if self.start == self.buf.len() { + self.buf.clear(); + self.start = 0; + } + return Ok(line); + } + scan = self.buf.len(); + // A bot that keeps the pipe busy (a flood of noise, a never-ending line) never makes `read` block, so + // the poll below would never see the deadline: check it on every pass. + if Instant::now() >= deadline { + return Err(IoErr::Timeout); + } + if self.buf.len() - self.start > MAX_LINE { + return Err(IoErr::Broken("line longer than 4 MiB".into())); + } + if self.start > (1 << 20) { + self.buf.drain(..self.start); + scan -= self.start; + self.start = 0; + } + let mut tmp = [0u8; 65536]; + let n = unsafe { libc::read(self.rfd, tmp.as_mut_ptr() as *mut libc::c_void, tmp.len()) }; + if n > 0 { + self.buf.extend_from_slice(&tmp[..n as usize]); + continue; + } + if n == 0 { + return Err(IoErr::Eof); + } + let e = io::Error::last_os_error(); + match e.kind() { + io::ErrorKind::WouldBlock => poll_fd(self.rfd, libc::POLLIN, deadline)?, + io::ErrorKind::Interrupted => {} + _ => return Err(IoErr::Broken(e.to_string())), + } + } + } + + /// SIGKILL the whole process group (the `sh -c` wrapper and whatever it started) and reap. + pub fn kill(&mut self) { + unsafe { + libc::kill(-(self.child.id() as i32), libc::SIGKILL); + } + let _ = self.child.kill(); + // Never block on a process that does not die (a different uid we may not signal, an uninterruptible + // state): close our end of its stdin so it sees EOF, wait a bounded time, then leave it to init. + let t0 = Instant::now(); + loop { + match self.child.try_wait() { + Ok(Some(_)) | Err(_) => return, + Ok(None) if t0.elapsed() > Duration::from_secs(3) => break, + Ok(None) => std::thread::sleep(Duration::from_millis(2)), + } + } + self.close_stdin(); + } + + /// Replace our write end of the bot's stdin by /dev/null so the bot reads EOF. + fn close_stdin(&mut self) { + unsafe { + let nul = libc::open(c"/dev/null".as_ptr(), libc::O_RDONLY); + if nul >= 0 { + libc::dup2(nul, self.wfd); + libc::close(nul); + } + } + } + + /// Polite end: `bye`, close stdin, wait a little, then kill. + pub fn finish(&mut self, bye: &str) { + let _ = self.send(bye, Instant::now() + Duration::from_millis(200)); + let t0 = Instant::now(); + self.close_stdin(); // the bot reads EOF + while t0.elapsed() < Duration::from_millis(1500) { + if let Ok(Some(_)) = self.child.try_wait() { + break; + } + std::thread::sleep(Duration::from_millis(5)); + } + self.kill(); + } +} + +impl Drop for BotProc { + fn drop(&mut self) { + self.kill(); + } +} + +// ------------------------------------------------------------------------------------ canonical JSON + signature + +/// Canonical JSON: UTF-8, object keys sorted (recursively), no whitespace, integers as integers, floats with +/// exactly 6 decimals (`{:.6}`). This is what is signed. +pub fn canonical_json(v: &Value) -> String { + let mut s = String::new(); + canon(v, &mut s); + s +} + +fn canon(v: &Value, out: &mut String) { + match v { + Value::Object(m) => { + let mut keys: Vec<&String> = m.keys().collect(); + keys.sort(); + out.push('{'); + for (i, k) in keys.iter().enumerate() { + if i > 0 { + out.push(','); + } + out.push_str(&serde_json::to_string(k).unwrap()); + out.push(':'); + canon(&m[*k], out); + } + out.push('}'); + } + Value::Array(a) => { + out.push('['); + for (i, x) in a.iter().enumerate() { + if i > 0 { + out.push(','); + } + canon(x, out); + } + out.push(']'); + } + // Floats are written with exactly 6 decimals: a 1-ulp difference between two JSON libraries' parsers + // (serde_json's default float parsing is not exactly round-trip) must not change the signed text. + Value::Number(n) if n.is_f64() => out.push_str(&format!("{:.6}", n.as_f64().unwrap())), + other => out.push_str(&other.to_string()), + } +} + +fn r6(x: f64) -> f64 { + (x * 1e6).round() / 1e6 +} + +/// `id=secret` or just `secret` (id `default`). +pub fn parse_key_spec(s: &str) -> Option<(String, String)> { + let s = s.trim(); + if s.is_empty() { + return None; + } + match s.split_once('=') { + Some((id, k)) if !id.is_empty() && !k.is_empty() && !id.contains(char::is_whitespace) => Some((id.trim().into(), k.trim().into())), + _ => Some(("default".into(), s.into())), + } +} + +/// `ARENA_WORKER_KEYS`: comma separated `id=secret` entries. +pub fn parse_keys(s: &str) -> Vec<(String, String)> { + s.split(',').filter_map(parse_key_spec).collect() +} + +fn signing_input(result: &Value) -> String { + let mut v = result.clone(); + if let Some(o) = v.as_object_mut() { + o.remove("signature"); + } + canonical_json(&v) +} + +/// Add `signature: {alg, key_id, value}` (HMAC-SHA256 over the canonical result without `signature`). +pub fn sign_result(result: &mut Value, key_id: &str, secret: &str) { + let mac = hex::encode(hmac_sha256(secret.as_bytes(), signing_input(result).as_bytes())); + result["signature"] = json!({"alg": "HMAC-SHA256", "key_id": key_id, "value": mac}); +} + +/// Check the signature of `result` against the configured keys. Returns the matching key id. +pub fn verify_result(result: &Value, keys: &[(String, String)]) -> Result { + let sig = result.get("signature").and_then(|s| s.as_object()).ok_or("unsigned result")?; + if sig.get("alg").and_then(|a| a.as_str()).map(|a| !a.eq_ignore_ascii_case("hmac-sha256")).unwrap_or(false) { + return Err("unsupported signature algorithm"); + } + let value = sig.get("value").and_then(|v| v.as_str()).ok_or("signature has no value")?; + if keys.is_empty() { + return Err("no worker keys configured (ARENA_WORKER_KEYS)"); + } + let input = signing_input(result); + let want_id = sig.get("key_id").and_then(|v| v.as_str()); + for (id, secret) in keys { + if want_id.map(|w| w != id).unwrap_or(false) { + continue; + } + let mac = hex::encode(hmac_sha256(secret.as_bytes(), input.as_bytes())); + if ct_eq(&mac, &value.to_ascii_lowercase()) { + return Ok(id.clone()); + } + } + Err("bad signature") +} + +// ------------------------------------------------------------------------------------ the match + +#[derive(Default, Clone, Debug)] +struct LaneStats { + lane: usize, + hands: u32, + decisions: u64, + timeouts: u32, + restarts: u32, + illegal_actions: u32, + forfeit_hands: u32, + noise_lines: u64, + anomalies: u32, + crashed: Option, + wall_ms: u64, + bot_wait_ms: f64, + aivat_ms: f64, +} + +struct LaneOut { + recs: Vec, + aivat: HashMap, + log: Vec<(u32, Option, u32, u64, [i64; 6])>, + stats: LaneStats, +} + +struct Cx<'a> { + opts: &'a WorkerOpts, + house: &'a HouseRegistry, + est: &'a EquityEstimator, + mode: Option, + participants: Vec, + cfg: TableConfig, + seed: String, + seed64: u64, + /// Prefix of every `hand_id` the bot sees. The track seed itself for the frozen deals (public anyway); + /// for any other seed a one-way hash of it, so a secret per-run seed never reaches the bot. + hand_prefix: String, + planned: u32, + lanes: usize, + done: AtomicU32, + /// The deals come from a secret per-run seed (not the public track seed). + seed_secret: bool, +} + +enum Decision { + Act(Action, u64), + Timeout(u64), +} + +struct Lane<'a> { + cx: &'a Cx<'a>, + lane: usize, + table_id: String, + bot: Option, + /// The bot command of the rotation being played (wrapped for its uid when isolated). + bot_cmd: String, + table_seq: u64, + st: LaneStats, +} + +fn envelope(kind: &str, table_id: &str, hand_id: Option<&str>, seq: Option, table_seq: u64, data: &str) -> String { + let mut s = String::with_capacity(data.len() + 160); + s.push_str("{\"v\":1,\"type\":\""); + s.push_str(kind); + s.push_str("\",\"table_id\":\""); + s.push_str(table_id); + s.push('"'); + if let Some(h) = hand_id { + s.push_str(",\"hand_id\":\""); + s.push_str(h); + s.push('"'); + } + if let Some(q) = seq { + s.push_str(",\"seq\":"); + s.push_str(&q.to_string()); + } + s.push_str(",\"table_seq\":"); + s.push_str(&table_seq.to_string()); + s.push_str(",\"t_ms\":"); + s.push_str(&now_ms().to_string()); + s.push_str(",\"data\":"); + s.push_str(data); + s.push('}'); + s +} + +impl<'a> Lane<'a> { + fn new(cx: &'a Cx<'a>, lane: usize) -> Self { + Lane { cx, lane, table_id: format!("lane-{lane}"), bot: None, bot_cmd: String::new(), table_seq: 0, st: LaneStats { lane, ..Default::default() } } + } + + fn alive(&self) -> bool { + self.st.crashed.is_none() + } + + fn die(&mut self, why: String) { + if self.st.crashed.is_none() { + self.st.crashed = Some(why); + } + if let Some(mut b) = self.bot.take() { + b.kill(); + } + } + + /// Start the bot process and do the hello/welcome handshake. + fn start_bot(&mut self) -> Result<(), String> { + let o = self.cx.opts; + let mut b = BotProc::spawn(&self.bot_cmd, self.lane, self.cx.lanes).map_err(|e| format!("spawn failed: {e}"))?; + let deadline = Instant::now() + Duration::from_millis(o.startup_timeout_ms); + loop { + if Instant::now() >= deadline { + return Err(format!("no hello within {} ms", o.startup_timeout_ms)); + } + let line = match b.recv(deadline) { + Ok(l) => l, + Err(IoErr::Timeout) => return Err(format!("no hello within {} ms", o.startup_timeout_ms)), + Err(IoErr::Eof) => return Err("bot exited before hello".into()), + Err(IoErr::Broken(e)) => return Err(e), + }; + let Ok(v) = serde_json::from_str::(&line) else { + self.st.noise_lines += 1; + continue; + }; + if v["type"] != "hello" { + continue; + } + if let Some(p) = v["data"]["protocol"].as_u64() { + if p > PROTOCOL as u64 { + return Err(format!("bot speaks pipe protocol {p}, this worker {PROTOCOL}")); + } + } + break; + } + let data = json!({ + "player_id": BOT_ID, "name": BOT_ID, "protocol": PROTOCOL, "mode": "benchmark", + "tables": [self.table_id], "lane": self.lane, "lanes": self.cx.lanes, "track": o.track, + "decision_time_ms": o.decision_timeout_ms, "server": format!("sharingan-arena-worker/{}", env!("CARGO_PKG_VERSION")), + }); + self.table_seq += 1; + let env = envelope("welcome", &self.table_id, None, None, self.table_seq, &data.to_string()); + b.send(&env, Instant::now() + Duration::from_millis(o.startup_timeout_ms)).map_err(|e| format!("welcome not delivered: {e:?}"))?; + self.bot = Some(b); + Ok(()) + } + + /// After a hang: kill and replace the process (state of the old one is lost), or give up. + fn restart_after_timeout(&mut self) { + if let Some(mut b) = self.bot.take() { + b.kill(); + } + if self.st.restarts >= self.cx.opts.max_restarts { + self.die(format!("decision timeouts: gave up after {} restarts", self.st.restarts)); + return; + } + self.st.restarts += 1; + if let Err(e) = self.start_bot() { + self.die(format!("restart failed: {e}")); + } + } + + /// Ask the bot for the pending decision. `turn` is the `your_turn` envelope line. + fn ask(&mut self, runner: &HandRunner, decision_id: &str, turn: &str) -> Decision { + let t0 = Instant::now(); + let deadline = t0 + Duration::from_millis(self.cx.opts.decision_timeout_ms); + let think = |t0: Instant| t0.elapsed().as_millis() as u64; + let Some(bot) = self.bot.as_mut() else { return Decision::Timeout(0) }; + if let Err(e) = bot.send(turn, deadline) { + return match e { + IoErr::Timeout => self.timed_out(t0), + IoErr::Eof => { + self.die("bot exited mid-game (closed its stdin)".into()); + Decision::Timeout(think(t0)) + } + IoErr::Broken(m) => { + self.die(m); + Decision::Timeout(think(t0)) + } + }; + } + loop { + if Instant::now() >= deadline { + return self.timed_out(t0); + } + let bot = self.bot.as_mut().unwrap(); + let line = match bot.recv(deadline) { + Ok(l) => l, + Err(IoErr::Timeout) => return self.timed_out(t0), + Err(IoErr::Eof) => { + let code = bot.child.try_wait().ok().flatten().map(|s| s.to_string()).unwrap_or_default(); + self.die(format!("bot exited mid-game {code}").trim().to_string()); + return Decision::Timeout(think(t0)); + } + Err(IoErr::Broken(m)) => { + self.die(m); + return Decision::Timeout(think(t0)); + } + }; + if !line.starts_with('{') { + self.st.noise_lines += 1; + continue; + } + let Ok(v) = serde_json::from_str::(&line) else { + self.st.noise_lines += 1; + continue; + }; + match v["type"].as_str() { + Some("act") => { + let d = &v["data"]; + if d["decision_id"].as_str() != Some(decision_id) { + continue; // stale answer to an earlier decision + } + let req = ActReq { kind: d["type"].as_str().unwrap_or("").to_string(), to: d["to"].as_i64() }; + match runner.validate(&req) { + Ok(a) => { + self.st.bot_wait_ms += t0.elapsed().as_secs_f64() * 1000.0; + return Decision::Act(a, think(t0)); + } + Err(e) => { + self.st.illegal_actions += 1; + let data = json!({"code": e.code, "message": e.message, "details": e.details, "decision_id": decision_id}); + self.table_seq += 1; + let env = envelope("error", &self.table_id, None, None, self.table_seq, &data.to_string()); + let bot = self.bot.as_mut().unwrap(); + if bot.send(&env, deadline).is_err() || bot.send(turn, deadline).is_err() { + return self.timed_out(t0); + } + } + } + } + Some("bye") => { + self.die("bot said bye".into()); + return Decision::Timeout(think(t0)); + } + _ => {} // hello / ping / unknown: ignored + } + } + } + + fn timed_out(&mut self, t0: Instant) -> Decision { + self.st.timeouts += 1; + self.st.bot_wait_ms += t0.elapsed().as_secs_f64() * 1000.0; + self.restart_after_timeout(); + Decision::Timeout(t0.elapsed().as_millis() as u64) + } + + fn play_hand(&mut self, hand_no: u32) -> Option<(HandRec, Option<[f64; 6]>, (u32, Option, u32, u64, [i64; 6]))> { + let cx = self.cx; + let (deal_no, rotation) = matches::locate(true, cx.planned, BLOCK_DEALS, hand_no); + let deal = deal_no.unwrap(); + let button = (deal % 6) as usize; + let mut seats = Vec::with_capacity(6); + for s in 0..6usize { + let pid = &cx.participants[(s + 6 - rotation as usize) % 6]; + seats.push(SeatInfo { seat: s, player_id: pid.clone(), name: pid.clone(), kind: "bot".into(), stack: cx.cfg.starting_stack }); + } + let dk = deck::deal_deck(&cx.seed, deal as u64); + // With a secret seed the id is opaque (keyed by the seed): hand ids would otherwise number the deals, and a bot that + // kept notes could match a deal across rotations by its number. Frozen (public) deals keep readable ids. + let hand_id = if cx.seed_secret { + format!("{}-{}", cx.hand_prefix, &sha256_hex(format!("hand:{}:{hand_no}", cx.seed).as_bytes())[..12]) + } else { + format!("{}-h{}", cx.hand_prefix, hand_no) + }; + let deck_digest = seed64(&cards::cards_str(&dk)); + let setup = HandSetup { + table_id: self.table_id.clone(), + hand_id: hand_id.clone(), + match_id: None, + hand_no, + deal_no, + rotation: Some(rotation), + cfg: cx.cfg.clone(), + button_seat: button, + seats, + sitting_out: vec![], + deck: dk, + salt: format!("{:016x}", seed64(&hand_id)), + started_ms: now_ms(), + lean: true, + }; + let (mut runner, _opening) = HandRunner::new(setup).ok()?; + let mut houses: Vec>> = Vec::new(); + for idx in 0..runner.n() { + let pid = &runner.info[idx].player_id; + let p = (pid != BOT_ID) + .then(|| cx.house.key_of(pid)) + .flatten() + .and_then(|k| cx.house.get(&k)) + .map(|f| f.new_player(idx, &runner.ecfg, mix(mix(cx.seed64, hand_no as u64), idx as u64))); + houses.push(p); + } + let mut crn = cards::Rng::new(mix(cx.seed64, deal as u64)); + let mut forfeited = false; + let mut restarted = false; + while !runner.is_over() { + let idx = runner.to_act_idx().unwrap(); + let applied = if houses[idx].is_some() { + let u = crn.f64(); + let hole = runner.deal.holes[idx]; + let action = { + let view = bench::policy::View { cfg: &runner.ecfg, state: &runner.st, board: runner.board(), history: &runner.ehist, seat: idx }; + houses[idx].as_mut().unwrap().act(&view, hole, u) + }; + let (action, timeout) = if crate::table::engine_legal(&runner.st, action) { + (action, false) + } else { + runner.anomalies.push(format!("house bot at seat {} chose an illegal action {action:?}", runner.seat_of(idx))); + (runner.timeout_action(), true) + }; + runner.apply(action, timeout, 0) + } else if self.bot.is_some() && self.alive() { + self.st.decisions += 1; + let deadline_ms = now_ms() + cx.opts.decision_timeout_ms; + let (decision_id, seq, data) = { + let t = runner.begin_turn(deadline_ms, 0).unwrap(); + (t.decision_id.clone(), t.event.seq.unwrap_or(0), t.event.data.to_string()) + }; + self.table_seq += 1; + let turn = envelope("your_turn", &self.table_id, Some(&hand_id), Some(seq), self.table_seq, &data); + let before = self.st.restarts; + let d = self.ask(&runner, &decision_id, &turn); + restarted |= self.st.restarts != before; + match d { + Decision::Act(a, think) => runner.apply(a, false, think), + Decision::Timeout(think) => { + if !self.alive() { + forfeited = true; + } + let a = runner.timeout_action(); + runner.apply(a, true, think) + } + } + } else { + forfeited = true; + let a = runner.timeout_action(); + runner.apply(a, true, 0) + }; + for p in houses.iter_mut().flatten() { + p.observe(&applied.pre, applied.idx, applied.action); + for &l in &applied.reveals { + p.observe_board(&runner.deal.board[..l]); + } + } + } + for p in houses.iter_mut().flatten() { + p.finish(&runner.deal, &runner.ehist, &runner.st); + } + let (end_events, hist) = runner.finish(true); + if forfeited { + self.st.forfeit_hands += 1; + } + self.st.anomalies += hist.anomalies.len() as u32; + if self.alive() && !restarted { + if let Some(mut e) = end_events.into_iter().find(|e| e.kind == "hand_end") { + crate::table::redact_hand_end(&mut e.data); + self.table_seq += 1; + let line = envelope("hand_end", &self.table_id, Some(&hand_id), e.seq, self.table_seq, &e.data.to_string()); + let deadline = Instant::now() + Duration::from_millis(cx.opts.decision_timeout_ms); + if let Some(b) = self.bot.as_mut() { + match b.send(&line, deadline) { + Ok(()) => {} + Err(IoErr::Timeout) => { + self.st.timeouts += 1; + self.restart_after_timeout(); + } + Err(_) => self.die("bot exited mid-game (closed its stdin)".into()), + } + } + } + } + let mut nets = [0i64; 6]; + for r in &hist.results { + nets[r.seat as usize] = r.net; + } + let av = cx.mode.and_then(|m| { + let t = Instant::now(); + let v = matches::aivat_hand(cx.house, &hist, cx.est, m); + self.st.aivat_ms += t.elapsed().as_secs_f64() * 1000.0; + v + }); + self.st.hands += 1; + cx.done.fetch_add(1, Ordering::Relaxed); + Some((HandRec { hand_no, nets }, av, (hand_no, deal_no, rotation, deck_digest, nets))) + } + + /// Play this lane's share of rotation `rot` with a fresh bot process (`bot_cmd`), then end it. A lane that gave up on + /// its bot (too many restarts) stays given up: its remaining hands are forfeited. + fn play_rotation(&mut self, rot: u32, bot_cmd: String, out: &mut LaneOut) { + let t0 = Instant::now(); + self.bot_cmd = bot_cmd; + self.table_seq = 0; // a new process is a new session + if self.alive() { + if let Err(e) = self.start_bot() { + self.die(format!("start failed: {e}")); + } + } + // this lane's deals of the rotation, in an order keyed by the seed (secret for hosted runs): the order of play says + // nothing about which deal is which + let mut hands = Vec::new(); + while let Some(h) = matches::lane_rotation_hand_no(self.cx.planned, BLOCK_DEALS, self.cx.lanes, self.lane, rot, hands.len() as u32) { + hands.push(h); + } + let mut rng = cards::Rng::new(mix(mix(self.cx.seed64 ^ 0x5eed_04de_u64, rot as u64), self.lane as u64)); + for i in (1..hands.len()).rev() { + hands.swap(i, (rng.next_u64() % (i as u64 + 1)) as usize); + } + for h in hands { + match self.play_hand(h) { + Some((rec, av, log)) => { + if let Some(a) = av { + out.aivat.insert(h, a); + } + out.recs.push(rec); + out.log.push(log); + } + None => { + self.st.anomalies += 1; + } + } + } + if let Some(mut b) = self.bot.take() { + let bye = envelope("bye", &self.table_id, None, None, self.table_seq + 1, "{}"); + b.finish(&bye); + } + self.st.wall_ms += t0.elapsed().as_millis() as u64; + } +} + +/// The bot command for rotation `rot`: as that rotation's own uid when isolated. +fn rotation_cmd(opts: &WorkerOpts, rot: u32) -> String { + match &opts.rotation_uids { + Some(u) => format!("exec setpriv --reuid={0} --regid={0} --clear-groups --inh-caps=-all --bounding-set=-all {1}", u[rot as usize], opts.bot_cmd), + None => opts.bot_cmd.clone(), + } +} + +/// Take the sandbox's loopback interface down (the worker is root with CAP_NET_ADMIN in the sandbox's own network +/// namespace). Bots talk to the worker over pipes and need no network; a TCP connection a bot makes to itself would +/// leave TIME_WAIT state (ports it chose) that outlives its processes and that the next rotation could read back. +fn loopback_down() -> Result<(), String> { + unsafe { + let fd = libc::socket(libc::AF_INET, libc::SOCK_DGRAM, 0); + if fd < 0 { + return Err(format!("isolation: socket: {}", io::Error::last_os_error())); + } + let mut ifr: libc::ifreq = std::mem::zeroed(); + for (i, b) in b"lo".iter().enumerate() { + ifr.ifr_name[i] = *b as libc::c_char; + } + let r = if libc::ioctl(fd, libc::SIOCGIFFLAGS as _, &mut ifr) < 0 { + Err(io::Error::last_os_error()) + } else { + ifr.ifr_ifru.ifru_flags &= !(libc::IFF_UP as libc::c_short); + if libc::ioctl(fd, libc::SIOCSIFFLAGS as _, &ifr) < 0 { Err(io::Error::last_os_error()) } else { Ok(()) } + }; + libc::close(fd); + r.map_err(|e| format!("isolation: cannot take the loopback interface down ({e}); the sandbox needs CAP_NET_ADMIN")) + } +} + +/// End everything `uid` left behind (see `WorkerOpts::rotation_uids`). A failure fails the run: a run that can't +/// guarantee the isolation must not be signed. +fn scrub(cmd: &str, uid: u32) -> Result<(), String> { + let st = Command::new("sh").arg("-c").arg(format!("{cmd} {uid}")).stdin(Stdio::null()).status() + .map_err(|e| format!("isolation: cannot run {cmd}: {e}"))?; + if st.success() { Ok(()) } else { Err(format!("isolation: `{cmd} {uid}` failed ({st})")) } +} + +// ------------------------------------------------------------------------------------ run + result + +/// What the bot sees of the seed inside `hand_id`s: the seed for the (public) track seed, a hash prefix otherwise. +fn hand_prefix(seed: &str, track_seed: &str) -> String { + if seed == track_seed { + seed.to_string() + } else { + format!("run-{}", &sha256_hex(format!("hand-prefix:{seed}").as_bytes())[..16]) + } +} + +/// Read a seed from a file (`--seed-file`): trimmed, must be non-empty. The hosted runner writes a root-only file +/// the bot's user cannot open; the worker reads it once and never passes it on to the bot process. +pub fn read_seed_file(path: &str) -> Result { + let raw = std::fs::read_to_string(path).map_err(|e| format!("cannot read seed file {path}: {e}"))?; + let seed = raw.trim(); + if seed.is_empty() { + return Err(format!("seed file {path} is empty")); + } + Ok(seed.to_string()) +} + +pub fn build_house(track: &Track, cfg: Option<&ServerConfig>) -> Result { + let cfg = cfg.cloned().unwrap_or_else(ServerConfig::from_env); + let house = HouseRegistry::build(&cfg)?; + for k in track.panel { + if house.key_of(k).is_none() { + return Err(format!( + "track {} needs house bot {k}: set ARENA_BLUEPRINT (and ARENA_BUCKETS / ARENA_SIZING) to the blueprint of the server's track", + track.id + )); + } + } + Ok(house) +} + +/// Play the benchmark and return the unsigned result JSON. +pub fn run_worker(opts: &WorkerOpts) -> Result { + let track = benchmarks::track(&opts.track).map_err(|e| e.message)?; + if opts.bot_cmd.trim().is_empty() { + return Err("--bot is required".into()); + } + let house = build_house(track, opts.house_cfg.as_ref())?; + let hands = ((opts.hands.clamp(6, 1_000_000)) + 5) / 6 * 6; + let blocks = ((hands / 6) + BLOCK_DEALS - 1) / BLOCK_DEALS; + let lanes = opts.lanes.clamp(1, 32).min(blocks.max(1) as usize); + let track_seed = benchmarks::seed_of(track); + let seed = opts.seed.clone().unwrap_or_else(|| track_seed.clone()); + let mut participants = vec![BOT_ID.to_string()]; + participants.extend(track.panel.iter().map(|k| house_id(&house.key_of(k).unwrap()))); + let mode = match opts.aivat.as_str() { + "off" => None, + "cards" => Some(Mode::CardsOnly), + _ => Some(Mode::Full), + }; + let cfg = TableConfig { mode: Some("benchmark".into()), decision_time_ms: opts.decision_timeout_ms, min_players_to_deal: 6, ..Default::default() }; + cfg.validate().map_err(|e| e.message)?; + let est = EquityEstimator::default(); + let cx = Cx { opts, house: &house, est: &est, mode, participants: participants.clone(), cfg: cfg.clone(), seed64: seed64(&seed), hand_prefix: hand_prefix(&seed, &track_seed), seed: seed.clone(), planned: hands, lanes, done: AtomicU32::new(0), seed_secret: seed != track_seed }; + let started_at = now_iso(); + let t0 = Instant::now(); + let finished = AtomicBool::new(false); + let outs: Vec = std::thread::scope(|sc| -> Result, String> { + if !opts.quiet { + let (cx, fin) = (&cx, &finished); + sc.spawn(move || { + let mut last = 0; + while !fin.load(Ordering::Relaxed) { + std::thread::sleep(Duration::from_millis(100)); + let d = cx.done.load(Ordering::Relaxed); + if d * 10 / cx.planned.max(1) > last * 10 / cx.planned.max(1) { + last = d; + let _ = writeln!(io::stderr(), " {} {}/{} hands ({:.0} hands/s)", cx.opts.track, d, cx.planned, d as f64 / t0.elapsed().as_secs_f64()); + } + } + }); + } + // Rotation-major: every lane plays rotation 0 of its deals, then (fresh processes) rotation 1, ... Within one rotation + // a deal appears once, so a bot process never meets a deal it already saw from another seat; with + // `rotation_uids` nothing it wrote down survives into the next rotation either. + if opts.rotation_uids.is_some() { + if let Err(e) = loopback_down() { + finished.store(true, Ordering::Relaxed); + return Err(e); + } + } + let mut ls: Vec = (0..lanes).map(|l| Lane::new(&cx, l)).collect(); + let mut outs: Vec = (0..lanes).map(|_| LaneOut { recs: vec![], aivat: HashMap::new(), log: vec![], stats: LaneStats::default() }).collect(); + for rot in 0..6u32 { + let cmd = rotation_cmd(opts, rot); + let hs: Vec<_> = ls.drain(..).zip(outs.drain(..)).map(|(mut lane, mut out)| { + let cmd = cmd.clone(); + sc.spawn(move || { + lane.play_rotation(rot, cmd, &mut out); + (lane, out) + }) + }).collect(); + for h in hs { + let (lane, out) = h.join().expect("lane thread panicked"); + ls.push(lane); + outs.push(out); + } + if let Some(uids) = &opts.rotation_uids { + if let Err(e) = scrub(&opts.scrub_cmd, uids[rot as usize]) { + finished.store(true, Ordering::Relaxed); + return Err(e); + } + } + } + for (lane, out) in ls.iter_mut().zip(outs.iter_mut()) { + out.stats = std::mem::take(&mut lane.st); + } + finished.store(true, Ordering::Relaxed); + Ok(outs) + })?; + let wall = t0.elapsed(); + let mut recs: Vec = Vec::new(); + let mut aivat: HashMap = HashMap::new(); + let mut log = Vec::new(); + let mut lane_stats = Vec::new(); + for o in outs { + recs.extend(o.recs); + aivat.extend(o.aivat); + log.extend(o.log); + lane_stats.push(o.stats); + } + recs.sort_by_key(|r| r.hand_no); + log.sort_by_key(|l| l.0); + let keys = matches::slot_keys_of(&participants); + let names: HashMap = participants.iter().map(|p| (p.clone(), p.clone())).collect(); + let (standings, _rows) = matches::build_standings(&keys, &participants, &names, cfg.big_blind, true, hands, BLOCK_DEALS, &recs, mode.map(|_| &aivat)); + let me = standings.iter().find(|s| s.player_id == BOT_ID).ok_or("no standing for the bot (no hands played?)")?; + if let Some(path) = &opts.hands_out { + let mut f = std::io::BufWriter::new(std::fs::File::create(path).map_err(|e| format!("{path}: {e}"))?); + for (h, d, r, dg, nets) in &log { + let _ = writeln!(f, "{}", json!({"hand_no": h, "deal_no": d, "rotation": r, "deck_digest": format!("{dg:016x}"), "nets": nets})); + } + } + let mut dg = Vec::new(); + for (h, _, _, d, _) in &log { + dg.extend_from_slice(&h.to_le_bytes()); + dg.extend_from_slice(&d.to_le_bytes()); + } + let sum = |f: &dyn Fn(&LaneStats) -> f64| lane_stats.iter().map(f).sum::(); + let hands_done = recs.len() as u32; + let finished_at = now_iso(); + Ok(json!({ + "schema": RESULT_SCHEMA, + "run_id": new_id("w"), + "track": track.id, + "panel_version": track.version, + "panel": track.panel.iter().map(|k| house_id(k)).collect::>(), + "seed": seed, + "player_id": opts.player_id, + "hands": hands_done, + "hands_planned": hands, + "deals": me.deals, + "lanes": lanes, + "mbb_per_game": r6(me.mbb_per_game), + "ci95_mbb": r6(me.ci95_mbb), + "method": me.method, + "bb_per_100": r6(me.bb_per_100), + "net_chips": me.net_chips, + "duplicate_mbb_per_hand": me.duplicate_mbb_per_hand.map(r6), + "forfeit_hands": sum(&|s| s.forfeit_hands as f64) as u64, + "crashed_lanes": lane_stats.iter().filter(|s| s.crashed.is_some()).count(), + "timeouts": sum(&|s| s.timeouts as f64) as u64, + "blueprint_fingerprint": house.blueprint_fp, + "deals_digest": sha256_hex(&dg), + "bot": {"command_sha256": sha256_hex(opts.bot_cmd.as_bytes())}, + "worker": {"name": "sharingan-arena", "version": env!("CARGO_PKG_VERSION"), "protocol": PROTOCOL, "aivat": opts.aivat, + "decision_timeout_ms": opts.decision_timeout_ms, "max_restarts": opts.max_restarts, + "isolated_rotations": opts.rotation_uids.is_some()}, + "per_lane": lane_stats.iter().map(|s| json!({ + "lane": s.lane, "hands": s.hands, "decisions": s.decisions, "timeouts": s.timeouts, "restarts": s.restarts, + "illegal_actions": s.illegal_actions, "forfeit_hands": s.forfeit_hands, "noise_lines": s.noise_lines, + "anomalies": s.anomalies, "crashed": s.crashed, "wall_ms": s.wall_ms, + "bot_wait_ms": s.bot_wait_ms.round(), "aivat_ms": s.aivat_ms.round(), + })).collect::>(), + "timings": { + "wall_ms": wall.as_millis() as u64, + "hands_per_sec": (hands_done as f64 / wall.as_secs_f64() * 10.0).round() / 10.0, + "bot_wait_ms_total": sum(&|s| s.bot_wait_ms).round(), + "aivat_ms_total": sum(&|s| s.aivat_ms).round(), + }, + "started_at": started_at, + "finished_at": finished_at, + })) +} + +// ------------------------------------------------------------------------------------ CLI + +pub const RUN_USAGE: &str = "usage: sharingan-arena run --bot \"\" [--track ladder-v1|sharingan-1] [--hands N] [--lanes L] [--seed S | --seed-file F] + [--out result.json] [--sign-key-file F] [--player-id ID] [--decision-timeout-ms 5000] [--startup-timeout-ms 30000] + [--max-restarts 3] [--aivat full|cards|off] [--hands-out FILE] [--quiet] + [--rotation-uids U0,U1,U2,U3,U4,U5 [--scrub-cmd sharingan-scrub]] (as root: each rotation's bot as its own uid, wiped after) + env: ARENA_BLUEPRINT / ARENA_BUCKETS / ARENA_SIZING select the sharingan-1 house bot (as for the server)"; + +/// `sharingan-arena run ...`; returns the process exit code. +pub fn cli_run(args: Vec) -> i32 { + let mut o = WorkerOpts::default(); + let (mut out, mut key_file, mut seed_file) = (None::, None::, None::); + let mut it = args.into_iter(); + let bad = |m: &str| -> i32 { + eprintln!("sharingan-arena run: {m}\n{RUN_USAGE}"); + 2 + }; + while let Some(a) = it.next() { + let mut val = || it.next(); + macro_rules! v { + () => { + match val() { + Some(v) => v, + None => return bad(&format!("{a} needs a value")), + } + }; + } + macro_rules! n { + ($t:ty) => { + match v!().parse::<$t>() { + Ok(x) => x, + Err(_) => return bad(&format!("{a}: bad number")), + } + }; + } + match a.as_str() { + "--bot" => o.bot_cmd = v!(), + "--track" => o.track = v!(), + "--hands" => o.hands = n!(u32), + "--lanes" => o.lanes = n!(usize), + "--seed" => o.seed = Some(v!()), + "--seed-file" => seed_file = Some(v!()), + "--out" => out = Some(v!()), + "--sign-key-file" => key_file = Some(v!()), + "--player-id" => o.player_id = Some(v!()), + "--decision-timeout-ms" => o.decision_timeout_ms = n!(u64), + "--startup-timeout-ms" => o.startup_timeout_ms = n!(u64), + "--max-restarts" => o.max_restarts = n!(u32), + "--aivat" => o.aivat = v!(), + "--hands-out" => o.hands_out = Some(v!()), + "--rotation-uids" => { + let u: Vec = v!().split(',').filter_map(|x| x.trim().parse().ok()).collect(); + let mut d = u.clone(); + d.sort_unstable(); + d.dedup(); + if u.len() != 6 || d.len() != 6 || u.iter().any(|&x| x < 1000) { + return bad("--rotation-uids needs 6 distinct uids >= 1000, comma separated"); + } + o.rotation_uids = Some([u[0], u[1], u[2], u[3], u[4], u[5]]); + } + "--scrub-cmd" => o.scrub_cmd = v!(), + "--quiet" => o.quiet = true, + "-h" | "--help" => { + println!("{RUN_USAGE}"); + return 0; + } + _ => return bad(&format!("unknown argument {a}")), + } + } + if o.bot_cmd.is_empty() { + return bad("--bot is required"); + } + if !matches!(o.aivat.as_str(), "full" | "cards" | "off") { + return bad("--aivat must be full, cards or off"); + } + if let Some(p) = &seed_file { + // takes precedence over --seed + match read_seed_file(p) { + Ok(sd) => o.seed = Some(sd), + Err(e) => { + eprintln!("sharingan-arena run: {e}"); + return 2; + } + } + } + let key = match &key_file { + Some(p) => match std::fs::read_to_string(p).ok().and_then(|s| parse_key_spec(&s)) { + Some(k) => Some(k), + None => { + eprintln!("sharingan-arena run: cannot read a key from {p}"); + return 2; + } + }, + None => None, + }; + let mut result = match run_worker(&o) { + Ok(r) => r, + Err(e) => { + eprintln!("sharingan-arena run: {e}"); + return 1; + } + }; + if let Some((id, secret)) = &key { + sign_result(&mut result, id, secret); + } + let text = serde_json::to_string_pretty(&result).unwrap(); + match &out { + Some(p) => { + if let Err(e) = std::fs::write(p, &text) { + eprintln!("sharingan-arena run: {p}: {e}"); + return 1; + } + } + None => println!("{text}"), + } + let r = &result; + eprintln!( + "{}: {:+.1} ± {:.1} mbb/game ({}) over {} hands on {}; {:.0} hands/s{}{}", + r["track"].as_str().unwrap_or(""), + r["mbb_per_game"].as_f64().unwrap_or(0.0), + r["ci95_mbb"].as_f64().unwrap_or(0.0), + r["method"].as_str().unwrap_or(""), + r["hands"], + r["track"].as_str().unwrap_or(""), + r["timings"]["hands_per_sec"].as_f64().unwrap_or(0.0), + if r["forfeit_hands"].as_u64().unwrap_or(0) > 0 { format!("; {} FORFEIT hands", r["forfeit_hands"]) } else { String::new() }, + if key.is_some() { "; signed" } else { "" }, + ); + 0 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn canonical_json_sorts_keys_and_is_compact() { + let v = json!({"b": [1, {"z": 1.5, "a": null}], "a": "x\"y", "c": 10}); + assert_eq!(canonical_json(&v), r#"{"a":"x\"y","b":[1,{"a":null,"z":1.500000}],"c":10}"#); + // key order of the input does not matter + let w: Value = serde_json::from_str(r#"{"c":10,"a":"x\"y","b":[1,{"a":null,"z":1.5}]}"#).unwrap(); + assert_eq!(canonical_json(&v), canonical_json(&w)); + } + + #[test] + fn sign_verify_and_forgery() { + let keys = parse_keys("w1=secret-one, w2=secret-two"); + assert_eq!(keys.len(), 2); + let mut r = json!({"schema": RESULT_SCHEMA, "mbb_per_game": 12.5, "ci95_mbb": 3.0, "hands": 600}); + assert_eq!(verify_result(&r, &keys), Err("unsigned result")); + sign_result(&mut r, "w2", "secret-two"); + assert_eq!(verify_result(&r, &keys), Ok("w2".to_string())); + // survives a serialize/parse round trip (what the control plane receives) + let back: Value = serde_json::from_str(&serde_json::to_string_pretty(&r).unwrap()).unwrap(); + assert_eq!(verify_result(&back, &keys), Ok("w2".to_string())); + // any change to the signed content breaks it + let mut forged = r.clone(); + forged["mbb_per_game"] = json!(1200.5); + assert_eq!(verify_result(&forged, &keys), Err("bad signature")); + let mut extra = r.clone(); + extra["verified"] = json!(true); + assert_eq!(verify_result(&extra, &keys), Err("bad signature")); + // wrong key / claimed key id mismatch / no keys + let mut other = r.clone(); + sign_result(&mut other, "w2", "not-the-secret"); + assert_eq!(verify_result(&other, &keys), Err("bad signature")); + let mut wrong_id = r.clone(); + wrong_id["signature"]["key_id"] = json!("w1"); + assert_eq!(verify_result(&wrong_id, &keys), Err("bad signature")); + assert!(verify_result(&r, &[]).is_err()); + assert_eq!(parse_key_spec("abc").unwrap(), ("default".to_string(), "abc".to_string())); + } +} diff --git a/arena/server/src/writer.rs b/arena/server/src/writer.rs new file mode 100644 index 00000000..ca2caac8 --- /dev/null +++ b/arena/server/src/writer.rs @@ -0,0 +1,73 @@ +//! Background batch writer for hand histories: the hand loop never waits on SQLite. +//! `flush()` is a barrier for readers (REST hand reads, AIVAT at match end). + +use crate::model::HandHistory; +use crate::store::Store; +use serde_json::Value; +use std::sync::mpsc::{channel, Sender, TryRecvError}; +use std::sync::Arc; + +enum Msg { + Hand(Box<(HandHistory, Vec)>), + Flush(tokio::sync::oneshot::Sender<()>), +} + +pub struct HandWriter { + tx: Sender, +} + +impl HandWriter { + pub fn spawn(store: Arc) -> Self { + let (tx, rx) = channel::(); + std::thread::Builder::new() + .name("hand-writer".into()) + .spawn(move || { + let mut batch: Vec<(HandHistory, Vec)> = Vec::new(); + let mut flushes: Vec> = Vec::new(); + loop { + let first = match rx.recv() { + Ok(m) => m, + Err(_) => break, + }; + let mut next = Some(first); + while let Some(m) = next.take() { + match m { + Msg::Hand(b) => batch.push(*b), + Msg::Flush(f) => flushes.push(f), + } + if batch.len() >= 500 || !flushes.is_empty() { + break; + } + match rx.try_recv() { + Ok(m) => next = Some(m), + Err(TryRecvError::Empty) => {} + Err(TryRecvError::Disconnected) => {} + } + } + if !batch.is_empty() { + if let Err(e) = store.append_hands(&batch) { + tracing::error!("hand writer: {e}"); + } + batch.clear(); + } + for f in flushes.drain(..) { + let _ = f.send(()); + } + } + }) + .expect("spawn writer thread"); + HandWriter { tx } + } + + pub fn push(&self, h: HandHistory, events: Vec) { + let _ = self.tx.send(Msg::Hand(Box::new((h, events)))); + } + + /// Resolves once everything pushed before this call is stored. + pub async fn flush(&self) { + let (tx, rx) = tokio::sync::oneshot::channel(); + if self.tx.send(Msg::Flush(tx)).is_ok() { + let _ = rx.await; + } + } +} diff --git a/arena/server/src/ws.rs b/arena/server/src/ws.rs new file mode 100644 index 00000000..8b16d2e7 --- /dev/null +++ b/arena/server/src/ws.rs @@ -0,0 +1,182 @@ +//! WebSocket `/v1/play` (TABLE_API.md section 4). + +use crate::error::ApiError; +use crate::state::{bearer, AppState, Principal}; +use crate::table::TableCmd; +use crate::util::now_ms; +use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade}; +use axum::extract::{Query, State}; +use axum::http::HeaderMap; +use axum::response::{IntoResponse, Response}; +use futures_util::{SinkExt, StreamExt}; +use serde_json::{json, Value}; +use std::collections::HashMap; +use std::sync::Arc; +use tokio::sync::mpsc::{unbounded_channel, UnboundedSender}; + +pub async fn play( + State(app): State>, + headers: HeaderMap, + Query(q): Query>, + ws: WebSocketUpgrade, +) -> Response { + let token = q.get("token").cloned().or_else(|| bearer(&headers)); + if let Err(e) = app.ensure_accepting() { + return e.into_response(); + } + let who = match token { + Some(t) => app.authenticate_token(&t), + None => Err(ApiError::unauthorized()), + }; + match who { + Ok(Principal::Player(p)) => { + let max = app.cfg.max_ws_per_player; + if max > 0 && app.hub.count(&p.player_id) >= max { + return ws_limit(max).into_response(); + } + let mx = app.cfg.max_ws_message_bytes; + ws.max_message_size(mx).max_frame_size(mx).on_upgrade(move |s| conn(app, p.player_id, p.name, s)) + } + Ok(Principal::Admin | Principal::Runner) => ApiError::forbidden("only a bot token can play; use a bot token").into_response(), + Err(e) => e.into_response(), + } +} + +async fn wait_sd(rx: &mut tokio::sync::watch::Receiver) { + let _ = rx.wait_for(|v| *v).await.map(|_| ()); +} + +fn ws_limit(max: usize) -> ApiError { + ApiError::rate_limited( + format!("this player already has {max} open sockets (limit)"), + json!({"limit": "ARENA_MAX_WS_PER_PLAYER", "max": max}), + ) +} + +fn err_msg(code: &str, message: &str, details: Value) -> String { + json!({"v": 1, "type": "error", "t_ms": now_ms(), "data": {"code": code, "message": message, "details": details}}).to_string() +} + +async fn conn(app: Arc, pid: String, name: String, socket: WebSocket) { + let (mut sink, mut stream) = socket.split(); + let (tx, mut rx) = unbounded_channel::(); + let Some(conn_id) = app.hub.try_register(&pid, tx.clone(), app.cfg.max_ws_per_player) else { + // Lost a race with another connect: same 429 contract, over the socket. + let e = ws_limit(app.cfg.max_ws_per_player); + let _ = sink.send(Message::Text(err_msg(e.code, &e.message, e.details).into())).await; + let _ = sink.send(Message::Close(None)).await; + return; + }; + let mut sd_w = app.shutdown.subscribe(); + let writer = tokio::spawn(async move { + loop { + tokio::select! { + m = rx.recv() => match m { + Some(m) => { + if sink.send(Message::Text(m.into())).await.is_err() { + break; + } + } + None => break, + }, + _ = wait_sd(&mut sd_w) => { + let _ = sink.send(Message::Close(None)).await; + break; + } + } + } + }); + let mut sd_r = app.shutdown.subscribe(); + loop { + let msg = tokio::select! { + m = stream.next() => match m { Some(Ok(m)) => m, _ => break }, + _ = wait_sd(&mut sd_r) => { + // let the writer deliver the close frame + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + break; + } + }; + match msg { + Message::Text(t) => handle(&app, &pid, &name, &tx, t.as_str()), + Message::Close(_) => break, + _ => {} + } + } + app.hub.unregister(&pid, conn_id); + writer.abort(); +} + +fn handle(app: &Arc, pid: &str, name: &str, tx: &UnboundedSender, text: &str) { + let Ok(m) = serde_json::from_str::(text) else { + let _ = tx.send(err_msg("bad_request", "message is not valid JSON", json!({}))); + return; + }; + let data = m.get("data").cloned().unwrap_or(json!({})); + match m["type"].as_str().unwrap_or("") { + "hello" => { + let tables = app.tables_of(pid); + let ids: Vec<&str> = tables.iter().map(|t| t.id.as_str()).collect(); + let _ = tx.send( + json!({"v": 1, "type": "welcome", "t_ms": now_ms(), + "data": {"player_id": pid, "name": name, "server_time": now_ms(), "tables": ids, "protocol": 1}}) + .to_string(), + ); + for t in &tables { + // Authoritative snapshot (no event replay), then the pending your_turn if any. + let _ = tx.send(t.snapshot_msg(&app.hub, pid)); + let _ = t.tx.send(TableCmd::Resume { player_id: pid.to_string(), conn: tx.clone() }); + } + } + "ping" => { + let _ = tx.send(json!({"v": 1, "type": "pong", "t_ms": now_ms(), "data": {}}).to_string()); + } + "act" => { + let table = match m["table_id"].as_str() { + Some(id) => app.table(id).ok(), + None => { + let hid = data["hand_id"].as_str().unwrap_or(""); + let ts = app.tables_of(pid); + ts.iter() + .find(|t| t.inner.lock().unwrap().hand_id.as_deref() == Some(hid)) + .cloned() + .or_else(|| if ts.len() == 1 { ts.first().cloned() } else { None }) + } + }; + match table { + Some(t) => { + let _ = t.tx.send(TableCmd::Act { player_id: pid.to_string(), data, conn: tx.clone() }); + } + None => { + let _ = tx.send(err_msg("not_seated", "you are not seated at that table", json!({}))); + } + } + } + "next_hand" | "ready" => { + let table = match m["table_id"].as_str() { + Some(id) => app.table(id).ok(), + None => { + let ts = app.tables_of(pid); + if ts.len() == 1 { ts.first().cloned() } else { None } + } + }; + match table { + Some(t) => { + let _ = t.tx.send(TableCmd::Ready { player_id: pid.to_string() }); + } + None => { + let _ = tx.send(err_msg("not_seated", "you are not seated at that table", json!({}))); + } + } + } + "leave" => { + if let Some(t) = data["table_id"].as_str().or(m["table_id"].as_str()).and_then(|id| app.table(id).ok()) { + let _ = t.tx.send(TableCmd::Leave { player_id: pid.to_string() }); + } else { + let _ = tx.send(err_msg("not_seated", "unknown table", json!({}))); + } + } + other => { + let _ = tx.send(err_msg("bad_request", &format!("unknown message type {other:?}"), json!({}))); + } + } +} diff --git a/arena/server/tests/conformance.rs b/arena/server/tests/conformance.rs new file mode 100644 index 00000000..fa704d8a --- /dev/null +++ b/arena/server/tests/conformance.rs @@ -0,0 +1,1316 @@ +//! Conformance tests for TABLE_API.md section 12, plus auth, error paths, house bots, +//! duplicate matches, hand history export and the leaderboard. Each test spawns the server +//! in-process on an ephemeral port with an in-memory SQLite database and drives it over +//! real HTTP and WebSocket connections. +//! +//! Storage backend: in-memory SQLite by default; with `ARENA_TEST_DATABASE_URL=postgres://...` every +//! test server gets its own fresh schema in that Postgres database, so the same suite runs on both. + +use arena_server::config::ServerConfig; +use arena_server::{start, RunningServer}; +use futures_util::{SinkExt, StreamExt}; +use serde_json::{json, Value}; +use std::time::Duration; +use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender}; +use tokio_tungstenite::{connect_async, tungstenite::Message}; + +struct Srv { + base: String, + ws: String, + rs: RunningServer, + http: reqwest::Client, +} + +/// A tiny compact blueprint for the sharingan-1 house bot, if one is available on this machine. +fn test_blueprint() -> Option { + let p = std::env::var("SHARINGAN_TEST_BLUEPRINT") + .map(std::path::PathBuf::from) + .unwrap_or_else(|_| std::path::PathBuf::from(std::env::var("HOME").unwrap_or_default()).join("dev-serve/tinybp/tiny.plcp")); + p.exists().then_some(p) +} + +async fn srv() -> Srv { + srv_with(None).await +} + +async fn srv_with(blueprint: Option) -> Srv { + srv_cfg(blueprint, |_| {}).await +} + +static SCHEMA_N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +async fn srv_cfg(blueprint: Option, tweak: impl FnOnce(&mut ServerConfig)) -> Srv { + let pg = std::env::var("ARENA_TEST_DATABASE_URL").ok().filter(|v| !v.is_empty()); + let schema = pg.as_ref().map(|_| { + let n = SCHEMA_N.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let t = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + format!("t_{}_{}_{}", std::process::id(), n, t % 1_000_000_007) + }); + let mut cfg = ServerConfig { + database_url: pg, + database_schema: schema, + db_pool: 2, // the whole suite runs ~30 servers in parallel; every pooled client holds ~10 fds + rate_limit_rps: 0.0, + blueprint, + sizing: "tiny".into(), + bind: "127.0.0.1:0".into(), + db_path: ":memory:".into(), + admin_token: Some("admin".into()), + hand_delay_ms: 0, + reconnect_grace_ms: 200, + min_leaderboard_hands: 6, + ..Default::default() + }; + tweak(&mut cfg); + let rs = start(cfg).await.unwrap(); + Srv { base: format!("http://{}", rs.addr), ws: format!("ws://{}", rs.addr), rs, http: reqwest::Client::new() } +} + +impl Srv { + async fn req(&self, method: &str, path: &str, token: Option<&str>, body: Option) -> (u16, Value) { + let m = reqwest::Method::from_bytes(method.as_bytes()).unwrap(); + let mut r = self.http.request(m, format!("{}{}", self.base, path)); + if let Some(t) = token { + r = r.bearer_auth(t); + } + if let Some(b) = body { + r = r.json(&b); + } + let resp = r.send().await.unwrap(); + let st = resp.status().as_u16(); + let txt = resp.text().await.unwrap(); + (st, serde_json::from_str(&txt).unwrap_or(Value::String(txt))) + } + async fn post(&self, p: &str, t: Option<&str>, b: Value) -> (u16, Value) { + self.req("POST", p, t, Some(b)).await + } + async fn get(&self, p: &str, t: Option<&str>) -> (u16, Value) { + self.req("GET", p, t, None).await + } + async fn register(&self, name: &str) -> (String, String) { + let (st, v) = self.post("/v1/bots", None, json!({"name": name, "kind": "bot"})).await; + assert_eq!(st, 201, "{v}"); + (v["player_id"].as_str().unwrap().into(), v["token"].as_str().unwrap().into()) + } + async fn table(&self, cfg: Value) -> String { + let (st, v) = self.post("/v1/tables", Some("admin"), cfg).await; + assert_eq!(st, 201, "{v}"); + v["table_id"].as_str().unwrap().into() + } + async fn wait_match(&self, id: &str) -> Value { + for _ in 0..600 { + let (_, v) = self.get(&format!("/v1/matches/{id}"), None).await; + if v["status"] == "finished" || v["status"] == "aborted" { + return v; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + panic!("match did not finish"); + } +} + +enum Out { + Text(String), + Close, +} + +struct Room { + ws_base: String, + ids: Vec<(String, String)>, + outs: Vec>>, + rx: UnboundedReceiver<(usize, Value)>, + mtx: UnboundedSender<(usize, Value)>, +} + +type Act = Option<(&'static str, Option)>; + +impl Room { + async fn new(s: &Srv, n: usize) -> Room { + let (mtx, rx) = unbounded_channel(); + let mut r = Room { ws_base: s.ws.clone(), ids: vec![], outs: vec![], rx, mtx }; + for i in 0..n { + let id = s.register(&format!("bot{i}")).await; + r.ids.push(id); + r.outs.push(None); + r.connect(i, true).await; + } + r + } + async fn connect(&mut self, i: usize, wait_welcome: bool) { + let url = format!("{}/v1/play?token={}", self.ws_base, self.ids[i].1); + let (ws, _) = connect_async(url).await.unwrap(); + let (mut w, mut rd) = ws.split(); + let (otx, mut orx) = unbounded_channel::(); + tokio::spawn(async move { + while let Some(o) = orx.recv().await { + match o { + Out::Text(s) => { + if w.send(Message::Text(s.into())).await.is_err() { + break; + } + } + Out::Close => { + let _ = w.close().await; + break; + } + } + } + }); + let mtx = self.mtx.clone(); + tokio::spawn(async move { + while let Some(Ok(m)) = rd.next().await { + if let Message::Text(t) = m { + let v: Value = serde_json::from_str(t.as_str()).unwrap(); + if mtx.send((i, v)).is_err() { + break; + } + } + } + }); + self.outs[i] = Some(otx); + self.send(i, "hello", None, json!({"client": "test/0.1", "resume": []})); + if wait_welcome { + loop { + let (j, m) = self.recv().await; + if j == i && m["type"] == "welcome" { + break; + } + } + } + } + fn send(&self, i: usize, ty: &str, table: Option<&str>, data: Value) { + let mut m = json!({"v": 1, "type": ty, "t_ms": 0, "data": data}); + if let Some(t) = table { + m["table_id"] = json!(t); + } + let _ = self.outs[i].as_ref().unwrap().send(Out::Text(m.to_string())); + } + fn close(&mut self, i: usize) { + let _ = self.outs[i].take().unwrap().send(Out::Close); + } + async fn recv(&mut self) -> (usize, Value) { + tokio::time::timeout(Duration::from_secs(20), self.rx.recv()).await.expect("timed out waiting for a message").unwrap() + } + async fn sit_all(&self, s: &Srv, table: &str, seats: &[usize]) { + for (i, seat) in seats.iter().enumerate() { + let (st, v) = s + .post(&format!("/v1/tables/{table}/seats/{seat}"), Some(&self.ids[i].1), json!({"player_id": self.ids[i].0})) + .await; + assert_eq!(st, 200, "{v}"); + } + } + fn act(&self, i: usize, table: &str, d: &Value, ty: &str, to: Option) { + let mut data = json!({"hand_id": d["hand_id"], "decision_id": d["decision_id"], "type": ty}); + if let Some(t) = to { + data["to"] = json!(t); + } + self.send(i, "act", Some(table), data); + } + /// Play one hand: answer every `your_turn` with `policy(client, your_turn.data)`; `None` = stay silent. + async fn run_hand(&mut self, table: &str, listeners: usize, mut policy: impl FnMut(usize, &Value) -> Act) -> Vec<(usize, Value)> { + let mut all = Vec::new(); + let mut ends = 0; + while ends < listeners { + let (i, m) = self.recv().await; + match m["type"].as_str().unwrap() { + "your_turn" => { + let d = m["data"].clone(); + if let Some((ty, to)) = policy(i, &d) { + self.act(i, table, &d, ty, to); + } + } + "hand_end" => ends += 1, + _ => {} + } + all.push((i, m)); + } + all + } +} + +fn of_type<'a>(evs: &'a [(usize, Value)], ty: &'a str) -> impl Iterator + 'a { + evs.iter().filter(move |(_, m)| m["type"] == ty).map(|(_, m)| m) +} + +/// Raise to max if possible, else call, else check. +fn jam(d: &Value) -> Act { + let l = &d["legal"]; + if !l["raise"].is_null() { + Some(("raise", l["raise"]["max_to"].as_i64())) + } else if !l["call"].is_null() { + Some(("call", None)) + } else { + Some(("check", None)) + } +} + +fn fold_or_check(d: &Value) -> Act { + Some(if d["legal"]["check"] == true { ("check", None) } else { ("fold", None) }) +} + +// ---- 12.1 blinds and first action ---- + +#[tokio::test] +async fn v1_blinds_and_first_action() { + let s = srv().await; + let t = s.table(json!({"mode": "sandbox", "sandbox": {"button_seat": 3}, "decision_time_ms": 5000})).await; + let mut room = Room::new(&s, 6).await; + room.sit_all(&s, &t, &[0, 1, 2, 3, 4, 5]).await; + let mut first = None; + let evs = room + .run_hand(&t, 6, |_, d| { + first.get_or_insert(d["seat"].as_u64().unwrap()); + Some(("fold", None)) + }) + .await; + assert_eq!(first, Some(0)); + let hs = of_type(&evs, "hand_start").next().unwrap(); + assert_eq!(hs["data"]["button_seat"], 3); + assert_eq!(hs["data"]["sb_seat"], 4); + assert_eq!(hs["data"]["bb_seat"], 5); + let acts: Vec<&Value> = of_type(&evs, "action").filter(|m| m["data"]["seat"].is_u64()).collect(); + let first_actions: Vec<(String, u64, i64)> = acts + .iter() + .take(2) + .map(|m| (m["data"]["type"].as_str().unwrap().into(), m["data"]["seat"].as_u64().unwrap(), m["data"]["to"].as_i64().unwrap())) + .collect(); + // every client sees every action; the first two distinct events are the blinds + assert_eq!(first_actions[0], ("post_sb".to_string(), 4, 50)); + assert_eq!(first_actions[1], ("post_bb".to_string(), 5, 100)); + assert_eq!(acts[0]["data"]["seq"], 1); + assert_eq!(acts[0]["data"]["forced"], true); +} + +#[tokio::test] +async fn v1_heads_up_button_is_sb_and_acts_first() { + let s = srv().await; + let t = s.table(json!({"mode": "sandbox", "min_players_to_deal": 2, "sandbox": {"button_seat": 4}})).await; + let mut room = Room::new(&s, 2).await; + room.sit_all(&s, &t, &[1, 4]).await; + let mut first = None; + let evs = room + .run_hand(&t, 2, |_, d| { + first.get_or_insert(d["seat"].as_u64().unwrap()); + Some(("fold", None)) + }) + .await; + assert_eq!(first, Some(4)); + let hs = of_type(&evs, "hand_start").next().unwrap(); + assert_eq!(hs["data"]["sb_seat"], 4); + assert_eq!(hs["data"]["bb_seat"], 1); +} + +// ---- 12.2 min-raise chain ---- + +#[tokio::test] +async fn v2_min_raise_chain() { + let s = srv().await; + let t = s.table(json!({"mode": "sandbox", "sandbox": {"button_seat": 3}})).await; + let mut room = Room::new(&s, 6).await; + room.sit_all(&s, &t, &[0, 1, 2, 3, 4, 5]).await; + let mut mins: Vec<(u64, i64)> = vec![]; + room.run_hand(&t, 6, |_, d| { + let seat = d["seat"].as_u64().unwrap(); + let min = d["legal"]["raise"]["min_to"].as_i64().unwrap_or(-1); + mins.push((seat, min)); + match (mins.len(), seat) { + (1, 0) => Some(("raise", Some(300))), + (2, 1) => Some(("raise", Some(500))), + (3, 2) => Some(("raise", Some(1200))), + _ => Some(("fold", None)), + } + }) + .await; + assert_eq!(&mins[..4], &[(0, 200), (1, 500), (2, 700), (3, 1900)]); +} + +// ---- 12.3 short all-in does not reopen ---- + +#[tokio::test] +async fn v3_short_all_in_does_not_reopen() { + let s = srv().await; + let t = s.table(json!({"mode": "sandbox", "starting_stack": 1500, "sandbox": {"button_seat": 3}})).await; + let mut room = Room::new(&s, 6).await; + room.sit_all(&s, &t, &[0, 1, 2, 3, 4, 5]).await; + let mut flop: Vec<(u64, Value)> = vec![]; + let evs = room + .run_hand(&t, 6, |_, d| { + let seat = d["seat"].as_u64().unwrap(); + if d["street"] == "preflop" { + return match seat { + 4 => Some(("call", None)), + 5 => Some(("check", None)), + _ => Some(("fold", None)), + }; + } + flop.push((seat, d["legal"].clone())); + match flop.len() { + 1 => Some(("bet", Some(1000))), // seat 4 bets 1000 + 2 => Some(("raise", Some(1400))), // seat 5 all-in for less than a full raise + _ => Some(("call", None)), // seat 4: only call/fold + } + }) + .await; + assert_eq!(flop.len(), 3); + // BB facing the bet: min raise is capped at the all-in amount + assert_eq!(flop[1].1["raise"], json!({"min_to": 1400, "max_to": 1400})); + // the bettor may only call or fold now + assert!(flop[2].1["raise"].is_null()); + assert_eq!(flop[2].1["call"]["to"], 1400); + let end = of_type(&evs, "hand_end").next().unwrap(); + let net: i64 = end["data"]["results"].as_array().unwrap().iter().map(|r| r["net"].as_i64().unwrap()).sum(); + assert_eq!(net, 0); +} + +// ---- 12.4 side pots ---- + +#[tokio::test] +async fn v4_side_pots() { + let s = srv().await; + let deck: Vec<&str> = vec!["As", "Ks", "7c", "Ah", "Kh", "2d", "3c", "4d", "5h", "9s", "3d", "Jc", "3h", "Qd"]; + let t = s + .table(json!({"mode": "sandbox", "min_players_to_deal": 3, + "sandbox": {"button_seat": 2, "stacks": [2000, 5000, 10000], "decks": [deck]}})) + .await; + let mut room = Room::new(&s, 3).await; + room.sit_all(&s, &t, &[0, 1, 2]).await; + let evs = room.run_hand(&t, 3, |_, d| jam(d)).await; + let end = of_type(&evs, "hand_end").next().unwrap()["data"].clone(); + let pots = end["pots"].as_array().unwrap(); + let amounts: Vec = pots.iter().map(|p| p["amount"].as_i64().unwrap()).collect(); + assert_eq!(amounts, vec![6000, 6000, 5000]); + assert_eq!(pots[0]["eligible_seats"], json!([0, 1, 2])); + assert_eq!(pots[1]["eligible_seats"], json!([1, 2])); + assert_eq!(pots[2]["eligible_seats"], json!([2])); + assert_eq!(pots[0]["winners"], json!([0])); + assert_eq!(pots[1]["winners"], json!([1])); + let nets: Vec = end["results"].as_array().unwrap().iter().map(|r| r["net"].as_i64().unwrap()).collect(); + assert_eq!(nets, vec![4000, 1000, -5000]); + assert_eq!(end["ended_by"], "showdown"); + assert_eq!(end["hole_cards"]["0"], json!(["As", "Ah"])); +} + +// ---- 12.5 odd chip ---- + +#[tokio::test] +async fn v5_odd_chip_goes_left_of_button() { + let s = srv().await; + let deck: Vec<&str> = vec!["4c", "Ac", "As", "5d", "Kd", "Kh", "6s", "2h", "3h", "7d", "6d", "9c", "6h", "Jd"]; + let t = s + .table(json!({"mode": "sandbox", "min_players_to_deal": 3, "small_blind": 1, "big_blind": 2, "starting_stack": 500, + "sandbox": {"button_seat": 5, "decks": [deck]}})) + .await; + let mut room = Room::new(&s, 3).await; + room.sit_all(&s, &t, &[1, 3, 5]).await; + let evs = room + .run_hand(&t, 3, |_, d| if d["seat"] == 1 { Some(("fold", None)) } else { jam(d) }) + .await; + let end = of_type(&evs, "hand_end").next().unwrap()["data"].clone(); + let pot = &end["pots"][0]; + assert_eq!(pot["amount"], 1001); + assert_eq!(pot["winners"], json!([3, 5])); + assert_eq!(pot["share"], json!([501, 500])); +} + +// ---- 12.6 timeout ---- + +#[tokio::test] +async fn v6_timeout_folds_when_facing_a_bet_and_checks_when_free() { + let s = srv().await; + let t = s.table(json!({"mode": "sandbox", "decision_time_ms": 300, "sandbox": {"button_seat": 3}})).await; + let mut room = Room::new(&s, 6).await; + room.sit_all(&s, &t, &[0, 1, 2, 3, 4, 5]).await; + let evs = room.run_hand(&t, 6, |_, _| None).await; + let a = of_type(&evs, "action").find(|m| m["data"]["seat"] == 0).unwrap(); + assert_eq!(a["data"]["type"], "fold"); + assert_eq!(a["data"]["timeout"], true); + + // heads-up: the BB is silent when checking is free -> check with timeout:true + let s2 = srv().await; + let t2 = s2.table(json!({"mode": "sandbox", "min_players_to_deal": 2, "decision_time_ms": 300, "sandbox": {"button_seat": 0}})).await; + let mut room2 = Room::new(&s2, 2).await; + room2.sit_all(&s2, &t2, &[0, 1]).await; + let evs = room2 + .run_hand(&t2, 2, |_, d| if d["seat"] == 0 { fold_or_check(d).map(|_| ("call", None)).filter(|_| d["legal"]["call"] != Value::Null).or(Some(("check", None))) } else { None }) + .await; + let bb_checks: Vec<&Value> = of_type(&evs, "action") + .filter(|m| m["data"]["seat"] == 1 && m["data"]["type"] == "check" && m["data"]["timeout"] == true) + .collect(); + assert!(!bb_checks.is_empty(), "BB should have been checked by the server"); +} + +// ---- 12.7 reconnect mid-hand ---- + +#[tokio::test] +async fn v7_reconnect_resumes_same_decision() { + let s = srv().await; + let t = s.table(json!({"mode": "sandbox", "decision_time_ms": 4000, "sandbox": {"button_seat": 3}})).await; + let mut room = Room::new(&s, 6).await; + room.sit_all(&s, &t, &[0, 1, 2, 3, 4, 5]).await; + let (turn, i) = loop { + let (i, m) = room.recv().await; + if m["type"] == "your_turn" { + break (m, i); + } + }; + assert_eq!(i, 0); + let decision = turn["data"]["decision_id"].as_str().unwrap().to_string(); + room.close(0); + tokio::time::sleep(Duration::from_millis(100)).await; + room.connect(0, false).await; + room.send(0, "hello", None, json!({"client": "t", "resume": [{"table_id": t, "last_table_seq": 0}]})); + let (mut welcome, mut snap, mut again) = (false, false, None); + while again.is_none() { + let (i, m) = room.recv().await; + if i != 0 { + continue; + } + match m["type"].as_str().unwrap() { + "welcome" => welcome = true, + "table_snapshot" => { + snap = true; + assert!(m["data"]["hand"]["hand_id"].is_string()); + assert_eq!(m["data"]["hole_cards"]["0"].as_array().unwrap().len(), 2); + } + "your_turn" => again = Some(m), + _ => {} + } + } + assert!(welcome && snap); + let again = again.unwrap(); + assert_eq!(again["data"]["decision_id"].as_str().unwrap(), decision); + room.act(0, &t, &again["data"], "fold", None); + loop { + let (_, m) = room.recv().await; + if m["type"] == "action" && m["data"]["seat"] == 0 && m["data"]["type"] == "fold" { + assert_eq!(m["data"]["timeout"], false); + break; + } + } +} + +// ---- errors: illegal action, bad amount, idempotency, stale ---- + +#[tokio::test] +async fn illegal_actions_get_errors_and_a_fresh_your_turn() { + let s = srv().await; + let t = s.table(json!({"mode": "sandbox", "min_players_to_deal": 2, "sandbox": {"button_seat": 0}})).await; + let mut room = Room::new(&s, 2).await; + room.sit_all(&s, &t, &[0, 1]).await; + let turn = loop { + let (_, m) = room.recv().await; + if m["type"] == "your_turn" { + break m; + } + }; + let d = turn["data"].clone(); + room.act(0, &t, &d, "raise", Some(150)); // below min + room.act(0, &t, &d, "check", None); // there is a bet + let mut errs = vec![]; + let mut turns = 0; + while errs.len() < 2 || turns < 2 { + let (i, m) = room.recv().await; + if i != 0 { + continue; + } + match m["type"].as_str().unwrap() { + "error" => errs.push(m), + "your_turn" => { + turns += 1; + assert_eq!(m["data"]["decision_id"], d["decision_id"]); + assert_eq!(m["table_seq"], turn["table_seq"], "a re-sent your_turn repeats its table_seq"); + } + _ => {} + } + } + assert_eq!(errs[0]["data"]["code"], "bad_amount"); + assert_eq!(errs[0]["data"]["details"]["min_to"], 200); + assert_eq!(errs[1]["data"]["code"], "illegal_action"); + // valid call, twice (idempotent), plus an unknown decision id + room.act(0, &t, &d, "call", None); + room.act(0, &t, &d, "call", None); + room.send(0, "act", Some(&t), json!({"hand_id": d["hand_id"], "decision_id": "d-bogus", "type": "fold"})); + let mut got_stale = false; + let mut seen_call = 0; + let mut bb_turn = None; + while bb_turn.is_none() || seen_call == 0 { + let (i, m) = room.recv().await; + match (i, m["type"].as_str().unwrap()) { + (0, "error") => { + assert_eq!(m["data"]["code"], "stale_decision"); + got_stale = true; + } + (_, "action") if m["data"]["seat"] == 0 && m["data"]["type"] == "call" && i == 0 => seen_call += 1, + (1, "your_turn") => bb_turn = Some(m), + _ => {} + } + } + assert_eq!(seen_call, 1); + // BB folds with check free: converted to a check, no error + let bt = bb_turn.unwrap(); + assert_eq!(bt["data"]["legal"]["check"], true); + room.act(1, &t, &bt["data"], "fold", None); + loop { + let (i, m) = room.recv().await; + if i == 1 && m["type"] == "action" && m["data"]["seat"] == 1 { + assert_eq!(m["data"]["type"], "check"); + break; + } + if i == 1 && m["type"] == "error" { + panic!("fold-when-free must not error: {m}"); + } + } + let _ = got_stale; +} + +// ---- auth, hashing ---- + +#[tokio::test] +async fn auth_and_token_hashing() { + let s = srv().await; + assert_eq!(s.get("/v1/hands/nope", None).await.0, 401); + assert_eq!(s.post("/v1/tables", None, json!({})).await.0, 401); + assert_eq!(s.post("/v1/tables", Some("wrong"), json!({})).await.0, 401); + let (pid, tok) = s.register("alice").await; + let rec = s.rs.app.store.get_player(&pid).unwrap().unwrap(); + assert_ne!(rec.token_hash, tok); + assert_eq!(rec.token_hash.len(), 64); + let (st, v) = s.get(&format!("/v1/players/{pid}"), None).await; + assert_eq!(st, 200); + assert!(v.get("token").is_none() && v.get("token_hash").is_none()); + // a bot token works as bearer; a bad ws token is refused + assert_eq!(s.post("/v1/tables", Some(&tok), json!({"decision_time_ms": 1000})).await.0, 201); + assert!(connect_async(format!("{}/v1/play?token=bad", s.ws)).await.is_err()); + // unknown house bot gives a clear error + let (st, v) = s.post("/v1/matches", Some("admin"), json!({"participants": [pid.clone(), "house:sharingan-1"], "hands_planned": 6})).await; + assert_eq!(st, 400, "{v}"); +} + +// ---- external bot vs house bots on a free table ---- + +#[tokio::test] +async fn single_bot_plays_a_full_table_against_house_bots() { + let s = srv().await; + let t = s.table(json!({"decision_time_ms": 3000})).await; + let mut room = Room::new(&s, 1).await; + room.sit_all(&s, &t, &[0]).await; + let (st, v) = s.post(&format!("/v1/tables/{t}/fill"), Some("admin"), json!({"bot": "ladder"})).await; + assert_eq!(st, 400, "ladder needs sharingan-1: {v}"); + let (st, v) = s.post(&format!("/v1/tables/{t}/fill"), Some("admin"), json!({"bot": "house:tight_aggressive"})).await; + assert_eq!(st, 200, "{v}"); + for _ in 0..5 { + let evs = room.run_hand(&t, 1, |_, d| if d["legal"]["check"] == true { Some(("check", None)) } else { Some(("call", None)) }).await; + let end = of_type(&evs, "hand_end").next().unwrap(); + let rs = end["data"]["results"].as_array().unwrap(); + assert_eq!(rs.len(), 6); + assert_eq!(rs.iter().map(|r| r["net"].as_i64().unwrap()).sum::(), 0); + for r in rs { + assert_eq!(r["stack_end"].as_i64().unwrap(), 10000 + r["net"].as_i64().unwrap()); + } + // seq is gap-free over the sequenced events seen by this client + let seqs: Vec = evs.iter().filter(|(_, m)| m["seq"].is_u64() && m["type"] != "your_turn").map(|(_, m)| m["seq"].as_i64().unwrap()).collect(); + assert!(seqs.windows(2).all(|w| w[1] > w[0])); + } + let (_, tj) = s.get(&format!("/v1/tables/{t}"), None).await; + assert_eq!(tj["seats"].as_array().unwrap().len(), 6); +} + +// ---- 12.8 / 12.9 duplicate matches, history, standings, leaderboard ---- + +fn participants() -> Value { + json!(["house:random", "house:calling_station", "house:tight_aggressive", "house:nit", "house:lag", "house:maniac"]) +} + +#[tokio::test] +async fn v8_v9_duplicate_matches_are_reproducible_and_consistent() { + let s = srv().await; + let mk = |seed: &str| json!({"participants": participants(), "hands_planned": 24, "duplicate": {"enabled": true, "rotations": 6, "deck_from": "seed"}, + "seed": seed, "block_deals": 2, "table_config": {"decision_time_ms": 1000}}); + let mut ids = vec![]; + for seed in ["abc", "abc", "xyz"] { + let (st, v) = s.post("/v1/matches", Some("admin"), mk(seed)).await; + assert_eq!(st, 201, "{v}"); + ids.push(v["match_id"].as_str().unwrap().to_string()); + } + for id in &ids { + let (st, _) = s.post(&format!("/v1/matches/{id}/start"), Some("admin"), json!({})).await; + assert_eq!(st, 200); + } + let mut hands = vec![]; + for id in &ids { + let m = s.wait_match(id).await; + assert_eq!(m["status"], "finished", "{m}"); + assert_eq!(m["hands_played"], 24); + let (st, h) = s.get(&format!("/v1/matches/{id}/hands?limit=500"), Some("admin")).await; + assert_eq!(st, 200); + let h: Vec = h.as_array().unwrap().clone(); + assert_eq!(h.len(), 24); + hands.push((m, h)); + } + // same seed -> identical decks hand by hand; a different seed differs + for k in 0..24 { + assert_eq!(hands[0].1[k]["deck"], hands[1].1[k]["deck"]); + assert_eq!(hands[0].1[k]["deal_no"], hands[1].1[k]["deal_no"]); + } + assert_ne!(hands[0].1[0]["deck"], hands[2].1[0]["deck"]); + // rotation r puts participant p in seat (p + r) mod 6; the cards fall on the same seats + let (m, h) = &hands[0]; + let parts: Vec = m["participants"].as_array().unwrap().iter().map(|p| p.as_str().unwrap().to_string()).collect(); + let mut by_deal: std::collections::BTreeMap> = Default::default(); + for x in h { + by_deal.entry(x["deal_no"].as_u64().unwrap()).or_default().push(x); + let r = x["rotation"].as_u64().unwrap() as usize; + for p in x["players"].as_array().unwrap() { + let seat = p["seat"].as_u64().unwrap() as usize; + let idx = parts.iter().position(|q| q == p["player_id"].as_str().unwrap()).unwrap(); + assert_eq!((idx + r) % 6, seat); + } + // v9 + let net: i64 = x["results"].as_array().unwrap().iter().map(|r| r["net"].as_i64().unwrap()).sum(); + assert_eq!(net, 0); + for (r, p) in x["results"].as_array().unwrap().iter().zip(x["players"].as_array().unwrap()) { + assert_eq!(r["stack_end"].as_i64().unwrap(), p["stack_start"].as_i64().unwrap() + r["net"].as_i64().unwrap()); + } + assert_eq!(x["anomalies"], json!([])); + } + assert_eq!(by_deal.len(), 4); + for (_, hs) in by_deal { + assert_eq!(hs.len(), 6); + let mut rots: Vec = hs.iter().map(|x| x["rotation"].as_u64().unwrap()).collect(); + rots.sort(); + assert_eq!(rots, vec![0, 1, 2, 3, 4, 5]); + assert!(hs.iter().all(|x| x["hole_cards"] == hs[0]["hole_cards"] && x["button_seat"] == hs[0]["button_seat"])); + } + // standings: a list with the SDK-facing fields; chips are conserved + let standings = m["standings"].as_array().unwrap(); + assert_eq!(standings.len(), 6); + let mut total = 0; + for st in standings { + assert!(st["player_id"].is_string() && st["mbb_per_game"].is_number() && st["ci95_mbb"].is_number()); + assert!(st["bb_per_100"].is_number() && st["ci95_bb_per_100"].is_number() && st["duplicate_bb_per_100"].is_number()); + assert_eq!(st["method"], "aivat"); + total += st["net_chips"].as_i64().unwrap(); + } + assert_eq!(total, 0); + // jsonl export + let r = s.http.get(format!("{}/v1/matches/{}/hands.jsonl", s.base, ids[0])).bearer_auth("admin").send().await.unwrap(); + let body = r.text().await.unwrap(); + assert_eq!(body.lines().count(), 24); + assert!(serde_json::from_str::(body.lines().next().unwrap()).is_ok()); + // single hand + events + let hid = h[0]["hand_id"].as_str().unwrap(); + assert_eq!(s.get(&format!("/v1/hands/{hid}"), Some("admin")).await.0, 200); + let (st, ev) = s.get(&format!("/v1/hands/{hid}/events"), Some("admin")).await; + assert_eq!(st, 200); + assert!(ev.as_array().unwrap().iter().any(|e| e["type"] == "hand_end")); + // leaderboard (min hands lowered to 6 in the test config) + let (st, lb) = s.get("/v1/leaderboard", None).await; + assert_eq!(st, 200); + let rows = lb["rows"].as_array().unwrap(); + assert_eq!(rows.len(), 6); + assert!(rows.windows(2).all(|w| w[0]["score_mbb_per_hand"].as_f64() >= w[1]["score_mbb_per_hand"].as_f64())); + assert!(rows[0]["ci95_mbb_per_hand"].as_f64().unwrap() > 0.0); + let (_, lb2) = s.get("/v1/leaderboard?min_hands=100000", None).await; + assert_eq!(lb2["rows"].as_array().unwrap().len(), 0); +} + +#[tokio::test] +async fn running_match_hands_are_private_and_matches_can_be_aborted() { + let s = srv().await; + let (_, tok) = s.register("spy").await; + let (st, v) = s.post("/v1/matches", Some("admin"), json!({"participants": participants(), "hands_planned": 6, "duplicate": true})).await; + assert_eq!(st, 201, "{v}"); + let id = v["match_id"].as_str().unwrap(); + assert_eq!(s.get(&format!("/v1/matches/{id}/hands"), Some(&tok)).await.0, 403); + assert_eq!(s.post(&format!("/v1/matches/{id}/start"), Some(&tok), json!({})).await.0, 403); + assert_eq!(s.post(&format!("/v1/matches/{id}/abort"), Some("admin"), json!({})).await.0, 200); + let m = s.wait_match(id).await; + assert_eq!(m["status"], "aborted"); + // bad duplicate size + let (st, _) = s.post("/v1/matches", Some("admin"), json!({"participants": participants(), "hands_planned": 7, "duplicate": true})).await; + assert_eq!(st, 400); +} + + +// ---- table_seq is gap-free per recipient ---- + +fn assert_gap_free(evs: &[(usize, Value)], clients: usize) { + for c in 0..clients { + let seqs: Vec = evs.iter().filter(|(i, m)| *i == c && m["table_seq"].is_u64()).map(|(_, m)| m["table_seq"].as_u64().unwrap()).collect(); + assert!(seqs.len() > 3, "client {c} saw {} sequenced messages", seqs.len()); + assert_eq!(seqs[0], 1, "client {c} starts at 1"); + for w in seqs.windows(2) { + assert_eq!(w[1], w[0] + 1, "client {c}: table_seq gap {} -> {}", w[0], w[1]); + } + } +} + +#[tokio::test] +async fn table_seq_is_gap_free_per_recipient() { + let s = srv().await; + let t = s.table(json!({"mode": "sandbox", "sandbox": {"button_seat": 3}})).await; + let mut room = Room::new(&s, 6).await; + room.sit_all(&s, &t, &[0, 1, 2, 3, 4, 5]).await; + // everyone calls/checks to the river: private hole_cards, per-seat your_turn and public events interleave + let evs = room.run_hand(&t, 6, |_, d| if d["legal"]["check"] == true { Some(("check", None)) } else { Some(("call", None)) }).await; + assert_gap_free(&evs, 6); + // each client got exactly one hole_cards (its own), so the global counter differs from theirs + for c in 0..6 { + assert_eq!(evs.iter().filter(|(i, m)| *i == c && m["type"] == "hole_cards").count(), 1); + } +} + +#[tokio::test] +async fn benchmark_mode_sends_only_your_turn_and_hand_end() { + let s = srv().await; + let t = s.table(json!({"mode": "benchmark", "sandbox": null, "decision_time_ms": 3000})).await; + let mut room = Room::new(&s, 1).await; + room.sit_all(&s, &t, &[0]).await; + let (st, _) = s.post(&format!("/v1/tables/{t}/fill"), Some("admin"), json!({"bot": "house:calling_station"})).await; + assert_eq!(st, 200); + let mut all = vec![]; + for _ in 0..3 { + all.extend(room.run_hand(&t, 1, |_, d| if d["legal"]["check"] == true { Some(("check", None)) } else { Some(("call", None)) }).await); + } + for (_, m) in &all { + let ty = m["type"].as_str().unwrap(); + assert!(["your_turn", "hand_end", "seat_update", "welcome", "table_snapshot"].contains(&ty), "unexpected {ty} in benchmark mode"); + } + assert!(all.iter().any(|(_, m)| m["type"] == "your_turn" && m["data"]["hole_cards"].as_array().unwrap().len() == 2)); + assert_eq!(all.iter().filter(|(_, m)| m["type"] == "hand_end").count(), 3); + assert_gap_free(&all, 1); + // nothing is lost: hands are stored (async writer) and readable + let (st, hand) = s.get(&format!("/v1/hands/{t}-h1"), Some("admin")).await; + assert_eq!(st, 200, "{hand}"); + assert_eq!(hand["results"].as_array().unwrap().len(), 6); +} + +// ---- parallel lanes ---- + +#[tokio::test] +async fn lanes_play_every_hand_once_and_keep_decks_reproducible() { + let s = srv().await; + let mk = |lanes: usize| json!({"participants": participants(), "hands_planned": 72, "duplicate": true, "seed": "lanes", + "block_deals": 2, "lanes": lanes, "table_config": {"mode": "benchmark"}}); + let mut ms = vec![]; + for lanes in [1, 3] { + let (st, v) = s.post("/v1/matches", Some("admin"), mk(lanes)).await; + assert_eq!(st, 201, "{v}"); + assert_eq!(v["table_ids"].as_array().unwrap().len(), lanes); + let id = v["match_id"].as_str().unwrap().to_string(); + s.post(&format!("/v1/matches/{id}/start"), Some("admin"), json!({})).await; + let m = s.wait_match(&id).await; + assert_eq!(m["status"], "finished"); + assert_eq!(m["hands_played"], 72); + let (_, h) = s.get(&format!("/v1/matches/{id}/hands?limit=500"), Some("admin")).await; + ms.push((m, h.as_array().unwrap().clone())); + } + for (k, (_, h)) in ms.iter().enumerate() { + let nos: Vec = h.iter().map(|x| x["hand_no"].as_u64().unwrap()).collect(); + assert_eq!(nos, (1..=72).collect::>(), "run {k}"); + } + for i in 0..72 { + assert_eq!(ms[0].1[i]["deck"], ms[1].1[i]["deck"]); + assert_eq!(ms[0].1[i]["deal_no"], ms[1].1[i]["deal_no"]); + assert_eq!(ms[0].1[i]["rotation"], ms[1].1[i]["rotation"]); + } + // the same duplicate scores regardless of lane count (house bots are seeded per deal) + let s0: Vec = ms[0].0["standings"].as_array().unwrap().iter().map(|x| x["net_chips"].as_f64().unwrap()).collect(); + let s1: Vec = ms[1].0["standings"].as_array().unwrap().iter().map(|x| x["net_chips"].as_f64().unwrap()).collect(); + assert_eq!(s0, s1); +} + +// ---- benchmark tracks ---- + +#[tokio::test] +async fn benchmark_track_needs_the_blueprint_and_lists_panels() { + let s = srv().await; + let (st, v) = s.get("/v1/benchmarks", None).await; + assert_eq!(st, 200); + assert_eq!(v.as_array().unwrap().len(), 2); + assert_eq!(v[0]["track"], "ladder-v1"); + assert_eq!(v[0]["available"], false); + assert_eq!(v[0]["default_hands"], 20000); + let (st, e) = s.post("/v1/benchmarks/ladder-v1/runs", Some("admin"), json!({"player_id": "house:random", "hands": 60})).await; + assert_eq!(st, 400, "{e}"); + assert_eq!(s.post("/v1/benchmarks/nope/runs", Some("admin"), json!({})).await.0, 404); +} + +#[tokio::test] +async fn benchmark_runs_house_verified_remote_unverified_with_progress() { + let Some(bp) = test_blueprint() else { + eprintln!("skipped: no tiny blueprint (set SHARINGAN_TEST_BLUEPRINT)"); + return; + }; + let s = srv_with(Some(bp)).await; + // house bot: server-run, verified + let (st, run) = s.post("/v1/benchmarks/ladder-v1/runs", Some("admin"), json!({"player_id": "house:tight_aggressive", "hands": 600})).await; + assert_eq!(st, 201, "{run}"); + assert_eq!(run["verified"], true); + assert_eq!(run["hands_planned"], 600); + let rid = run["run_id"].as_str().unwrap().to_string(); + let mut done = Value::Null; + for _ in 0..300 { + let (_, r) = s.get(&format!("/v1/benchmarks/ladder-v1/runs/{rid}"), None).await; + assert!(r["hands_total"] == 600); + if r["status"] == "finished" { + done = r; + break; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + assert_eq!(done["status"], "finished", "{done}"); + assert_eq!(done["hands_done"], 600); + assert!(done["mbb_per_game"].is_number() && done["ci95_mbb"].as_f64().unwrap() > 0.0); + assert_eq!(done["method"], "aivat"); + // a remote bot: unverified, gets benchmark_progress over its socket + let mut room = Room::new(&s, 1).await; + let (st, run2) = s + .post("/v1/benchmarks/sharingan-1/runs", Some(&room.ids[0].1), json!({"hands": 120, "lanes": 2})) + .await; + assert_eq!(st, 201, "{run2}"); + assert_eq!(run2["verified"], false); + let mut progress = 0; + let mut final_status = String::new(); + while final_status.is_empty() { + let (i, m) = room.recv().await; + match m["type"].as_str().unwrap() { + "your_turn" => { + let d = m["data"].clone(); + let ty = if d["legal"]["check"] == true { "check" } else { "call" }; + room.act(i, m["table_id"].as_str().unwrap(), &d, ty, None); + } + "benchmark_progress" => { + progress += 1; + assert_eq!(m["data"]["hands_total"], 120); + if m["data"]["status"] != "running" { + final_status = m["data"]["status"].as_str().unwrap().to_string(); + assert_eq!(m["data"]["verified"], false); + } + } + _ => {} + } + } + assert_eq!(final_status, "finished"); + assert!(progress >= 1); + // leaderboard: one column per track + verified flag, in the field names the site reads + let (st, lb) = s.get("/v1/leaderboard?min_hands=100000", None).await; + assert_eq!(st, 200); + let rows = lb["rows"].as_array().unwrap(); + let house = rows.iter().find(|r| r["player_id"] == "house:tight_aggressive").expect("house row"); + assert_eq!(house["verified"], true); + assert!(house["vs_ladder_v1"]["mbb"].is_number() && house["vs_ladder_v1"]["ci95_mbb"].is_number() && house["vs_ladder_v1"]["hands"] == 600); + assert!(house["vs_sharingan_1"].is_null()); + let bot = rows.iter().find(|r| r["player_id"] == room.ids[0].0.as_str()).expect("bot row"); + assert_eq!(bot["verified"], false); + assert!(bot["vs_sharingan_1"]["mbb"].is_number()); + let (_, only) = s.get("/v1/leaderboard?track=ladder-v1", None).await; + assert_eq!(only["rows"].as_array().unwrap().len(), 1); + let (_, t) = s.get("/v1/benchmarks/ladder-v1", None).await; + assert_eq!(t["top_runs"].as_array().unwrap().len(), 1); +} + +// ---- hosted attestation (runner token) ---- + +/// Answer every `your_turn` with check/call until the run's final `benchmark_progress`; returns its data. +async fn play_run_out(room: &mut Room) -> Value { + loop { + let (i, m) = room.recv().await; + match m["type"].as_str().unwrap() { + "your_turn" => { + let d = m["data"].clone(); + let ty = if d["legal"]["check"] == true { "check" } else { "call" }; + room.act(i, m["table_id"].as_str().unwrap(), &d, ty, None); + } + "benchmark_progress" if m["data"]["status"] != "running" => return m["data"].clone(), + _ => {} + } + } +} + +#[tokio::test] +async fn hosted_attestation_only_via_the_runner_token() { + let Some(bp) = test_blueprint() else { + eprintln!("skipped: no tiny blueprint (set SHARINGAN_TEST_BLUEPRINT)"); + return; + }; + let s = srv_cfg(Some(bp), |c| c.runner_token = Some("runner-secret".into())).await; + let mut room = Room::new(&s, 1).await; + let (pid, ptok) = room.ids[0].clone(); + // nobody but the runner can ask for a hosted run + for who in [ptok.as_str(), "admin"] { + let (st, e) = s.post("/v1/benchmarks/ladder-v1/runs", Some(who), json!({"player_id": pid, "hands": 12, "hosted": true})).await; + assert_eq!(st, 403, "{e}"); + assert_eq!(e["error"]["code"], "forbidden"); + } + assert_eq!(s.post("/v1/runner/hosted", Some(&ptok), json!({"player_id": pid, "run_id": "x"})).await.0, 403); + assert_eq!(s.post("/v1/runner/hosted", Some("admin"), json!({"player_id": pid, "run_id": "x"})).await.0, 403); + assert_eq!(s.post("/v1/runner/hosted", None, json!({"player_id": pid, "run_id": "x"})).await.0, 401); + // the runner token is not an admin token + assert_eq!(s.post("/v1/tables", Some("runner-secret"), json!({})).await.0, 403); + assert_eq!(s.post("/v1/benchmarks/ladder-v1/runs", Some("runner-secret"), json!({"hands": 12})).await.0, 400); // player_id required + // runner starts a hosted run: verified, and stays verified on the leaderboard + let (st, run) = s.post("/v1/benchmarks/ladder-v1/runs", Some("runner-secret"), json!({"player_id": pid, "hands": 12, "hosted": true})).await; + assert_eq!(st, 201, "{run}"); + assert_eq!((run["hosted"].clone(), run["verified"].clone()), (json!(true), json!(true))); + let fin = play_run_out(&mut room).await; + assert_eq!(fin["status"], "finished"); + assert_eq!(fin["verified"], true); + let (_, lb) = s.get("/v1/leaderboard?track=ladder-v1&min_hands=1", None).await; + let row = lb["rows"].as_array().unwrap().iter().find(|r| r["player_id"] == pid.as_str()).expect("row").clone(); + assert_eq!(row["verified"], true); + // a run the runner starts without `hosted` is remote: unverified until attested, and only while running + let (st, run2) = s.post("/v1/benchmarks/ladder-v1/runs", Some("runner-secret"), json!({"player_id": pid, "hands": 12})).await; + assert_eq!(st, 201, "{run2}"); + assert_eq!((run2["hosted"].clone(), run2["verified"].clone()), (json!(false), json!(false))); + let rid = run2["run_id"].as_str().unwrap().to_string(); + let (st, e) = s.post("/v1/runner/hosted", Some("runner-secret"), json!({"player_id": "someone-else", "run_id": rid})).await; + assert_eq!(st, 400, "{e}"); + let (st, a) = s.post("/v1/runner/hosted", Some("runner-secret"), json!({"player_id": pid, "run_id": rid})).await; + assert_eq!(st, 200, "{a}"); + assert_eq!((a["hosted"].clone(), a["verified"].clone()), (json!(true), json!(true))); + let (_, g) = s.get(&format!("/v1/benchmarks/ladder-v1/runs/{rid}"), None).await; + assert_eq!(g["verified"], true); + // revoking works too + let (_, a) = s.post("/v1/runner/hosted", Some("runner-secret"), json!({"player_id": pid, "run_id": rid, "hosted": false})).await; + assert_eq!(a["verified"], false); + s.post("/v1/runner/hosted", Some("runner-secret"), json!({"player_id": pid, "run_id": rid})).await; + assert_eq!(play_run_out(&mut room).await["verified"], true); + let (st, e) = s.post("/v1/runner/hosted", Some("runner-secret"), json!({"player_id": pid, "run_id": rid})).await; + assert_eq!(st, 409, "{e}"); + // a plain remote run by the bot itself stays unverified, and is rejected without a runner token set up + let (st, run3) = s.post("/v1/benchmarks/ladder-v1/runs", Some(&ptok), json!({"hands": 12})).await; + assert_eq!(st, 201, "{run3}"); + assert_eq!(run3["verified"], false); + assert_eq!(play_run_out(&mut room).await["verified"], false); +} + +#[tokio::test] +async fn runner_endpoints_are_off_without_a_runner_token() { + let s = srv().await; + let (st, e) = s.post("/v1/runner/hosted", Some("anything"), json!({"player_id": "x", "run_id": "y"})).await; + assert_eq!(st, 401, "{e}"); +} + +// ---- rate limits and abuse limits ---- + +fn err_code(v: &Value) -> &str { + v["error"]["code"].as_str().unwrap_or("") +} + +#[tokio::test] +async fn bot_registrations_are_capped_per_address_humans_and_admin_are_not() { + let s = srv_cfg(None, |c| c.bots_per_ip_per_day = 2.0).await; + let reg = |name: &str, kind: &str, tok: Option<&str>| { + let body = json!({"name": name, "kind": kind}); + let tok = tok.map(|t| t.to_string()); + let s = &s; + async move { s.req("POST", "/v1/players", tok.as_deref(), Some(body)).await } + }; + assert_eq!(reg("cap_a", "bot", None).await.0, 201); + assert_eq!(reg("cap_b", "bot", None).await.0, 201); + let (st, e) = reg("cap_c", "bot", None).await; + assert_eq!((st, err_code(&e)), (429, "rate_limited"), "{e}"); + assert_eq!(e["error"]["details"]["limit"], "ARENA_BOTS_PER_IP_PER_DAY"); + assert_eq!(reg("cap_human", "human", None).await.0, 201, "people at the play page have their own, 10x roomier bucket"); + assert_eq!(reg("cap_admin", "bot", Some("admin")).await.0, 201, "the admin token is exempt"); + let (st, e) = reg("Sharingan-3", "bot", Some("admin")).await; + assert_eq!(st, 400, "reserved names stay reserved: {e}"); + for (name, kind) in [("SHARINGAN-1", "human"), ("nit", "human"), ("house-maniac", "bot"), ("R\u{430}ndom", "bot"), ("\u{ff33}haringan", "bot")] { + let (st, e) = reg(name, kind, Some("admin")).await; + assert_eq!(st, 400, "{name} ({kind}) is refused: {e}"); + } +} + +#[tokio::test] +async fn request_rate_limit_is_per_token_with_retry_after() { + let s = srv_cfg(None, |c| { + c.rate_limit_rps = 0.5; + c.rate_limit_burst = 5.0; + }) + .await; + let (_, a) = s.register("a").await; // 1 anonymous request + let (_, b) = s.register("b").await; // 2 + for _ in 0..3 { + assert_eq!(s.get("/v1/leaderboard", None).await.0, 200); // 3,4,5 + } + let resp = s.http.get(format!("{}/v1/leaderboard", s.base)).send().await.unwrap(); + assert_eq!(resp.status().as_u16(), 429); + let ra: u64 = resp.headers()["retry-after"].to_str().unwrap().parse().unwrap(); + assert!((1..=3).contains(&ra), "{ra}"); + let body: Value = resp.json().await.unwrap(); + assert_eq!(err_code(&body), "rate_limited", "{body}"); + assert_eq!(body["error"]["details"]["limit"], "ARENA_RATE_LIMIT_RPS"); + assert!(body["error"]["details"]["retry_after_ms"].as_u64().unwrap() > 0); + // buckets are per token: a and b are unaffected by the anonymous flood and by each other + for tok in [&a, &b] { + assert_eq!(s.get("/v1/leaderboard", Some(tok)).await.0, 200); + } + for _ in 0..4 { + assert_eq!(s.get("/v1/leaderboard", Some(&a)).await.0, 200); + } + let (st, e) = s.get("/v1/leaderboard", Some(&a)).await; + assert_eq!((st, err_code(&e)), (429, "rate_limited")); + assert_eq!(s.get("/v1/leaderboard", Some(&b)).await.0, 200); + // admin and health probes are exempt + for _ in 0..30 { + assert_eq!(s.get("/v1/leaderboard", Some("admin")).await.0, 200); + assert_eq!(s.get("/healthz", None).await.0, 200); + assert_eq!(s.get("/readyz", None).await.0, 200); + } + // the 429 carries CORS headers so browsers can read it + let resp = s.http.get(format!("{}/v1/leaderboard", s.base)).send().await.unwrap(); + assert_eq!(resp.status().as_u16(), 429); + assert_eq!(resp.headers()["access-control-allow-origin"], "*"); +} + +#[tokio::test] +async fn open_tables_per_player_are_capped_and_freed_by_delete() { + let s = srv_cfg(None, |c| c.max_tables_per_player = 2).await; + let (pid, tok) = s.register("capped").await; + let mut ids = vec![]; + for _ in 0..2 { + let (st, t) = s.post("/v1/tables", Some(&tok), json!({"decision_time_ms": 1000})).await; + assert_eq!(st, 201, "{t}"); + ids.push(t["table_id"].as_str().unwrap().to_string()); + } + let (st, e) = s.post("/v1/tables", Some(&tok), json!({})).await; + assert_eq!((st, err_code(&e)), (429, "rate_limited"), "{e}"); + assert_eq!(e["error"]["details"]["limit"], "ARENA_MAX_TABLES_PER_PLAYER"); + // sitting at someone else's table counts too + let other = s.table(json!({"decision_time_ms": 1000})).await; // admin-owned + let (st, e) = s.post(&format!("/v1/tables/{other}/seats/0"), Some(&tok), json!({"player_id": pid})).await; + assert_eq!((st, err_code(&e)), (429, "rate_limited"), "{e}"); + // only the owner or admin can close; closing frees a slot + let (_, tok2) = s.register("stranger").await; + assert_eq!(s.req("DELETE", &format!("/v1/tables/{}", ids[0]), Some(&tok2), None).await.0, 403); + let (st, c) = s.req("DELETE", &format!("/v1/tables/{}", ids[0]), Some(&tok), None).await; + assert_eq!(st, 200, "{c}"); + assert_eq!(c["status"], "closed"); + assert_eq!(s.post("/v1/tables", Some(&tok), json!({"decision_time_ms": 1000})).await.0, 201); + // house bots and the admin are not capped + for _ in 0..4 { + s.table(json!({"decision_time_ms": 1000})).await; + } +} + +#[tokio::test] +async fn unfinished_matches_per_player_and_hand_caps() { + let s = srv_cfg(None, |c| { + c.max_matches_per_player = 1; + c.max_match_hands = 60; + c.max_run_hands = 600; + }) + .await; + let (_, tok) = s.register("m").await; + let m = json!({"participants": participants(), "hands_planned": 12, "table_config": {"decision_time_ms": 1000}}); + let (st, v) = s.post("/v1/matches", Some(&tok), m.clone()).await; + assert_eq!(st, 201, "{v}"); + let (st, e) = s.post("/v1/matches", Some(&tok), m.clone()).await; + assert_eq!((st, err_code(&e)), (429, "rate_limited"), "{e}"); + assert_eq!(e["error"]["details"]["limit"], "ARENA_MAX_MATCHES_PER_PLAYER"); + assert_eq!(s.post("/v1/matches", Some("admin"), m.clone()).await.0, 201); // admin exempt + // hands cap on matches (admin included) and on benchmark runs (players) + let big = json!({"participants": participants(), "hands_planned": 66}); + let (st, e) = s.post("/v1/matches", Some("admin"), big).await; + assert_eq!(st, 400, "{e}"); + assert_eq!(e["error"]["details"]["limit"], "ARENA_MAX_MATCH_HANDS"); + let (_, tok2) = s.register("r").await; + let (st, e) = s.post("/v1/benchmarks/ladder-v1/runs", Some(&tok2), json!({"hands": 6000})).await; + assert_eq!(st, 400, "{e}"); + assert_eq!(e["error"]["details"]["limit"], "ARENA_MAX_RUN_HANDS"); +} + +#[tokio::test] +async fn websockets_per_player_are_capped() { + let s = srv_cfg(None, |c| c.max_ws_per_player = 2).await; + let (_, tok) = s.register("w").await; + let url = format!("{}/v1/play?token={tok}", s.ws); + let (a, _) = connect_async(&url).await.unwrap(); + let (b, _) = connect_async(&url).await.unwrap(); + for _ in 0..50 { + if s.rs.app.hub.total() == 2 { + break; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + match connect_async(&url).await { + Err(tokio_tungstenite::tungstenite::Error::Http(r)) => { + assert_eq!(r.status().as_u16(), 429); + let body: Value = serde_json::from_slice(r.body().as_deref().unwrap_or(b"{}")).unwrap_or_default(); + assert_eq!(err_code(&body), "rate_limited", "{body}"); + } + other => panic!("expected a 429 handshake, got {:?}", other.map(|_| "connected")), + } + // another player is unaffected; closing one frees a slot + let (_, tok2) = s.register("w2").await; + connect_async(format!("{}/v1/play?token={tok2}", s.ws)).await.unwrap(); + drop(a); + let mut ok = false; + for _ in 0..100 { + if connect_async(&url).await.is_ok() { + ok = true; + break; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + assert!(ok, "slot never freed"); + drop(b); +} + +#[tokio::test] +async fn payload_size_limits() { + let s = srv_cfg(None, |c| { + c.max_body_bytes = 1024; + c.max_ws_message_bytes = 256; + }) + .await; + let (st, e) = s.post("/v1/bots", None, json!({"name": "x".repeat(5000)})).await; + assert_eq!(st, 413, "{e}"); + assert_eq!(err_code(&e), "payload_too_large"); + assert_eq!(e["error"]["details"]["max_bytes"], 1024); + assert_eq!(s.post("/v1/bots", None, json!({"name": "fine"})).await.0, 201); + // an oversized WebSocket message ends the connection; small ones are fine + let (_, tok) = s.register("big").await; + let (mut ws, _) = connect_async(format!("{}/v1/play?token={tok}", s.ws)).await.unwrap(); + ws.send(Message::Text(json!({"v": 1, "type": "ping", "data": {}}).to_string().into())).await.unwrap(); + let pong = tokio::time::timeout(Duration::from_secs(5), ws.next()).await.unwrap().unwrap().unwrap(); + assert!(pong.to_text().unwrap().contains("pong")); + ws.send(Message::Text(format!("{{\"type\":\"ping\",\"pad\":\"{}\"}}", "x".repeat(2000)).into())).await.unwrap(); + let end = tokio::time::timeout(Duration::from_secs(5), async { + loop { + match ws.next().await { + None | Some(Err(_)) | Some(Ok(Message::Close(_))) => return, + Some(Ok(_)) => {} + } + } + }) + .await; + assert!(end.is_ok(), "socket stayed open after an oversized message"); +} + +// ---- health, readiness, graceful shutdown ---- + +#[tokio::test] +async fn health_and_readiness() { + let s = srv().await; + let (st, v) = s.get("/healthz", None).await; + assert_eq!((st, v.as_str()), (200, Some("ok"))); + let (st, v) = s.get("/readyz", None).await; + assert_eq!(st, 200, "{v}"); + assert_eq!((v["status"].as_str(), v["db"].as_str(), v["draining"].as_bool()), (Some("ready"), Some("ok"), Some(false))); + assert_eq!(s.get("/livez", None).await.0, 200); +} + +#[tokio::test] +async fn graceful_shutdown_drains_aborts_and_closes_sockets() { + let s = srv_cfg(None, |c| c.shutdown_grace_ms = 300).await; + let (_, tok) = s.register("sd").await; + let (mut ws, _) = connect_async(format!("{}/v1/play?token={}", s.ws, tok)).await.unwrap(); + // a long all-house match that cannot finish within the grace period + let (st, m) = s + .post("/v1/matches", Some("admin"), json!({"participants": participants(), "hands_planned": 600000, "duplicate": true, + "aivat": "off", "table_config": {"decision_time_ms": 1000}})) + .await; + assert_eq!(st, 201, "{m}"); + let mid = m["match_id"].as_str().unwrap().to_string(); + assert_eq!(s.post(&format!("/v1/matches/{mid}/start"), Some("admin"), json!({})).await.0, 200); + tokio::time::sleep(Duration::from_millis(200)).await; + let (base, app, http) = (s.base.clone(), s.rs.app.clone(), s.http.clone()); + let Srv { rs, .. } = s; + let down = tokio::spawn(rs.shutdown()); + // draining: not ready, new work refused, reads still served + let mut saw = false; + for _ in 0..50 { + let r = http.get(format!("{base}/readyz")).send().await.unwrap(); + if r.status().as_u16() == 503 { + let v: Value = r.json().await.unwrap(); + assert_eq!(v["status"], "draining"); + saw = true; + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + assert!(saw, "readyz never turned 503"); + let r = http.post(format!("{base}/v1/tables")).bearer_auth("admin").json(&json!({})).send().await.unwrap(); + assert_eq!(r.status().as_u16(), 503); + let v: Value = r.json().await.unwrap(); + assert_eq!(err_code(&v), "shutting_down"); + assert_eq!(http.get(format!("{base}/healthz")).send().await.unwrap().status().as_u16(), 200); + tokio::time::timeout(Duration::from_secs(30), down).await.expect("shutdown hung").unwrap(); + // the unfinished match was aborted and persisted; the socket got closed + let rec = app.store.get_match(&mid).unwrap().unwrap(); + assert_eq!(rec.status, "aborted"); + let closed = tokio::time::timeout(Duration::from_secs(5), async { + loop { + match ws.next().await { + None | Some(Err(_)) | Some(Ok(Message::Close(_))) => return, + Some(Ok(_)) => {} + } + } + }) + .await; + assert!(closed.is_ok(), "websocket not closed by shutdown"); + assert!(http.get(format!("{base}/healthz")).send().await.is_err(), "still accepting connections"); +} + +// ---- human UIs: hold the table between hands, `next_hand` skips the pause ---- + +#[tokio::test] +async fn next_hand_ends_the_pause_between_hands_early() { + let s = srv().await; + let t = s.table(json!({"decision_time_ms": 3000, "hand_delay_ms": 60000})).await; + let mut room = Room::new(&s, 1).await; + room.sit_all(&s, &t, &[0]).await; + let (st, v) = s.post(&format!("/v1/tables/{t}/fill"), Some("admin"), json!({"bot": "house:tight_aggressive"})).await; + assert_eq!(st, 200, "{v}"); + let evs = room.run_hand(&t, 1, |_, d| fold_or_check(d)).await; + assert_eq!(of_type(&evs, "hand_end").count(), 1); + // The table is held: no new hand starts while the pause runs. + let held = tokio::time::timeout(Duration::from_millis(1200), async { + loop { + let (_, m) = room.recv().await; + if m["type"] == "hand_start" { + return; + } + } + }) + .await; + assert!(held.is_err(), "a hand started during the pause"); + room.send(0, "next_hand", Some(&t), json!({})); + let next = tokio::time::timeout(Duration::from_secs(10), async { + loop { + let (_, m) = room.recv().await; + if m["type"] == "hand_start" { + return m; + } + } + }) + .await + .expect("next_hand did not start the next hand"); + assert_eq!(next["data"]["hand_no"], 2); +} + +// ---- abandoned free tables close themselves ---- + +#[tokio::test] +async fn abandoned_free_table_closes_itself_and_frees_its_slot() { + let s = srv().await; + // The env knob is read when a table is spawned: only `t` gets the short timeout. + std::env::set_var("ARENA_TABLE_ABANDON_MS", "1000"); + let t = s.table(json!({})).await; + std::env::remove_var("ARENA_TABLE_ABANDON_MS"); + let t2 = s.table(json!({})).await; + let mut closed = false; + for _ in 0..40 { + let (_, v) = s.get(&format!("/v1/tables/{t}"), None).await; + if v["status"] == "closed" { + closed = true; + break; + } + tokio::time::sleep(Duration::from_millis(250)).await; + } + assert!(closed, "a table nobody is connected to must close after the abandon timeout"); + let (_, v) = s.get(&format!("/v1/tables/{t2}"), None).await; + assert_ne!(v["status"], "closed", "the default timeout is far longer"); +} diff --git a/arena/server/tests/hardening.rs b/arena/server/tests/hardening.rs new file mode 100644 index 00000000..1aaff950 --- /dev/null +++ b/arena/server/tests/hardening.rs @@ -0,0 +1,325 @@ +//! Release hardening: match ownership and connection checks, the JSON error envelope on every rejection, +//! player-name validation, hand-page limits. In-process server on an ephemeral port, in-memory SQLite. + +use arena_server::config::ServerConfig; +use arena_server::{start, RunningServer}; +use futures_util::{SinkExt, StreamExt}; +use serde_json::{json, Value}; +use std::time::Duration; +use tokio_tungstenite::{connect_async, tungstenite::Message}; + +struct Srv { + base: String, + ws: String, + rs: RunningServer, + http: reqwest::Client, +} + +async fn srv() -> Srv { + let cfg = ServerConfig { + rate_limit_rps: 0.0, + sizing: "tiny".into(), + bind: "127.0.0.1:0".into(), + db_path: ":memory:".into(), + admin_token: Some("admin".into()), + hand_delay_ms: 0, + reconnect_grace_ms: 200, + ..Default::default() + }; + let rs = start(cfg).await.unwrap(); + Srv { base: format!("http://{}", rs.addr), ws: format!("ws://{}", rs.addr), rs, http: reqwest::Client::new() } +} + +fn err_code(v: &Value) -> &str { + v["error"]["code"].as_str().unwrap_or("") +} + +fn house() -> Vec<&'static str> { + vec!["house:random", "house:calling_station", "house:tight_aggressive", "house:nit", "house:lag", "house:maniac"] +} + +fn with_first(first: &str) -> Value { + let mut p = house(); + p[0] = first; + json!(p) +} + +impl Srv { + async fn req(&self, method: &str, path: &str, token: Option<&str>, body: Option) -> (u16, Value) { + let m = reqwest::Method::from_bytes(method.as_bytes()).unwrap(); + let mut r = self.http.request(m, format!("{}{}", self.base, path)); + if let Some(t) = token { + r = r.bearer_auth(t); + } + if let Some(b) = body { + r = r.json(&b); + } + let resp = r.send().await.unwrap(); + let st = resp.status().as_u16(); + let txt = resp.text().await.unwrap(); + (st, serde_json::from_str(&txt).unwrap_or(Value::String(txt))) + } + async fn post(&self, p: &str, t: Option<&str>, b: Value) -> (u16, Value) { + self.req("POST", p, t, Some(b)).await + } + async fn get(&self, p: &str, t: Option<&str>) -> (u16, Value) { + self.req("GET", p, t, None).await + } + async fn register(&self, name: &str) -> (String, String) { + let (st, v) = self.post("/v1/bots", None, json!({"name": name, "kind": "bot"})).await; + assert_eq!(st, 201, "{v}"); + (v["player_id"].as_str().unwrap().into(), v["token"].as_str().unwrap().into()) + } + async fn wait_match(&self, id: &str) -> Value { + for _ in 0..600 { + let (_, v) = self.get(&format!("/v1/matches/{id}"), None).await; + if v["status"] == "finished" || v["status"] == "aborted" { + return v; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + panic!("match did not finish"); + } + /// Open /v1/play for the token and wait for the welcome; the returned sink keeps the socket (and the bot "connected") alive. + async fn connect(&self, token: &str) -> tokio::task::JoinHandle<()> { + let (ws, _) = connect_async(format!("{}/v1/play?token={token}", self.ws)).await.unwrap(); + let (mut w, mut r) = ws.split(); + w.send(Message::Text(json!({"v": 1, "type": "hello", "t_ms": 0, "data": {"client": "test"}}).to_string().into())).await.unwrap(); + while let Some(Ok(Message::Text(t))) = r.next().await { + if serde_json::from_str::(t.as_str()).unwrap()["type"] == "welcome" { + break; + } + } + tokio::spawn(async move { + let _keep = w; + while r.next().await.is_some() {} + }) + } +} + +// ---------------------------------------------------------------------------------------------- 1: match ownership + +#[tokio::test] +async fn nobody_can_run_a_match_that_scores_someone_elses_bot() { + let s = srv().await; + let (victim, _victim_tok) = s.register("victim").await; + let (mine, mytok) = s.register("attacker").await; + let body = |first: &str| json!({"participants": with_first(first), "hands_planned": 6, "table_config": {"decision_time_ms": 1000}}); + + let (st, e) = s.post("/v1/matches", Some(&mytok), body(&victim)).await; + assert_eq!((st, err_code(&e)), (403, "forbidden"), "{e}"); + assert!(e["error"]["message"].as_str().unwrap().contains("you can only run your own bot"), "{e}"); + // same wording as the benchmark endpoint (ownership is checked before the panel is resolved) + let (st, e2) = s.post("/v1/benchmarks/ladder-v1/runs", Some(&mytok), json!({"player_id": victim, "hands": 6})).await; + assert_eq!((st, err_code(&e2)), (403, "forbidden"), "{e2}"); + assert_eq!(e["error"]["message"], e2["error"]["message"]); + // nothing was created, and the victim has no results + let (_, list) = s.get("/v1/matches", None).await; + assert_eq!(list.as_array().unwrap().len(), 0); + let (_, v) = s.get(&format!("/v1/players/{victim}"), None).await; + assert_eq!(v["stats"]["matches"], 0); + + // your own bot, with house bots around it, is fine; so is the admin entering anybody + let (st, m) = s.post("/v1/matches", Some(&mytok), body(&mine)).await; + assert_eq!(st, 201, "{m}"); + let (st, m2) = s.post("/v1/matches", Some("admin"), body(&victim)).await; + assert_eq!(st, 201, "{m2}"); + // two different players in one match is admin-only as well (a second bot of yours cannot be told apart from a stranger's) + let (other, _) = s.register("other").await; + let mut two = house(); + two[0] = &mine; + two[1] = &other; + let (st, e) = s.post("/v1/matches", Some(&mytok), json!({"participants": two, "hands_planned": 6})).await; + assert_eq!((st, err_code(&e)), (403, "forbidden"), "{e}"); + // a stranger cannot start the admin's match with the victim in it + let mid = m2["match_id"].as_str().unwrap(); + assert_eq!(s.post(&format!("/v1/matches/{mid}/start"), Some(&mytok), json!({})).await.0, 403); + // `owner` is a free-text label chosen at registration, so it grants nothing + let (st, liar) = s.post("/v1/bots", None, json!({"name": "liar", "owner": "attacker"})).await; + assert_eq!(st, 201); + let (st, _) = s.post("/v1/matches", Some(&mytok), body(liar["player_id"].as_str().unwrap())).await; + assert_eq!(st, 403); +} + +// ---------------------------------------------------------------------------------------------- 2: start needs connected bots + +#[tokio::test] +async fn start_refuses_a_disconnected_participant_unless_admin() { + let s = srv().await; + let (pid, tok) = s.register("offline").await; + let (st, m) = s + .post("/v1/matches", Some(&tok), json!({"participants": with_first(&pid), "hands_planned": 6, "table_config": {"decision_time_ms": 1000}})) + .await; + assert_eq!(st, 201, "{m}"); + let mid = m["match_id"].as_str().unwrap().to_string(); + let (st, e) = s.post(&format!("/v1/matches/{mid}/start"), Some(&tok), json!({})).await; + assert_eq!((st, err_code(&e)), (409, "not_connected"), "{e}"); + assert_eq!(e["error"]["details"]["player_id"], json!(pid)); + let (_, now) = s.get(&format!("/v1/matches/{mid}"), None).await; + assert_eq!((now["status"].as_str(), now["hands_played"].as_u64()), (Some("scheduled"), Some(0)), "nothing was played"); + // resume goes through the same check + assert_eq!(s.post(&format!("/v1/matches/{mid}/resume"), Some(&tok), json!({})).await.0, 409); + // connect, then it starts + let _sock = s.connect(&tok).await; + let (st, started) = s.post(&format!("/v1/matches/{mid}/start"), Some(&tok), json!({})).await; + assert_eq!(st, 200, "{started}"); + assert_eq!(started["status"], "running"); + // starting a running match again stays a harmless no-op + assert_eq!(s.post(&format!("/v1/matches/{mid}/start"), Some(&tok), json!({})).await.0, 200); + assert_eq!(s.post(&format!("/v1/matches/{mid}/abort"), Some("admin"), json!({})).await.0, 200); + s.wait_match(&mid).await; + + // the admin may start it without the bot being there (it plays on with auto-folds) + let (st, m) = s.post("/v1/matches", Some("admin"), json!({"participants": with_first(&pid), "hands_planned": 6, "table_config": {"decision_time_ms": 1000}})).await; + assert_eq!(st, 201, "{m}"); + let id2 = m["match_id"].as_str().unwrap(); + assert_eq!(s.post(&format!("/v1/matches/{id2}/start"), Some("admin"), json!({})).await.0, 200); + s.post(&format!("/v1/matches/{id2}/abort"), Some("admin"), json!({})).await; + s.wait_match(id2).await; + // house-only matches need nobody connected + let (st, m) = s.post("/v1/matches", Some(&tok), json!({"participants": house(), "hands_planned": 6, "table_config": {"decision_time_ms": 1000}})).await; + assert_eq!(st, 201, "{m}"); + let id3 = m["match_id"].as_str().unwrap(); + assert_eq!(s.post(&format!("/v1/matches/{id3}/start"), Some(&tok), json!({})).await.0, 200); + assert_eq!(s.wait_match(id3).await["status"], "finished"); + let _ = &s.rs; +} + +// ---------------------------------------------------------------------------------------------- 5: JSON error envelope + +async fn raw(s: &Srv, method: &str, path: &str, ctype: Option<&str>, body: &str, token: Option<&str>) -> (u16, String, Value, reqwest::header::HeaderMap) { + let mut r = s.http.request(reqwest::Method::from_bytes(method.as_bytes()).unwrap(), format!("{}{}", s.base, path)); + if let Some(c) = ctype { + r = r.header("content-type", c); + } + if let Some(t) = token { + r = r.bearer_auth(t); + } + if !body.is_empty() { + r = r.body(body.to_string()); + } + let resp = r.send().await.unwrap(); + let st = resp.status().as_u16(); + let headers = resp.headers().clone(); + let ct = headers.get("content-type").and_then(|v| v.to_str().ok()).unwrap_or("").to_string(); + let txt = resp.text().await.unwrap(); + let v: Value = serde_json::from_str(&txt).unwrap_or_else(|_| panic!("{method} {path}: body is not JSON ({st}): {txt:?}")); + (st, ct, v, headers) +} + +#[tokio::test] +async fn every_rejection_uses_the_json_error_envelope() { + let s = srv().await; + let (_, tok) = s.register("env").await; + let j = Some("application/json"); + // (method, path, content-type, body, token, expected status, expected code) + let cases: Vec<(&str, &str, Option<&str>, &str, Option<&str>, u16, &str)> = vec![ + ("POST", "/v1/bots", j, "{not json", None, 400, "bad_request"), + ("POST", "/v1/bots", j, "{}", None, 400, "bad_request"), // missing field `name` + ("POST", "/v1/bots", j, r#"{"name": 5}"#, None, 400, "bad_request"), // wrong type + ("POST", "/v1/bots", Some("text/plain"), r#"{"name":"x"}"#, None, 415, "unsupported_media_type"), + ("POST", "/v1/bots", None, r#"{"name":"x"}"#, None, 415, "unsupported_media_type"), + ("POST", "/v1/tables", j, r#"{"max_seats": "six"}"#, Some(&tok), 400, "bad_request"), + ("POST", "/v1/matches", j, r#"{"participants": []}"#, Some(&tok), 400, "bad_request"), // hands_planned missing + ("GET", "/v1/matches/m_x/hands?limit=abc", None, "", Some(&tok), 400, "bad_request"), + ("GET", "/v1/matches/m_x/hands?after_hand_no=-1", None, "", Some(&tok), 400, "bad_request"), + ("GET", "/v1/leaderboard?min_hands=lots", None, "", None, 400, "bad_request"), + ("POST", "/v1/tables/t_x/seats/notanumber", j, "{}", Some(&tok), 400, "bad_request"), + ("GET", "/v1/nope", None, "", None, 404, "not_found"), + ("GET", "/", None, "", None, 404, "not_found"), + ("POST", "/v1/matches/m_x/start/extra", j, "{}", Some(&tok), 404, "not_found"), + ("PUT", "/v1/bots", j, "{}", Some(&tok), 405, "method_not_allowed"), + ("DELETE", "/v1/leaderboard", None, "", None, 405, "method_not_allowed"), + ("GET", "/v1/matches/m_x/start", None, "", None, 405, "method_not_allowed"), + // the existing envelope is untouched + ("GET", "/v1/me", None, "", None, 401, "unauthorized"), + ("GET", "/v1/matches/m_x", None, "", None, 404, "not_found"), + ]; + for (method, path, ct, body, token, want_st, want_code) in cases { + let (st, ctype, v, headers) = raw(&s, method, path, ct, body, token).await; + assert_eq!((st, err_code(&v)), (want_st, want_code), "{method} {path}: {v}"); + assert!(ctype.starts_with("application/json"), "{method} {path}: content-type {ctype}"); + assert!(v["error"]["message"].as_str().map(|m| !m.is_empty()).unwrap_or(false), "{method} {path}: {v}"); + assert!(v["error"]["details"].is_object(), "{method} {path}: {v}"); + assert_eq!(headers.get("access-control-allow-origin").and_then(|h| h.to_str().ok()), Some("*"), "CORS survives the mapping"); + if want_st == 405 { + assert!(headers.contains_key("allow"), "{method} {path}: Allow header kept"); + } + } + // oversized bodies keep their own envelope + let big = "x".repeat(2 << 20); + let (st, _, v, _) = raw(&s, "POST", "/v1/bots", j, &format!(r#"{{"name":"{big}"}}"#), None).await; + assert_eq!((st, err_code(&v)), (413, "payload_too_large")); +} + +// ---------------------------------------------------------------------------------------------- 6: names + +#[tokio::test] +async fn player_names_reject_control_invisible_and_bidi_characters() { + let s = srv().await; + for bad in [ + "nul\u{0}byte", "line\nbreak", "cr\rx", "tab\tx", "esc\u{1b}[31m", "del\u{7f}", "c1\u{85}x", "\u{202e}evil", "a\u{202a}b", "a\u{202d}b", "a\u{2066}b", "a\u{2069}b", + "zero\u{200b}width", "zwnj\u{200c}x", "zwj\u{200d}x", "lrm\u{200e}x", "rlm\u{200f}x", "bom\u{feff}x", "sep\u{2028}x", "wj\u{2060}x", + ] { + let (st, e) = s.post("/v1/bots", None, json!({"name": bad})).await; + assert_eq!((st, err_code(&e)), (400, "bad_request"), "{bad:?}: {e}"); + let (st, _) = s.post("/v1/players", None, json!({"name": bad, "kind": "human"})).await; + assert_eq!(st, 400, "{bad:?}"); + } + // other stored free text + assert_eq!(s.post("/v1/bots", None, json!({"name": "ok", "owner": "o\u{0}wner"})).await.0, 400); + assert_eq!(s.post("/v1/bots", None, json!({"name": "ok", "owner": "x".repeat(129)})).await.0, 400); + assert_eq!(s.post("/v1/bots", None, json!({"name": "ok", "owner": "alice@example.com"})).await.0, 201); + // ordinary Unicode is fine, and the length is counted in characters + for good in ["José Müller", "李小龍", "Zoë 🂡♠", "Ünïcödé-bot_1.0", "🤖", &"é".repeat(64), &"🤖".repeat(64)] { + let (st, v) = s.post("/v1/bots", None, json!({"name": good})).await; + assert_eq!(st, 201, "{good:?}: {v}"); + assert_eq!(v["name"], json!(good)); + } + for bad in ["", " ", &"é".repeat(65), &"a".repeat(65)] { + assert_eq!(s.post("/v1/bots", None, json!({"name": bad})).await.0, 400, "{bad:?}"); + } + // seeds are stored text too + let (_, tok) = s.register("seeder").await; + let (st, _) = s.post("/v1/matches", Some("admin"), json!({"participants": house(), "hands_planned": 6, "seed": "a\u{0}b"})).await; + assert_eq!(st, 400); + let _ = tok; +} + +// ---------------------------------------------------------------------------------------------- 8: paging and closed tables + +#[tokio::test] +async fn hands_page_is_capped_at_500_and_zero_is_rejected() { + let s = srv().await; + let (st, m) = s + .post("/v1/matches", Some("admin"), json!({"participants": house(), "hands_planned": 606, "aivat": "off", "table_config": {"decision_time_ms": 1000}})) + .await; + assert_eq!(st, 201, "{m}"); + let id = m["match_id"].as_str().unwrap().to_string(); + assert_eq!(s.post(&format!("/v1/matches/{id}/start"), Some("admin"), json!({})).await.0, 200); + assert_eq!(s.wait_match(&id).await["status"], "finished"); + let n = |v: &Value| v.as_array().unwrap().len(); + let (st, h) = s.get(&format!("/v1/matches/{id}/hands"), Some("admin")).await; + assert_eq!((st, n(&h)), (200, 500), "default page is 500"); + let (_, h) = s.get(&format!("/v1/matches/{id}/hands?limit=100000"), Some("admin")).await; + assert_eq!(n(&h), 500, "limit is capped at 500"); + let (_, h) = s.get(&format!("/v1/matches/{id}/hands?limit=2"), Some("admin")).await; + assert_eq!(n(&h), 2); + let (_, h) = s.get(&format!("/v1/matches/{id}/hands?after_hand_no=500&limit=500"), Some("admin")).await; + assert_eq!(n(&h), 106, "paging continues after the cap"); + let (st, e) = s.get(&format!("/v1/matches/{id}/hands?limit=0"), Some("admin")).await; + assert_eq!((st, err_code(&e)), (400, "bad_request"), "{e}"); +} + +#[tokio::test] +async fn closing_a_closed_table_is_idempotent() { + let s = srv().await; + let (st, t) = s.post("/v1/tables", Some("admin"), json!({"decision_time_ms": 1000})).await; + assert_eq!(st, 201, "{t}"); + let id = t["table_id"].as_str().unwrap(); + for _ in 0..2 { + let (st, c) = s.req("DELETE", &format!("/v1/tables/{id}"), Some("admin"), None).await; + assert_eq!(st, 200, "{c}"); + assert_eq!(c["status"], "closed"); + } +} diff --git a/arena/server/tests/store.rs b/arena/server/tests/store.rs new file mode 100644 index 00000000..af244462 --- /dev/null +++ b/arena/server/tests/store.rs @@ -0,0 +1,149 @@ +//! `Store` contract tests, run against SQLite always and against Postgres when +//! `ARENA_TEST_DATABASE_URL=postgres://...` is set (each test uses its own fresh schema). + +use arena_server::model::*; +use arena_server::pgstore::PgStore; +use arena_server::store::{SqliteStore, Store}; + +fn backends(tag: &str) -> Vec<(&'static str, Box)> { + let mut v: Vec<(&'static str, Box)> = vec![("sqlite", Box::new(SqliteStore::open(":memory:").unwrap()))]; + if let Ok(url) = std::env::var("ARENA_TEST_DATABASE_URL") { + if !url.is_empty() { + v.push(("postgres", Box::new(PgStore::open(&url, Some(&schema(tag)), 2).unwrap()))); + } + } + v +} + +fn schema(tag: &str) -> String { + let t = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + format!("s_{tag}_{}_{}", std::process::id(), t % 1_000_000_007) +} + +fn player(id: &str, house: bool) -> PlayerRecord { + PlayerRecord { + player_id: id.into(), + name: format!("name-{id}"), + kind: "bot".into(), + owner: Some("o".into()), + created_at: "2026-01-01T00:00:00Z".into(), + house, + token_hash: format!("hash-{id}"), + webhook_url: Some("https://x/act".into()), + webhook_secret: Some("s".into()), + } +} + +fn run(id: &str, track: &str, pid: &str) -> RunRecord { + RunRecord { + run_id: id.into(), + track: track.into(), + panel_version: "1".into(), + panel: vec!["house:nit".into()], + player_id: pid.into(), + name: "n".into(), + match_id: format!("m-{id}"), + seed: "s".into(), + deals: None, + hands_planned: 600, + hands_done: 0, + status: "running".into(), + verified: false, + hosted: false, + mbb_per_game: None, + ci95_mbb: None, + method: None, + blueprint_fingerprint: None, + created_at: "2026-01-01T00:00:00Z".into(), + finished_at: None, + } +} + +#[test] +fn players_roundtrip_upsert_and_order() { + for (name, s) in backends("players") { + s.ping().unwrap(); + s.put_player(&player("p1", false)).unwrap(); + s.put_player(&player("p2", true)).unwrap(); + let mut p1 = player("p1", false); + p1.name = "renamed".into(); + p1.webhook_url = None; + s.put_player(&p1).unwrap(); + let g = s.get_player("p1").unwrap().unwrap(); + assert_eq!((g.name.as_str(), g.webhook_url.clone(), g.house), ("renamed", None, false), "{name}"); + assert!(s.get_player("p2").unwrap().unwrap().house, "{name}"); + assert!(s.get_player("nope").unwrap().is_none(), "{name}"); + assert_eq!(s.player_by_token_hash("hash-p2").unwrap().unwrap().player_id, "p2", "{name}"); + assert!(s.player_by_token_hash("").unwrap().is_none(), "{name}"); + let ids: Vec = s.list_players(10).unwrap().into_iter().map(|p| p.player_id).collect(); + assert_eq!(ids, ["p1", "p2"], "{name}: insertion order survives an upsert"); + assert_eq!(s.list_players(1).unwrap().len(), 1, "{name}"); + } +} + +#[test] +fn runs_filter_order_and_update_in_place() { + for (name, s) in backends("runs") { + s.put_run(&run("r1", "ladder-v1", "a")).unwrap(); + s.put_run(&run("r2", "ladder-v1", "b")).unwrap(); + s.put_run(&run("r3", "sharingan-1", "a")).unwrap(); + let mut r1 = run("r1", "ladder-v1", "a"); + r1.status = "finished".into(); + r1.verified = true; + r1.hosted = true; + r1.mbb_per_game = Some(12.5); + s.put_run(&r1).unwrap(); + let ids = |t: Option<&str>, p: Option<&str>| -> Vec { s.list_runs(t, p, 10).unwrap().into_iter().map(|r| r.run_id).collect() }; + assert_eq!(ids(None, None), ["r3", "r2", "r1"], "{name}: newest first, update keeps position"); + assert_eq!(ids(Some("ladder-v1"), None), ["r2", "r1"], "{name}"); + assert_eq!(ids(None, Some("a")), ["r3", "r1"], "{name}"); + assert_eq!(ids(Some("ladder-v1"), Some("a")), ["r1"], "{name}"); + assert_eq!(s.list_runs(None, None, 1).unwrap().len(), 1, "{name}"); + let g = s.get_run("r1").unwrap().unwrap(); + assert_eq!((g.status.as_str(), g.verified, g.hosted, g.mbb_per_game), ("finished", true, true, Some(12.5)), "{name}"); + assert!(s.get_run("zz").unwrap().is_none(), "{name}"); + } +} + +#[test] +fn results_replace_per_match() { + for (name, s) in backends("results") { + let row = |m: &str, p: &str, net: i64| StoredResult { + match_id: m.into(), + player_id: p.into(), + hands: 600, + deals: 100, + net_chips: net, + score_mbb: 1.25, + se_mbb: 0.5, + method: "aivat".into(), + }; + s.put_results("m1", &[row("m1", "a", 10), row("m1", "b", -10)]).unwrap(); + s.put_results("m2", &[row("m2", "a", 5)]).unwrap(); + s.put_results("m1", &[row("m1", "a", 99)]).unwrap(); // replaces m1 wholesale + let all = s.all_results().unwrap(); + assert_eq!(all.len(), 2, "{name}"); + let a = s.results_of_player("a").unwrap(); + assert_eq!(a.len(), 2, "{name}"); + assert!(a.iter().any(|r| r.match_id == "m1" && r.net_chips == 99 && r.hands == 600 && r.score_mbb == 1.25), "{name}"); + assert!(s.results_of_player("b").unwrap().is_empty(), "{name}"); + } +} + +#[test] +fn postgres_migrations_are_idempotent_and_schemas_are_isolated() { + let Ok(url) = std::env::var("ARENA_TEST_DATABASE_URL") else { return }; + let sch = schema("mig"); + let a = PgStore::open(&url, Some(&sch), 2).unwrap(); + a.put_player(&player("p1", false)).unwrap(); + // a second process starting against the same schema re-runs migrations harmlessly and sees the data + let b = PgStore::open(&url, Some(&sch), 2).unwrap(); + assert!(b.get_player("p1").unwrap().is_some()); + // another schema is empty + let c = PgStore::open(&url, Some(&schema("mig2")), 1).unwrap(); + assert!(c.get_player("p1").unwrap().is_none()); + // a bad schema name is refused (it is interpolated into SQL) + assert!(PgStore::open(&url, Some("x\"; drop table players; --"), 1).is_err()); + // an unreachable database is a clean error, not a hang or a panic + assert!(PgStore::open("postgres://arena@127.0.0.1:1/none?connect_timeout=2", None, 1).is_err()); +} diff --git a/arena/server/tests/worker.rs b/arena/server/tests/worker.rs new file mode 100644 index 00000000..e6b69dc7 --- /dev/null +++ b/arena/server/tests/worker.rs @@ -0,0 +1,763 @@ +//! Match worker (`sharingan-arena run`, pipe protocol) and the control-plane intake `POST /v1/results`. +//! +//! The worker plays the real ladder-v1 panel, which contains SHARINGAN-1, so these tests need a tiny +//! blueprint (`SHARINGAN_TEST_BLUEPRINT`, default `~/dev-serve/tinybp/tiny.plcp`, sizing `tiny`) and skip +//! without one, like tests/conformance.rs. Bots are the binary's own `pipe-house` subcommand plus tiny +//! shell/python scripts for the failure modes. + +use arena_server::config::ServerConfig; +use arena_server::worker::{run_worker, sign_result, verify_result, WorkerOpts, RESULT_SCHEMA}; +use futures_util::{SinkExt, StreamExt}; +use serde_json::{json, Value}; +use std::path::PathBuf; +use std::time::Duration; +use tokio_tungstenite::{connect_async, tungstenite::Message}; + +const BIN: &str = env!("CARGO_BIN_EXE_sharingan-arena"); + +fn blueprint() -> Option { + let p = std::env::var("SHARINGAN_TEST_BLUEPRINT") + .map(PathBuf::from) + .unwrap_or_else(|_| PathBuf::from(std::env::var("HOME").unwrap_or_default()).join("dev-serve/tinybp/tiny.plcp")); + p.exists().then_some(p) +} + +fn house_cfg(bp: PathBuf) -> ServerConfig { + ServerConfig { blueprint: Some(bp), sizing: "tiny".into(), ..Default::default() } +} + +fn opts(bp: &PathBuf, cmd: &str, hands: u32, lanes: usize) -> WorkerOpts { + WorkerOpts { bot_cmd: cmd.into(), hands, lanes, quiet: true, house_cfg: Some(house_cfg(bp.clone())), ..Default::default() } +} + +fn station() -> String { + format!("{BIN} pipe-house calling_station") +} + +fn tmp(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("shw-{}-{}", std::process::id(), name)); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +const HELLO: &str = r#"{"v":1,"type":"hello","data":{"protocol":1,"client":"test"}}"#; + +// ---------------------------------------------------------------------------------------------- protocol + +#[test] +fn protocol_conformance_hello_welcome_your_turn_hand_end_bye() { + let Some(bp) = blueprint() else { return eprintln!("skipped: no test blueprint") }; + let d = tmp("proto"); + let (inlog, outlog) = (d.join("in.log"), d.join("out.log")); + // tee records what the worker sends (stdin of the bot) and what the bot answers (its stdout) + let cmd = format!("tee -a {} | {} | tee -a {}", inlog.display(), station(), outlog.display()); + let r = run_worker(&opts(&bp, &cmd, 24, 1)).unwrap(); + assert_eq!(r["hands"], 24); + assert_eq!(r["forfeit_hands"], 0); + let ins: Vec = std::fs::read_to_string(&inlog).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + let outs: Vec = std::fs::read_to_string(&outlog).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + // handshake: bot speaks first (hello), worker answers welcome + assert_eq!(outs[0]["type"], "hello"); + assert_eq!(outs[0]["data"]["protocol"], 1); + assert_eq!(ins[0]["type"], "welcome"); + assert_eq!(ins[0]["v"], 1); + assert_eq!(ins[0]["data"]["protocol"], 1); + assert_eq!(ins[0]["data"]["mode"], "benchmark"); + assert_eq!(ins[0]["data"]["tables"], json!(["lane-0"])); + // benchmark mode: only your_turn + hand_end between welcome and bye + let kinds: std::collections::BTreeSet<&str> = ins.iter().map(|m| m["type"].as_str().unwrap()).collect(); + assert_eq!(kinds, ["bye", "hand_end", "welcome", "your_turn"].into_iter().collect()); + assert_eq!(ins.last().unwrap()["type"], "bye"); + // one session (process) per rotation: welcome ... bye, table_seq gap-free from 1 within each + let mut sessions = 0; + let mut next = 0u64; + for (i, m) in ins.iter().enumerate() { + if m["type"] == "welcome" { + sessions += 1; + next = 1; + } + assert_eq!(m["table_seq"], next, "table_seq at message {i}"); + next += 1; + } + assert_eq!(sessions, 6, "a fresh process for each of the 6 rotations"); + // your_turn carries the section 5.3 payload + let turns: Vec<&Value> = ins.iter().filter(|m| m["type"] == "your_turn").collect(); + assert!(turns.len() >= 24); + for t in &turns { + assert_eq!(t["table_id"], "lane-0"); + assert!(t["hand_id"].is_string() && t["seq"].is_u64() && t["t_ms"].is_u64()); + let d = &t["data"]; + for k in ["hand_id", "seq", "decision_id", "seat", "street", "hole_cards", "board", "history", "players", "button_seat", "small_blind", "big_blind", "pot", "pots", "legal", "deadline_ms", "time_bank_ms"] { + assert!(!d[k].is_null(), "your_turn.data.{k} missing"); + } + assert_eq!(d["hole_cards"].as_array().unwrap().len(), 2); + assert_eq!(d["players"].as_array().unwrap().len(), 6); + assert!(d["history"].as_array().unwrap().len() >= 2); // at least the blinds + } + // every decision is answered by exactly one act echoing the decision_id + let acts: Vec<&Value> = outs.iter().filter(|m| m["type"] == "act").collect(); + assert_eq!(acts.len(), turns.len()); + for (t, a) in turns.iter().zip(&acts) { + assert_eq!(a["data"]["decision_id"], t["data"]["decision_id"]); + assert_eq!(a["data"]["hand_id"], t["data"]["hand_id"]); + } + // hand_end: results sum to zero; other players' cards are redacted unless shown (reveal match_end) + let ends: Vec<&Value> = ins.iter().filter(|m| m["type"] == "hand_end").collect(); + assert_eq!(ends.len(), 24); + for e in &ends { + let d = &e["data"]; + let net: i64 = d["results"].as_array().unwrap().iter().map(|r| r["net"].as_i64().unwrap()).sum(); + assert_eq!(net, 0); + assert!(d["deck_reveal"].is_null()); + for seat in d["hole_cards"].as_object().unwrap().keys() { + assert!(d["showdown"].as_array().unwrap().iter().any(|s| s["seat"].to_string() == *seat && s["shown"] == true)); + } + } +} + +#[test] +fn noise_on_stdout_is_ignored_and_illegal_actions_are_retried_with_the_same_decision() { + let Some(bp) = blueprint() else { return eprintln!("skipped: no test blueprint") }; + if std::process::Command::new("python3").arg("-V").output().is_err() { + return eprintln!("skipped: no python3"); + } + let py = r#" +import sys, json +print("this is not json, a stray print()", flush=True) +print(json.dumps({"v":1,"type":"hello","data":{"protocol":1}}), flush=True) +tried = set() +errors = 0 +for line in sys.stdin: + m = json.loads(line) + t = m["type"] + if t == "error": + errors += 1 + elif t == "your_turn": + d = m["data"] + did = d["decision_id"] + if did not in tried: + tried.add(did) + print(json.dumps({"v":1,"type":"act","data":{"hand_id":d["hand_id"],"decision_id":did,"type":"raise","to":1}}), flush=True) + continue + l = d["legal"] + a = "check" if l["check"] else "call" + print(json.dumps({"v":1,"type":"act","data":{"hand_id":d["hand_id"],"decision_id":did,"type":a}}), flush=True) + elif t == "bye": + break +"#; + let d = tmp("illegal"); + let script = d.join("bot.py"); + std::fs::write(&script, py).unwrap(); + let r = run_worker(&opts(&bp, &format!("python3 {}", script.display()), 24, 1)).unwrap(); + let lane = &r["per_lane"][0]; + assert_eq!(r["hands"], 24); + assert_eq!(r["forfeit_hands"], 0, "{r}"); + assert_eq!(lane["timeouts"], 0, "{r}"); + assert_eq!(lane["noise_lines"], 6, "one noise line per process, one process per rotation"); + assert_eq!(lane["illegal_actions"], lane["decisions"], "every decision was first answered illegally once"); + // same score as the plain calling station: illegal answers change nothing + let base = run_worker(&opts(&bp, &station(), 24, 1)).unwrap(); + assert_eq!(r["mbb_per_game"], base["mbb_per_game"]); +} + +// ---------------------------------------------------------------------------------------------- failures + +#[test] +fn hung_bot_is_killed_folded_restarted_then_forfeits() { + let Some(bp) = blueprint() else { return eprintln!("skipped: no test blueprint") }; + // says hello, then never answers anything + let cmd = format!("echo '{HELLO}'; exec sleep 600"); + let mut o = opts(&bp, &cmd, 24, 1); + o.decision_timeout_ms = 150; + o.max_restarts = 1; + let t0 = std::time::Instant::now(); + let r = run_worker(&o).unwrap(); + assert!(t0.elapsed() < Duration::from_secs(20), "hang must not stall the worker"); + let lane = &r["per_lane"][0]; + assert_eq!(r["hands"], 24, "all planned hands are still played and scored"); + assert_eq!(lane["restarts"], 1); + assert_eq!(lane["timeouts"], 2); // first hang, then the restarted process hangs too + assert!(lane["crashed"].as_str().unwrap().contains("restarts"), "{lane}"); + assert_eq!(r["crashed_lanes"], 1); + let ff = r["forfeit_hands"].as_u64().unwrap(); + assert!(ff >= 22 && ff <= 24, "forfeit_hands {ff}"); + assert!(r["mbb_per_game"].as_f64().unwrap().is_finite()); +} + +#[test] +fn crash_at_start_forfeits_every_hand_without_restart() { + let Some(bp) = blueprint() else { return eprintln!("skipped: no test blueprint") }; + let cmd = format!("echo '{HELLO}'; read x; exit 3"); + let r = run_worker(&opts(&bp, &cmd, 144, 2)).unwrap(); // 24 deals = 2 blocks = 2 lanes + assert_eq!(r["hands"], 144); + assert_eq!(r["forfeit_hands"], 144); + assert_eq!(r["crashed_lanes"], 2); + assert_eq!(r["timeouts"], 0); + for l in r["per_lane"].as_array().unwrap() { + assert_eq!(l["restarts"], 0); + // whichever the worker notices first: the write to the dead bot's stdin or the EOF on its stdout + let why = l["crashed"].as_str().unwrap(); + assert!(why.contains("exited") || why.contains("closed its stdin"), "{l}"); + } + // a bot that cannot even start + let r = run_worker(&opts(&bp, "exit 1", 12, 1)).unwrap(); + assert_eq!(r["forfeit_hands"], 12); + assert!(r["per_lane"][0]["crashed"].as_str().unwrap().contains("start failed")); +} + +#[test] +fn crash_midway_forfeits_only_the_rest_of_that_lane() { + let Some(bp) = blueprint() else { return eprintln!("skipped: no test blueprint") }; + // the bot dies after 41 lines (hello + 40 acts, `sed -u 41q` forwards unbuffered) + let cmd = format!("{} | sed -u 41q", station()); + let r = run_worker(&opts(&bp, &cmd, 120, 1)).unwrap(); + assert_eq!(r["hands"], 120); + let ff = r["forfeit_hands"].as_u64().unwrap(); + assert!(ff > 40 && ff < 120, "forfeit_hands {ff}"); + assert_eq!(r["crashed_lanes"], 1); + // lane-scoped: with 2 lanes (24 deals = 2 blocks of 12) one crash leaves the other lane intact + let cmd = format!("{} | sed -u 41q", station()); + let r = run_worker(&opts(&bp, &cmd, 144, 2)).unwrap(); + assert_eq!(r["crashed_lanes"], 2); // each lane has its own process that dies the same way + assert!(r["forfeit_hands"].as_u64().unwrap() > 0); +} + +// ---------------------------------------------------------------------------------------------- determinism + +#[test] +fn same_seed_same_deals_and_results_whatever_the_lane_count() { + let Some(bp) = blueprint() else { return eprintln!("skipped: no test blueprint") }; + let d = tmp("det"); + let (f1, f2) = (d.join("h1.jsonl"), d.join("h4.jsonl")); + let mut a = opts(&bp, &station(), 360, 1); + a.hands_out = Some(f1.display().to_string()); + let mut b = opts(&bp, &station(), 360, 4); + b.hands_out = Some(f2.display().to_string()); + let (ra, rb) = (run_worker(&a).unwrap(), run_worker(&b).unwrap()); + assert_eq!(ra["deals_digest"], rb["deals_digest"]); + assert_eq!(ra["mbb_per_game"], rb["mbb_per_game"]); + assert_eq!(ra["ci95_mbb"], rb["ci95_mbb"]); + assert_eq!(std::fs::read_to_string(&f1).unwrap(), std::fs::read_to_string(&f2).unwrap(), "per-hand nets and decks identical"); + assert_eq!(ra["seed"], "bench:ladder-v1:v1"); + // another seed deals other cards + let mut c = opts(&bp, &station(), 360, 4); + c.seed = Some("another-seed".into()); + let rc = run_worker(&c).unwrap(); + assert_ne!(ra["deals_digest"], rc["deals_digest"]); + // each deal is played in all 6 rotations: the same deck 6 times + let lines: Vec = std::fs::read_to_string(&f1).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + let mut by_deal: std::collections::HashMap> = Default::default(); + for l in &lines { + by_deal.entry(l["deal_no"].as_u64().unwrap()).or_default().push(l); + } + assert_eq!(by_deal.len(), 60); + for (_, v) in by_deal { + assert_eq!(v.len(), 6); + assert!(v.iter().all(|x| x["deck_digest"] == v[0]["deck_digest"])); + let mut rots: Vec = v.iter().map(|x| x["rotation"].as_u64().unwrap()).collect(); + rots.sort(); + assert_eq!(rots, vec![0, 1, 2, 3, 4, 5]); + } +} + +// ---------------------------------------------------------------------------------------------- CLI + signing + +#[test] +fn cli_run_writes_a_signed_result_json() { + let Some(bp) = blueprint() else { return eprintln!("skipped: no test blueprint") }; + let d = tmp("cli"); + let (key, out) = (d.join("key"), d.join("result.json")); + std::fs::write(&key, "w1=cli-secret\n").unwrap(); + let st = std::process::Command::new(BIN) + .args(["run", "--bot", &station(), "--track", "sharingan-1", "--hands", "120", "--lanes", "2", "--quiet", "--player-id", "p_abc"]) + .arg("--out").arg(&out).arg("--sign-key-file").arg(&key) + .env("ARENA_BLUEPRINT", bp.display().to_string()) + .env("ARENA_SIZING", "tiny") + .status() + .unwrap(); + assert!(st.success()); + let r: Value = serde_json::from_str(&std::fs::read_to_string(&out).unwrap()).unwrap(); + assert_eq!(r["schema"], RESULT_SCHEMA); + assert_eq!(r["track"], "sharingan-1"); + assert_eq!(r["panel_version"], "1"); + assert_eq!(r["hands"], 120); + assert_eq!(r["lanes"], 2); + assert_eq!(r["player_id"], "p_abc"); + assert_eq!(r["seed"], "bench:sharingan-1:v1"); + assert_eq!(r["panel"], json!(vec!["house:sharingan-1"; 5])); + assert_eq!(r["bot"]["command_sha256"].as_str().unwrap().len(), 64); + assert!(r["mbb_per_game"].is_f64() && r["ci95_mbb"].is_f64() && r["method"] == "aivat"); + assert_eq!(r["per_lane"].as_array().unwrap().len(), 2); + assert!(r["timings"]["hands_per_sec"].as_f64().unwrap() > 0.0); + assert!(r["blueprint_fingerprint"].is_string()); + assert_eq!(r["signature"]["alg"], "HMAC-SHA256"); + let keys = vec![("w1".to_string(), "cli-secret".to_string())]; + assert_eq!(verify_result(&r, &keys), Ok("w1".to_string())); + let mut forged = r.clone(); + forged["mbb_per_game"] = json!(99999.0); + assert!(verify_result(&forged, &keys).is_err()); + assert!(verify_result(&r, &[("w1".to_string(), "other".to_string())]).is_err()); + // unsigned when no key is given + let out2 = d.join("r2.json"); + assert!(std::process::Command::new(BIN) + .args(["run", "--bot", &station(), "--hands", "12", "--quiet"]) + .arg("--out").arg(&out2) + .env("ARENA_BLUEPRINT", bp.display().to_string()) + .env("ARENA_SIZING", "tiny") + .status().unwrap().success()); + let r2: Value = serde_json::from_str(&std::fs::read_to_string(&out2).unwrap()).unwrap(); + assert!(r2.get("signature").is_none()); +} + +// ---------------------------------------------------------------------------------------------- POST /v1/results + +struct Srv { + base: String, + ws: String, + http: reqwest::Client, + _rs: arena_server::RunningServer, +} + +async fn server(bp: Option, keys: &str) -> Srv { + let cfg = ServerConfig { + bind: "127.0.0.1:0".into(), + db_path: ":memory:".into(), + admin_token: Some("admin".into()), + runner_token: Some("runner".into()), + worker_keys: arena_server::worker::parse_keys(keys), + blueprint: bp, + sizing: "tiny".into(), + rate_limit_rps: 0.0, + hand_delay_ms: 0, + min_leaderboard_hands: 6, + ..Default::default() + }; + let rs = arena_server::start(cfg).await.unwrap(); + Srv { base: format!("http://{}", rs.addr), ws: format!("ws://{}", rs.addr), http: reqwest::Client::new(), _rs: rs } +} + +impl Srv { + async fn call(&self, method: &str, path: &str, token: Option<&str>, body: Option) -> (u16, Value) { + let mut r = self.http.request(method.parse().unwrap(), format!("{}{}", self.base, path)); + if let Some(t) = token { + r = r.bearer_auth(t); + } + if let Some(b) = body { + r = r.json(&b); + } + let resp = r.send().await.unwrap(); + let st = resp.status().as_u16(); + let txt = resp.text().await.unwrap(); + (st, serde_json::from_str(&txt).unwrap_or(Value::String(txt))) + } +} + +fn err_code(v: &Value) -> &str { + v["error"]["code"].as_str().unwrap_or("") +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn post_results_accepts_signed_rejects_forged_and_the_leaderboard_picks_it_up() { + let Some(bp) = blueprint() else { return eprintln!("skipped: no test blueprint") }; + let s = server(Some(bp.clone()), "w1=top-secret,w2=second").await; + let (st, reg) = s.call("POST", "/v1/bots", None, Some(json!({"name": "evalbot", "kind": "bot"}))).await; + assert_eq!(st, 201, "{reg}"); + let (pid, ptoken) = (reg["player_id"].as_str().unwrap().to_string(), reg["token"].as_str().unwrap().to_string()); + + let o = opts(&bp, &station(), 120, 2); + let mut result = tokio::task::spawn_blocking(move || run_worker(&o).unwrap()).await.unwrap(); + result["player_id"] = json!(pid); + let mut signed = result.clone(); + sign_result(&mut signed, "w1", "top-secret"); + + // 401: no token / bad token; 403: a player token (even with a valid signature) + assert_eq!(s.call("POST", "/v1/results", None, Some(signed.clone())).await.0, 401); + assert_eq!(s.call("POST", "/v1/results", Some("nope"), Some(signed.clone())).await.0, 401); + assert_eq!(s.call("POST", "/v1/results", Some(&ptoken), Some(signed.clone())).await.0, 403); + // 401: unsigned, forged number, wrong key, unknown key id + let (st, e) = s.call("POST", "/v1/results", Some("runner"), Some(result.clone())).await; + assert_eq!((st, err_code(&e)), (401, "invalid_signature"), "{e}"); + let mut forged = signed.clone(); + forged["mbb_per_game"] = json!(5000.0); + assert_eq!(s.call("POST", "/v1/results", Some("runner"), Some(forged)).await.0, 401); + let mut badkey = result.clone(); + sign_result(&mut badkey, "w1", "guess"); + assert_eq!(s.call("POST", "/v1/results", Some("runner"), Some(badkey)).await.0, 401); + let mut unknown = result.clone(); + sign_result(&mut unknown, "w9", "top-secret"); + assert_eq!(s.call("POST", "/v1/results", Some("admin"), Some(unknown)).await.0, 401); + // nothing was stored by any of that + let (_, lb) = s.call("GET", "/v1/leaderboard?track=ladder-v1", None, None).await; + assert_eq!(lb["rows"].as_array().unwrap().len(), 0); + + // valid, from the runner token + let (st, run) = s.call("POST", "/v1/results", Some("runner"), Some(signed.clone())).await; + assert_eq!(st, 201, "{run}"); + assert_eq!(run["verified"], true); + assert_eq!(run["hosted"], true); + assert_eq!(run["status"], "finished"); + assert_eq!(run["track"], "ladder-v1"); + assert_eq!(run["player_id"], pid); + assert_eq!(run["mbb_per_game"], signed["mbb_per_game"]); + assert_eq!(run["key_id"], "w1"); + assert_eq!(run["deals"], "frozen"); // played on the track's public seed + let rid = run["run_id"].as_str().unwrap(); + // replay is refused + let (st, e) = s.call("POST", "/v1/results", Some("runner"), Some(signed.clone())).await; + assert_eq!((st, err_code(&e)), (409, "duplicate_result"), "{e}"); + // readable like any run + let (st, got) = s.call("GET", &format!("/v1/benchmarks/ladder-v1/runs/{rid}"), None, None).await; + assert_eq!(st, 200); + assert_eq!(got["verified"], true); + assert_eq!(got["hosted"], true); + // leaderboard + let (_, lb) = s.call("GET", "/v1/leaderboard?track=ladder-v1", None, None).await; + let row = &lb["rows"][0]; + assert_eq!(row["player_id"], pid); + assert_eq!(row["verified"], true); + assert_eq!(row["tracks"]["ladder-v1"]["verified"], true); + assert_eq!(row["vs_ladder_v1"]["mbb"], signed["mbb_per_game"]); + + // wrapper form with the player id outside the signed body; admin token; second key + let mut r2 = run_worker_clone(&bp).await; + sign_result(&mut r2, "w2", "second"); + let (st, run2) = s.call("POST", "/v1/results", Some("admin"), Some(json!({"result": r2, "player_id": pid}))).await; + assert_eq!(st, 201, "{run2}"); + assert_eq!(run2["key_id"], "w2"); + + // signed but not the frozen deals / panel / blueprint: refused with 400/409 even though the signature is valid + let resign = |mut v: Value| { + sign_result(&mut v, "w1", "top-secret"); + v + }; + let fresh = || async { run_worker_clone(&bp).await }; + let mut a = fresh().await; + a["player_id"] = json!(pid); + a["seed"] = json!("my-own-seed"); + assert_eq!(s.call("POST", "/v1/results", Some("runner"), Some(resign(a))).await.0, 400); + // a per-run seed must be run:<32..128 hex> + for bad_seed in ["run:abc", "run:", &format!("run:{}", "g".repeat(64)), &format!("run:{}", "a".repeat(129)), &format!("RUN:{}", "a".repeat(64)), &"a".repeat(64)] { + let mut a = fresh().await; + a["player_id"] = json!(pid); + a["seed"] = json!(bad_seed); + let (st, e) = s.call("POST", "/v1/results", Some("runner"), Some(resign(a))).await; + assert_eq!((st, err_code(&e)), (400, "bad_request"), "{bad_seed}: {e}"); + } + let mut a = fresh().await; + a["player_id"] = json!(pid); + a["panel"] = json!(vec!["house:random"; 5]); + assert_eq!(s.call("POST", "/v1/results", Some("runner"), Some(resign(a))).await.0, 400); + let mut a = fresh().await; + a["player_id"] = json!(pid); + a["blueprint_fingerprint"] = json!("deadbeefdeadbeef"); + let (st, e) = s.call("POST", "/v1/results", Some("runner"), Some(resign(a))).await; + assert_eq!((st, err_code(&e)), (409, "blueprint_mismatch"), "{e}"); + let mut a = fresh().await; + a["player_id"] = json!("p_does_not_exist"); + assert_eq!(s.call("POST", "/v1/results", Some("runner"), Some(resign(a))).await.0, 404); + let a = fresh().await; // no player_id anywhere + assert_eq!(s.call("POST", "/v1/results", Some("runner"), Some(resign(a))).await.0, 400); +} + +async fn run_worker_clone(bp: &PathBuf) -> Value { + let o = opts(bp, &station(), 120, 2); + tokio::task::spawn_blocking(move || run_worker(&o).unwrap()).await.unwrap() +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn post_results_without_configured_keys_refuses_everything() { + let Some(bp) = blueprint() else { return eprintln!("skipped: no test blueprint") }; + let s = server(Some(bp.clone()), "").await; + let mut r = run_worker_clone(&bp).await; + r["player_id"] = json!("house:random"); + sign_result(&mut r, "w1", "anything"); + let (st, e) = s.call("POST", "/v1/results", Some("admin"), Some(r)).await; + assert_eq!((st, err_code(&e)), (401, "invalid_signature"), "{e}"); +} + +// ---------------------------------------------------------------------------------------------- comparability with the server + +/// A remote WebSocket bot that checks/calls, as `house:calling_station` does. +async fn ws_station(url: String) { + let (ws, _) = connect_async(url).await.unwrap(); + let (mut w, mut r) = ws.split(); + w.send(Message::Text(json!({"v": 1, "type": "hello", "t_ms": 0, "data": {"client": "test"}}).to_string().into())).await.unwrap(); + while let Some(Ok(Message::Text(t))) = r.next().await { + let m: Value = serde_json::from_str(t.as_str()).unwrap(); + if m["type"] == "your_turn" { + let d = &m["data"]; + let kind = if d["legal"]["check"] == true { "check" } else { "call" }; + let act = json!({"v": 1, "type": "act", "table_id": m["table_id"], "t_ms": 0, + "data": {"hand_id": d["hand_id"], "decision_id": d["decision_id"], "type": kind}}); + if w.send(Message::Text(act.to_string().into())).await.is_err() { + break; + } + } + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn worker_results_are_comparable_with_server_runs_on_the_same_frozen_deals() { + let Some(bp) = blueprint() else { return eprintln!("skipped: no test blueprint") }; + let s = server(Some(bp.clone()), "w1=k").await; + let (_, reg) = s.call("POST", "/v1/bots", None, Some(json!({"name": "ws-station", "kind": "bot"}))).await; + let (pid, tok) = (reg["player_id"].as_str().unwrap().to_string(), reg["token"].as_str().unwrap().to_string()); + tokio::spawn(ws_station(format!("{}/v1/play?token={tok}", s.ws))); + for _ in 0..100 { + if s._rs.app.hub.connected(&pid) { + break; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + let (st, run) = s.call("POST", "/v1/benchmarks/ladder-v1/runs", Some(&tok), Some(json!({"hands": 360, "lanes": 2}))).await; + assert_eq!(st, 201, "{run}"); + let (rid, mid) = (run["run_id"].as_str().unwrap().to_string(), run["match_id"].as_str().unwrap().to_string()); + let mut done = Value::Null; + for _ in 0..600 { + let (_, r) = s.call("GET", &format!("/v1/benchmarks/ladder-v1/runs/{rid}"), None, None).await; + if r["status"] == "finished" { + done = r; + break; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + assert_eq!(done["status"], "finished", "server run did not finish"); + let (_, m) = s.call("GET", &format!("/v1/matches/{mid}"), None, None).await; + let me = m["standings"].as_array().unwrap().iter().find(|x| x["player_id"] == json!(pid)).unwrap().clone(); + let w = run_worker_clone_hands(&bp, 360).await; + // identical deals, identical panel randomness, identical bot => identical duplicate score and chips + assert_eq!(w["net_chips"], me["net_chips"], "worker {w} vs server {me}"); + let (a, b) = (w["duplicate_mbb_per_hand"].as_f64().unwrap(), me["duplicate_mbb_per_hand"].as_f64().unwrap()); + assert!((a - b).abs() < 1e-6, "{a} vs {b}"); + // AIVAT estimates agree up to the Monte-Carlo noise of the preflop equity sampler (hand ids differ) + let (x, y) = (w["mbb_per_game"].as_f64().unwrap(), done["mbb_per_game"].as_f64().unwrap()); + assert!((x - y).abs() < 0.25 * w["ci95_mbb"].as_f64().unwrap().max(50.0), "aivat {x} vs {y}"); +} + +async fn run_worker_clone_hands(bp: &PathBuf, hands: u32) -> Value { + let o = opts(bp, &station(), hands, 2); + tokio::task::spawn_blocking(move || run_worker(&o).unwrap()).await.unwrap() +} + +// ---------------------------------------------------------------------------------------------- secret per-run seeds + +fn hex64() -> String { + arena_server::util::random_hex() +} + +#[test] +fn seed_file_sets_fresh_deals_and_the_seed_never_reaches_the_bot() { + let Some(bp) = blueprint() else { return eprintln!("skipped: no test blueprint") }; + let d = tmp("seedfile"); + let seed = format!("run:{}", hex64()); + let (seedf, out, inlog, envlog) = (d.join("run.seed"), d.join("result.json"), d.join("in.log"), d.join("env.log")); + std::fs::write(&seedf, format!("{seed}\n")).unwrap(); // trailing newline is trimmed + // the bot records its environment and everything the worker sends it, then plays like a calling station + let cmd = format!("env > {}; tee {} | {}", envlog.display(), inlog.display(), station()); + let run = |extra: &[&str], out: &PathBuf| { + std::process::Command::new(BIN) + .args(["run", "--bot", &cmd, "--hands", "72", "--lanes", "2", "--quiet", "--seed", "decoy-seed-that-loses"]) + .args(extra) + .arg("--out").arg(out) + .env("ARENA_BLUEPRINT", bp.display().to_string()) + .env("ARENA_SIZING", "tiny") + .output() + .unwrap() + }; + // --seed-file takes precedence over --seed + let o = run(&["--seed-file", &seedf.display().to_string()], &out); + assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr)); + let r: Value = serde_json::from_str(&std::fs::read_to_string(&out).unwrap()).unwrap(); + assert_eq!(r["seed"], json!(seed)); + assert_eq!(r["hands"], 72); + assert_eq!(r["forfeit_hands"], 0); + // not the frozen deals: another deck digest than the track seed's + let base = run_worker(&opts(&bp, &station(), 72, 2)).unwrap(); + assert_ne!(r["deals_digest"], base["deals_digest"]); + // ... but reproducible from the same seed (the control plane can audit a finished run) + let mut again = opts(&bp, &station(), 72, 1); + again.seed = Some(seed.clone()); + assert_eq!(run_worker(&again).unwrap()["deals_digest"], r["deals_digest"]); + // the seed is nowhere the bot can see: not in its environment, not in a single message of the pipe protocol + // (hand_id, decision_id, table_id, welcome ...), and no hand_id encodes the (hashed) prefix of the track seed either + let hexpart = seed.strip_prefix("run:").unwrap(); + for (what, text) in [("env", std::fs::read_to_string(&envlog).unwrap()), ("pipe", std::fs::read_to_string(&inlog).unwrap())] { + assert!(!text.contains(hexpart), "the seed leaked into the bot's {what}"); + assert!(!text.contains("decoy-seed"), "the --seed value leaked into the bot's {what}"); + } + let first: Value = serde_json::from_str(std::fs::read_to_string(&inlog).unwrap().lines().find(|l| l.contains("your_turn")).unwrap()).unwrap(); + assert!(first["hand_id"].as_str().unwrap().starts_with("run-"), "{first}"); + assert!(!first["hand_id"].as_str().unwrap().contains("bench:"), "{first}"); + // the frozen deals keep their documented hand ids + let frozen_log = d.join("frozen.log"); + let cmd2 = format!("tee {} | {}", frozen_log.display(), station()); + run_worker(&opts(&bp, &cmd2, 12, 1)).unwrap(); + let t: Value = serde_json::from_str(std::fs::read_to_string(&frozen_log).unwrap().lines().find(|l| l.contains("your_turn")).unwrap()).unwrap(); + assert!(t["hand_id"].as_str().unwrap().starts_with("bench:ladder-v1:v1-h"), "{t}"); +} + +#[test] +fn seed_file_errors_are_reported_and_nothing_runs() { + let d = tmp("seederr"); + let args = |f: &PathBuf| { + std::process::Command::new(BIN) + .args(["run", "--bot", "true", "--hands", "6", "--quiet", "--seed", "ignored"]) + .arg("--seed-file").arg(f) + .output() + .unwrap() + }; + let missing = args(&d.join("nope")); + assert_eq!(missing.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&missing.stderr).contains("cannot read seed file"), "{}", String::from_utf8_lossy(&missing.stderr)); + std::fs::write(d.join("empty"), " \n\t\n").unwrap(); + let empty = args(&d.join("empty")); + assert_eq!(empty.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&empty.stderr).contains("empty"), "{}", String::from_utf8_lossy(&empty.stderr)); + // the unreadable file is not silently replaced by --seed + assert!(!String::from_utf8_lossy(&missing.stdout).contains("ignored")); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn post_results_accepts_a_fresh_per_run_seed_and_records_it() { + let Some(bp) = blueprint() else { return eprintln!("skipped: no test blueprint") }; + let s = server(Some(bp.clone()), "w1=top-secret").await; + let (_, reg) = s.call("POST", "/v1/bots", None, Some(json!({"name": "fresh", "kind": "bot"}))).await; + let pid = reg["player_id"].as_str().unwrap().to_string(); + let seed = format!("run:{}", hex64()); + let mut o = opts(&bp, &station(), 120, 2); + o.seed = Some(seed.clone()); + let mut r = tokio::task::spawn_blocking(move || run_worker(&o).unwrap()).await.unwrap(); + r["player_id"] = json!(pid); + sign_result(&mut r, "w1", "top-secret"); + let (st, run) = s.call("POST", "/v1/results", Some("runner"), Some(r.clone())).await; + assert_eq!(st, 201, "{run}"); + assert_eq!((run["seed"].as_str(), run["deals"].as_str()), (Some(seed.as_str()), Some("fresh")), "{run}"); + assert_eq!((run["verified"].clone(), run["hosted"].clone()), (json!(true), json!(true))); + let rid = run["run_id"].as_str().unwrap(); + let (_, got) = s.call("GET", &format!("/v1/benchmarks/ladder-v1/runs/{rid}"), None, None).await; + assert_eq!(got["deals"], "fresh"); + // the signature still binds the seed: swapping it for another valid run: seed is refused + let mut swapped = r.clone(); + swapped["seed"] = json!(format!("run:{}", hex64())); + swapped["run_id"] = json!("w_other_run_1"); + let (st, e) = s.call("POST", "/v1/results", Some("runner"), Some(swapped)).await; + assert_eq!((st, err_code(&e)), (401, "invalid_signature"), "{e}"); +} + +// ---------------------------------------------------------------------------------------------- slow and noisy bots never hang a run + +#[test] +fn a_bot_that_answers_after_the_deadline_is_folded_restarted_then_forfeits_and_the_run_ends() { + let Some(bp) = blueprint() else { return eprintln!("skipped: no test blueprint") }; + if std::process::Command::new("python3").arg("-V").output().is_err() { + return eprintln!("skipped: no python3"); + } + // sleeps longer than the decision timeout before every answer (`def act(s): time.sleep(8); return Action.check()`) + let py = r#" +import sys, json, time +print(json.dumps({"v":1,"type":"hello","data":{"protocol":1}}), flush=True) +for line in sys.stdin: + m = json.loads(line) + if m["type"] == "your_turn": + d = m["data"] + time.sleep(8) + print(json.dumps({"v":1,"type":"act","data":{"hand_id":d["hand_id"],"decision_id":d["decision_id"],"type":"check"}}), flush=True) + elif m["type"] == "bye": + break +"#; + let d = tmp("slow"); + let script = d.join("slow.py"); + std::fs::write(&script, py).unwrap(); + let mut o = opts(&bp, &format!("python3 {}", script.display()), 144, 2); + o.decision_timeout_ms = 300; + o.max_restarts = 3; + let t0 = std::time::Instant::now(); + let r = within(Duration::from_secs(60), move || run_worker(&o).unwrap()); + assert!(t0.elapsed() < Duration::from_secs(30), "took {:?}", t0.elapsed()); + assert_eq!(r["hands"], 144, "every planned hand is still played and scored"); + for l in r["per_lane"].as_array().unwrap() { + assert_eq!(l["restarts"], 3, "{l}"); + assert_eq!(l["timeouts"], 4, "3 restarts, then the 4th late decision forfeits: {l}"); + assert!(l["crashed"].as_str().unwrap().contains("restarts"), "{l}"); + } + assert_eq!(r["crashed_lanes"], 2); + assert!(r["forfeit_hands"].as_u64().unwrap() >= 130); + assert!(r["mbb_per_game"].as_f64().unwrap().is_finite()); +} + +/// Run `f` on a thread; fail the test (instead of hanging it) when it takes longer than `limit`. +fn within(limit: Duration, f: impl FnOnce() -> T + Send + 'static) -> T { + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let _ = tx.send(f()); + }); + rx.recv_timeout(limit).unwrap_or_else(|_| panic!("the worker did not finish within {limit:?}: a misbehaving bot hung the run")) +} + +#[test] +fn a_bot_that_floods_stdout_cannot_starve_the_decision_deadline() { + let Some(bp) = blueprint() else { return eprintln!("skipped: no test blueprint") }; + // hello, then endless noise lines and never an act: the pipe is never empty, so a reader that only checks the + // deadline when `read` would block waits forever + let cmd = format!("echo '{HELLO}'; exec yes 'this is not json'"); + let mut o = opts(&bp, &cmd, 24, 1); + o.decision_timeout_ms = 200; + o.max_restarts = 1; + let r = within(Duration::from_secs(60), move || run_worker(&o).unwrap()); + let lane = &r["per_lane"][0]; + assert_eq!(r["hands"], 24); + assert_eq!(lane["timeouts"], 2, "{lane}"); + assert_eq!(lane["restarts"], 1, "{lane}"); + assert!(lane["noise_lines"].as_u64().unwrap() > 1000, "{lane}"); + // and a bot that floods an unterminated line (no newline at all) is cut off too (here by the 4 MiB line cap, or the deadline) + let cmd = format!("echo '{HELLO}'; yes x | tr -d '\\n'"); + let mut o = opts(&bp, &cmd, 12, 1); + o.decision_timeout_ms = 200; + o.max_restarts = 0; + let r = within(Duration::from_secs(60), move || run_worker(&o).unwrap()); + assert_eq!(r["hands"], 12); + assert_eq!(r["forfeit_hands"], 12, "{r}"); + assert_eq!(r["crashed_lanes"], 1); +} + +// ---------------------------------------------------------------------------------------------- duplicate deals never leak + +#[test] +fn a_bot_process_never_meets_a_deal_it_already_saw_from_another_seat() { + let Some(bp) = blueprint() else { return eprintln!("skipped: no test blueprint") }; + if std::process::Command::new("python3").arg("-V").output().is_err() { + return eprintln!("skipped: no python3"); + } + // a bot with a memory: logs (its pid, every hand_id it is asked about) + let py = r#" +import sys, json, os +log = open(sys.argv[1], "a") +print(json.dumps({"v":1,"type":"hello","data":{"protocol":1}}), flush=True) +for line in sys.stdin: + m = json.loads(line) + if m["type"] == "your_turn": + d = m["data"] + log.write("%d %s\n" % (os.getpid(), d["hand_id"])); log.flush() + t = "check" if d["legal"].get("check") else "call" + print(json.dumps({"v":1,"type":"act","data":{"hand_id":d["hand_id"],"decision_id":d["decision_id"],"type":t}}), flush=True) + elif m["type"] == "bye": + break +"#; + let d = tmp("memory"); + let (script, log) = (d.join("memory.py"), d.join("seen.log")); + std::fs::write(&script, py).unwrap(); + let r = run_worker(&opts(&bp, &format!("python3 {} {}", script.display(), log.display()), 144, 2)).unwrap(); + assert_eq!(r["hands"], 144); + let mut seen: std::collections::HashMap<(String, u32), u32> = std::collections::HashMap::new(); + let mut pids = std::collections::HashSet::new(); + for line in std::fs::read_to_string(&log).unwrap().lines() { + let (pid, hand_id) = line.split_once(' ').unwrap(); + let hand_no: u32 = hand_id.rsplit("-h").next().unwrap().parse().unwrap(); + let (deal, _) = arena_server::matches::locate(true, 144, 12, hand_no); + pids.insert(pid.to_string()); + let first = *seen.entry((pid.to_string(), deal.unwrap())).or_insert(hand_no); + assert_eq!(first, hand_no, "process {pid} met deal {deal:?} twice (hands {first} and {hand_no})"); + } + assert!(pids.len() >= 12, "a fresh process per lane and rotation: {} processes", pids.len()); +} diff --git a/data/README.md b/data/README.md new file mode 100644 index 00000000..e2c7d146 --- /dev/null +++ b/data/README.md @@ -0,0 +1,27 @@ +# data/ + +Large data is **not** stored in git (see `.gitignore`). + +## data/buckets-200/ (required to run any blueprint) + +The 200-bucket card abstraction: `flop.u16` (~2.5 MB), `turn.u16` (~27 MB), `river.u16` (~235 MB), `meta.txt` (`buckets 200 200 200`); about 264 MB in total. +The same archive is also published with [SHARINGAN-2](https://huggingface.co/markokraemer/sharingan-2). +SHARINGAN-1/C@2e10 and final SHARINGAN-2/C@1.83e11 both require these tables and +the `medium` sizing menu. Their model-card descriptions do not change the weights +or bucket files; verify the published part and full-model checksum manifests. + +Download `buckets-200.tar` from the Hugging Face repository [`markokraemer/sharingan-1`](https://huggingface.co/markokraemer/sharingan-1) and extract it here, or rebuild it +(about 30 s on 128 cores, minutes on a laptop; same seed, same tables): + +```bash +cargo run --release -p abstraction --bin build_buckets -- data/buckets-200 200 200 200 200000 +``` + +## data/pokerbench/ (optional, for `arena/referee`) + +The PokerBench CSVs (~88 MB) are used by the `referee` crate to measure per-spot accuracy. PokerBench is published by its authors on Hugging Face +(`RZ412/PokerBench`, Apache-2.0 according to its dataset card). It is not redistributed in this repository; download the four `*_game_scenario_information.csv` files from there. + +## data/run-*/ and data/probe-*/ + +Training runs and probe outputs are written here and are git-ignored. diff --git a/deploy/local/bots/tag_bot.py b/deploy/local/bots/tag_bot.py new file mode 100644 index 00000000..2c30f2a8 --- /dev/null +++ b/deploy/local/bots/tag_bot.py @@ -0,0 +1,7 @@ +"""The bot the local e2e submits: the Python SDK's built-in tight-aggressive example bot, as an uploadable single file. + +Runs unchanged over every transport: `sharingan pipe` (hosted match worker), `sharingan connect` (WebSocket), `sharingan eval`. +""" +from sharingan.bots import TightAggressive + +bot = TightAggressive() diff --git a/deploy/local/compose.yml b/deploy/local/compose.yml new file mode 100644 index 00000000..9b69cd3b --- /dev/null +++ b/deploy/local/compose.yml @@ -0,0 +1,125 @@ +# The hosted Sharingan stack on one machine, with no Platinum and no Stripe account: +# +# postgres arena + runner databases +# arena the table server (REST + WS), Postgres store, hosted attestation + signed worker results enabled +# runner credit ledger + Stripe webhook + job API; runs each job in a LOCAL container ("sandbox") through the host's +# container engine socket, on the arena's network (SANDBOX_BACKEND=local) +# +# Use deploy/local/e2e.sh (builds the images, writes the .env, runs a full job and asserts the result). By hand: +# podman build ... (see e2e.sh), then: docker-compose -f deploy/local/compose.yml --env-file -p sharingan-e2e up -d +# Works with docker-compose v2 against podman's compat socket (DOCKER_HOST=unix://$XDG_RUNTIME_DIR/podman/podman.sock), +# docker compose, or podman-compose. +# +# Networks +# core postgres, arena, runner (published ports are bound to 127.0.0.1 only) +# botnet `internal: true` (no route out): the arena and, in connect mode, the sandboxes. Worker-mode sandboxes join NO network. +# egress a normal network, joined by a sandbox only while `pip install` runs +name: ${COMPOSE_PROJECT_NAME:-sharingan-local} + +services: + postgres: + image: docker.io/library/postgres:16-alpine + environment: + POSTGRES_USER: sharingan + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-sharingan-local-pw} + volumes: + - pgdata:/var/lib/postgresql/data + - ./initdb:/docker-entrypoint-initdb.d:ro + healthcheck: + test: ["CMD-SHELL", "pg_isready -U sharingan -d runner"] + interval: 2s + timeout: 3s + retries: 30 + networks: [core] + + arena: + image: ${ARENA_IMAGE:-localhost/sharingan-arena:local} + build: + context: ../.. + dockerfile: deploy/platinum/docker/Dockerfile + target: arena + pull_policy: never + depends_on: + postgres: { condition: service_healthy } + environment: + ARENA_DATABASE_URL: postgres://sharingan:${POSTGRES_PASSWORD:-sharingan-local-pw}@postgres:5432/arena?sslmode=disable + ARENA_ADMIN_TOKEN: ${ARENA_ADMIN_TOKEN:-local-admin-token} + ARENA_RUNNER_TOKEN: ${ARENA_RUNNER_TOKEN:-local-runner-token} + ARENA_WORKER_KEYS: ${WORKER_KEY_ID:-runner1}=${WORKER_SIGN_KEY:-local-worker-signing-key} + ARENA_OPEN_REGISTRATION: "true" + # Optional blueprint: BLUEPRINT_DIR holds BLUEPRINT_FILE (+ buckets-200/); unset = house bots only (no ladder-v1 / sharingan-1) + BLUEPRINT_FILE: ${BLUEPRINT_FILE:-sharingan-1.plcp} + SIZING: ${SIZING:-medium} + volumes: + - ${BLUEPRINT_DIR:-./empty-models}:/models:ro + ports: + - 127.0.0.1:${ARENA_PORT:-18080}:8080 + healthcheck: + test: ["CMD", "curl", "-fsS", "http://127.0.0.1:8080/readyz"] + interval: 2s + timeout: 3s + retries: 40 + networks: + core: {} + botnet: {} + + runner: + image: ${RUNNER_IMAGE:-localhost/sharingan-runner:local} + build: + context: ../.. + dockerfile: deploy/platinum/docker/Dockerfile.runner + pull_policy: never + # Root inside the container = the invoking user on the host (rootless podman), which is what owns the engine socket. + user: "0:0" + depends_on: + postgres: { condition: service_healthy } + arena: { condition: service_healthy } + environment: + SANDBOX_BACKEND: local + PORT: "8090" + RUNNER_DATABASE_URL: postgres://sharingan:${POSTGRES_PASSWORD:-sharingan-local-pw}@postgres:5432/runner + RUNNER_AUTH_TOKEN: ${RUNNER_AUTH_TOKEN:-local-service-token} + ARENA_URL: http://arena:8080 + ARENA_RUNNER_TOKEN: ${ARENA_RUNNER_TOKEN:-local-runner-token} + STRIPE_WEBHOOK_SECRET: ${STRIPE_WEBHOOK_SECRET:-whsec_local_fake_signing_secret} + # STRIPE_SECRET_KEY deliberately unset: checkout sessions are simulated, nothing talks to Stripe + PUBLIC_BASE_URL: http://127.0.0.1:${RUNNER_PORT:-18090} + PRICE_USD_PER_1K_HANDS: ${PRICE_USD_PER_1K_HANDS:-0.05} + DEFAULT_JOB_MODE: ${DEFAULT_JOB_MODE:-worker} + POLL_INTERVAL_MS: ${POLL_INTERVAL_MS:-500} + BOT_CPU: ${BOT_CPU:-2} + BOT_RAM_MB: ${BOT_RAM_MB:-2048} + # local sandboxes + CONTAINER_HOST: unix:///var/run/engine.sock + LOCAL_BOT_IMAGE: ${BOT_IMAGE:-localhost/sharingan-bot:local} + LOCAL_BOT_NETWORK: ${BOTNET_NAME:-sharingan-botnet} + LOCAL_EGRESS_NETWORK: ${EGRESS_NAME:-sharingan-egress} + LOCAL_SANDBOX_BINDS: ${SANDBOX_BINDS:-} + # match worker + WORKER_KEY_ID: ${WORKER_KEY_ID:-runner1} + WORKER_SIGN_KEY: ${WORKER_SIGN_KEY:-local-worker-signing-key} + WORKER_ENV_JSON: ${WORKER_ENV_JSON:-} + volumes: + - ${CONTAINER_SOCKET:-/run/user/1000/podman/podman.sock}:/var/run/engine.sock + security_opt: + - label=disable + ports: + - 127.0.0.1:${RUNNER_PORT:-18090}:8090 + healthcheck: + test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:8090/readyz').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"] + interval: 2s + timeout: 3s + retries: 40 + # the runner is trusted and also attaches `egress` so that the network exists for sandboxes' pip window + networks: [core, egress] + +networks: + core: {} + botnet: + name: ${BOTNET_NAME:-sharingan-botnet} + internal: true + egress: + name: ${EGRESS_NAME:-sharingan-egress} + +volumes: + pgdata: {} diff --git a/deploy/local/e2e.sh b/deploy/local/e2e.sh new file mode 100755 index 00000000..da1d0832 --- /dev/null +++ b/deploy/local/e2e.sh @@ -0,0 +1,261 @@ +#!/usr/bin/env bash +# End to end, locally, with no Platinum and no Stripe account: +# +# build images -> compose up (postgres + arena + runner) -> top up credits with a SIMULATED, SIGNED Stripe webhook -> +# submit the SDK's example bot for a 2,000-hand ladder-v1 run -> wait -> assert: +# * the run completed and the result is verified:true +# * credits were debited by the hands played (and nothing is left reserved) +# * the sandbox container was torn down +# +# Usage: deploy/local/e2e.sh +# Env: E2E_MODE=worker|connect worker = match worker in the sandbox, signed result POSTed to /v1/results (default) +# connect = `sharingan connect` over WebSocket + hosted:true run +# E2E_HANDS=2000 hands for the run +# E2E_BUILD=1|0 build the images first (default 1) +# E2E_KEEP=1 leave the stack running afterwards +# BLUEPRINT_SRC / BUCKETS_SRC / SIZING the blueprint the arena and the sandboxes load +# (default: the tiny test blueprint on the dev box, sizing tiny) +# E2E_NICE="nice -n 19" prefix for the image builds; E2E_CPUSET=0-15 taskset the builds; CARGO_BUILD_JOBS=16 +# Needs: podman (rootless is fine) or docker, a compose (docker-compose v2 / docker compose / podman-compose), curl, openssl, python3. +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +HERE="$ROOT/deploy/local" +STATE="${E2E_DIR:-$ROOT/data/local-e2e}" +PROJECT="${E2E_PROJECT:-sharingan-e2e}" +MODE="${E2E_MODE:-worker}" +HANDS="${E2E_HANDS:-2000}" +TRACK=ladder-v1 +BLUEPRINT_SRC="${BLUEPRINT_SRC:-/home/ubuntu/dev-serve/tinybp/tiny.plcp}" +BUCKETS_SRC="${BUCKETS_SRC:-/home/ubuntu/pluribus/data/buckets-200}" +SIZING="${SIZING:-tiny}" +ARENA_PORT="${ARENA_PORT:-18080}" +RUNNER_PORT="${RUNNER_PORT:-18090}" +NICE="${E2E_NICE-nice -n 19}" +CARGO_BUILD_JOBS="${CARGO_BUILD_JOBS:-16}" +mkdir -p "$STATE" + +say() { printf '\n\033[1m== %s\033[0m\n' "$*"; } +note() { printf ' %s\n' "$*"; } +PASS=0; FAIL=0 +check() { # check "description" "actual" "expected" + if [ "$2" = "$3" ]; then PASS=$((PASS+1)); printf ' PASS %-62s %s\n' "$1" "$2" + else FAIL=$((FAIL+1)); printf ' FAIL %-62s got %s, want %s\n' "$1" "$2" "$3"; fi +} +jget() { python3 -c 'import json,sys +d=json.load(sys.stdin) +for k in sys.argv[1].split("."): + d=d[int(k)] if isinstance(d,list) else d.get(k) if isinstance(d,dict) else None +print("null" if d is None else ("true" if d is True else "false" if d is False else d))' "$1"; } + +# ---------------------------------------------------------------- container engine + compose +if command -v podman >/dev/null 2>&1; then ENGINE=podman; else ENGINE=docker; fi +if [ "$ENGINE" = podman ]; then + export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}" + SOCK="${CONTAINER_SOCKET:-$XDG_RUNTIME_DIR/podman/podman.sock}" +else + SOCK="${CONTAINER_SOCKET:-/var/run/docker.sock}" +fi +SVC_PID="" +if [ "$ENGINE" = podman ] && [ ! -S "$SOCK" ]; then + systemctl --user start podman.socket 2>/dev/null || true + if [ ! -S "$SOCK" ]; then + mkdir -p "$(dirname "$SOCK")" + podman system service --time=0 "unix://$SOCK" >"$STATE/podman-service.log" 2>&1 & + SVC_PID=$! + for _ in $(seq 1 30); do [ -S "$SOCK" ] && break; sleep 0.2; done + fi +fi +[ -S "$SOCK" ] || { echo "no container engine socket at $SOCK"; exit 2; } +export DOCKER_HOST="unix://$SOCK" + +if command -v docker-compose >/dev/null 2>&1; then COMPOSE=(docker-compose) +elif [ -x /usr/libexec/docker/cli-plugins/docker-compose ]; then COMPOSE=(/usr/libexec/docker/cli-plugins/docker-compose) +elif docker compose version >/dev/null 2>&1; then COMPOSE=(docker compose) +elif command -v podman-compose >/dev/null 2>&1; then COMPOSE=(podman-compose) +else echo "no compose found (docker-compose v2, docker compose or podman-compose)"; exit 2; fi +echo "engine: $ENGINE ($(${ENGINE} --version)) compose: ${COMPOSE[*]} socket: $SOCK mode: $MODE" + +# ---------------------------------------------------------------- blueprint (staged copy; read-only mount) +MODELS="$STATE/models" +BP_FILE="$(basename "$BLUEPRINT_SRC")" +if [ -f "$BLUEPRINT_SRC" ] && [ -d "$BUCKETS_SRC" ]; then + mkdir -p "$MODELS" + [ -f "$MODELS/$BP_FILE" ] || $NICE cp "$BLUEPRINT_SRC" "$MODELS/$BP_FILE" + [ -d "$MODELS/buckets-200" ] || $NICE cp -r "$BUCKETS_SRC" "$MODELS/buckets-200" +else + echo "blueprint not found ($BLUEPRINT_SRC / $BUCKETS_SRC): ladder-v1 cannot run"; exit 2 +fi + +# ---------------------------------------------------------------- images +ARENA_IMAGE=localhost/sharingan-arena:local; RUNNER_IMAGE=localhost/sharingan-runner:local; BOT_IMAGE=localhost/sharingan-bot:local +if [ "${E2E_BUILD:-1}" = 1 ]; then + say "building images (nice, ${E2E_CPUSET:+taskset $E2E_CPUSET, }CARGO_BUILD_JOBS=$CARGO_BUILD_JOBS)" + PRE="$NICE ${E2E_CPUSET:+taskset -c $E2E_CPUSET}" + # shellcheck disable=SC2086 + $PRE $ENGINE build -q -f "$ROOT/deploy/platinum/docker/Dockerfile" --target arena --build-arg "CARGO_BUILD_JOBS=$CARGO_BUILD_JOBS" -t "$ARENA_IMAGE" "$ROOT" >/dev/null + # shellcheck disable=SC2086 + $PRE $ENGINE build -q -f "$ROOT/deploy/platinum/docker/Dockerfile.bot" --build-arg "ARENA_IMAGE=$ARENA_IMAGE" -t "$BOT_IMAGE" "$ROOT" >/dev/null + # shellcheck disable=SC2086 + $PRE $ENGINE build -q -f "$ROOT/deploy/platinum/docker/Dockerfile.runner" -t "$RUNNER_IMAGE" "$ROOT" >/dev/null +fi +$ENGINE image exists "$ARENA_IMAGE" 2>/dev/null || $ENGINE image inspect "$ARENA_IMAGE" >/dev/null + +# ---------------------------------------------------------------- stack +rnd() { openssl rand -hex 16; } +RUNNER_AUTH_TOKEN="$(rnd)"; WEBHOOK_SECRET="whsec_e2e_$(rnd)" +cat >"$STATE/e2e.env" </dev/null 2>&1 || true; done + dc down -v --remove-orphans >/dev/null 2>&1 || true + else + note "E2E_KEEP=1: stack left running (project $PROJECT, runner :$RUNNER_PORT, arena :$ARENA_PORT)" + fi + [ -n "$SVC_PID" ] && kill "$SVC_PID" 2>/dev/null || true + exit $rc +} +trap cleanup EXIT + +say "compose up" +dc down -v --remove-orphans >/dev/null 2>&1 || true +dc up -d --no-build 2>&1 | tail -n 12 +ARENA="http://127.0.0.1:$ARENA_PORT"; RUNNER="http://127.0.0.1:$RUNNER_PORT" +for i in $(seq 1 90); do + if curl -fsS -m 2 "$ARENA/readyz" >/dev/null 2>&1 && curl -fsS -m 2 "$RUNNER/readyz" >/dev/null 2>&1; then break; fi + [ "$i" = 90 ] && { dc logs --tail 40; echo "stack did not become ready"; exit 1; } + sleep 1 +done +note "arena $ARENA runner $RUNNER" +api() { curl -sS -m 60 -H "authorization: Bearer $RUNNER_AUTH_TOKEN" -H 'content-type: application/json' "$@"; } +check "ladder-v1 is available on the arena (blueprint loaded)" "$(curl -sS "$ARENA/v1/benchmarks" | python3 -c 'import json,sys;print([t["available"] for t in json.load(sys.stdin) if t["track"]=="ladder-v1"][0])')" "True" + +# ---------------------------------------------------------------- credits +USER_ID="user_e2e_$(openssl rand -hex 3)" +say "credits for $USER_ID" +check "balance starts at 0" "$(api "$RUNNER/v1/credits/$USER_ID" | jget balance_micro)" "0" + +mkdir -p "$STATE" +tar czf "$STATE/bot.tgz" -C "$HERE/bots" tag_bot.py +python3 - "$STATE/bot.tgz" "$STATE/submit.json" "$USER_ID" "$HANDS" "$MODE" <<'PY' +import base64, json, sys +tgz, out, user, hands, mode = sys.argv[1:6] +json.dump({"userId": user, "botName": "tag-bot", "language": "python", "entry": "tag_bot.py", "track": "ladder-v1", + "hands": int(hands), "lanes": 4, "mode": mode, "idempotencyKey": f"e2e-{user}", + "artifactTgzBase64": base64.b64encode(open(tgz, "rb").read()).decode()}, open(out, "w")) +PY +CODE=$(api -o "$STATE/resp.json" -w '%{http_code}' -X POST --data-binary @"$STATE/submit.json" "$RUNNER/v1/jobs") +check "submit with no credits is refused (HTTP 402 insufficient_credits)" "$CODE $(jget error.code < "$STATE/resp.json")" "402 insufficient_credits" + +stripe_event() { # signed checkout.session.completed for $USER_ID: stripe_event [secret] + local body ts sig + body=$(printf '{"id":"%s","type":"checkout.session.completed","data":{"object":{"id":"%s","object":"checkout.session","payment_status":"paid","currency":"usd","amount_total":%s,"client_reference_id":"%s","metadata":{"kind":"sharingan_credits","user_id":"%s"}}}}' "$1" "$2" "$3" "$USER_ID" "$USER_ID") + ts=$(date +%s) + sig=$(printf '%s.%s' "$ts" "$body" | openssl dgst -sha256 -hmac "${4:-$WEBHOOK_SECRET}" -hex | awk '{print $NF}') + curl -sS -m 20 -o "$STATE/resp.json" -w '%{http_code}' -X POST -H "stripe-signature: t=$ts,v1=$sig" -H 'content-type: application/json' --data-binary "$body" "$RUNNER/v1/webhooks/stripe" +} +SESSION=$(api -X POST -d "{\"userId\":\"$USER_ID\",\"amountUsd\":10}" "$RUNNER/v1/credits/checkout") +SESSION_ID=$(printf '%s' "$SESSION" | jget id) +check "checkout session is simulated (no Stripe call)" "$(printf '%s' "$SESSION" | jget simulated)" "true" +check "webhook with a WRONG secret is rejected (400)" "$(stripe_event evt_bad "$SESSION_ID" 1000 whsec_wrong)" "400" +check "balance still 0 after the rejected webhook" "$(api "$RUNNER/v1/credits/$USER_ID" | jget balance_micro)" "0" +check "signed webhook credits \$10 (HTTP 200)" "$(stripe_event evt_e2e_1 "$SESSION_ID" 1000) $(jget outcome < "$STATE/resp.json")" "200 credited" +check "replayed webhook is a no-op (duplicate)" "$(stripe_event evt_e2e_1 "$SESSION_ID" 1000) $(jget outcome < "$STATE/resp.json")" "200 duplicate" +check "balance is \$10.00 = 10000000 micro-USD" "$(api "$RUNNER/v1/credits/$USER_ID" | jget balance_micro)" "10000000" + +# ---------------------------------------------------------------- the job +say "submit: $HANDS hands of $TRACK, mode=$MODE, bot=deploy/local/bots/tag_bot.py" +CODE=$(api -o "$STATE/resp.json" -w '%{http_code}' -X POST --data-binary @"$STATE/submit.json" "$RUNNER/v1/jobs") +JOB=$(jget id < "$STATE/resp.json"); JOB_IDS="$JOB" +check "submit accepted (HTTP 202)" "$CODE" "202" +note "job $JOB reserved_micro=$(jget reserved_micro < "$STATE/resp.json")" +T0=$(date +%s); LAST="" +while :; do + api "$RUNNER/v1/jobs/$JOB" >"$STATE/job.json" + ST=$(jget status < "$STATE/job.json"); SETTLED=$(jget settled < "$STATE/job.json") + LINE="$ST $(jget hands_done < "$STATE/job.json")/$(jget hands_total < "$STATE/job.json") hands" + [ "$LINE" != "$LAST" ] && note "[$(( $(date +%s) - T0 ))s] $LINE" && LAST="$LINE" + case "$ST" in finished|failed|aborted) [ "$SETTLED" = true ] && break ;; esac + [ $(( $(date +%s) - T0 )) -gt "${E2E_TIMEOUT_S:-600}" ] && { echo "timed out"; cat "$STATE/job.json"; exit 1; } + sleep 1 +done + +say "assertions" +J="$STATE/job.json" +if [ "$(jget status < "$J")" != finished ]; then echo "job did not finish: $(jget error < "$J") [$(jget error_class < "$J")]"; jget bot_log_tail < "$J" | tail -n 15; fi +HANDS_DONE=$(jget hands_done < "$J"); CHARGE=$(jget charge_micro < "$J"); RUN_ID=$(jget run_id < "$J") +EXPECT_HANDS=$(( (HANDS + 5) / 6 * 6 )) +check "run completed: job status" "$(jget status < "$J")" "finished" +check "result verified:true (job)" "$(jget verified < "$J")" "true" +check "hands played = $HANDS rounded to whole deals" "$HANDS_DONE" "$EXPECT_HANDS" +check "AIVAT score present (mbb_per_game is a number)" "$(jget mbb_per_game < "$J" | python3 -c 'import sys;v=sys.stdin.read().strip();print("number" if v not in ("null","") and float(v)==float(v) else v)')" "number" +RUN="$(curl -sS "$ARENA/v1/benchmarks/$TRACK/runs/$RUN_ID")" +check "arena agrees: run status / verified / hosted" "$(printf '%s' "$RUN" | jget status) $(printf '%s' "$RUN" | jget verified) $(printf '%s' "$RUN" | jget hosted)" "finished true true" +check "arena agrees: hands" "$(printf '%s' "$RUN" | jget hands_done)" "$EXPECT_HANDS" +check "credits debited by hands played (50 micro-USD/hand at \$0.05/1k)" "$CHARGE" "$(( HANDS_DONE * 50 ))" +C="$(api "$RUNNER/v1/credits/$USER_ID")" +check "balance = 10000000 - charge, nothing left reserved" "$(printf '%s' "$C" | jget balance_micro) $(printf '%s' "$C" | jget reserved_micro)" "$(( 10000000 - CHARGE )) 0" +check "ledger kinds: topup, reserve, settle" "$(api "$RUNNER/v1/credits/$USER_ID/entries" | python3 -c 'import json,sys;print(",".join(e["kind"] for e in reversed(json.load(sys.stdin)["entries"]) if e["kind"]!="release"))')" "topup,reserve,settle" +check "job reports the sandbox deleted" "$(jget sandbox_deleted < "$J")" "true" +LEFT="$($ENGINE ps -a --filter label=sharingan.sandbox=1 --filter "name=run-$JOB" --format '{{.Names}}' | tr -d '\n')" +check "no sandbox container of this job is left" "${LEFT:-none}" "none" +CODE=$(api -o "$STATE/resp.json" -w '%{http_code}' -X POST --data-binary @"$STATE/submit.json" "$RUNNER/v1/jobs") +check "resubmitting the same idempotency key is deduped (200, same job)" "$CODE $(jget id < "$STATE/resp.json") $(jget deduped < "$STATE/resp.json")" "200 $JOB true" +check "... and does not charge again" "$(api "$RUNNER/v1/credits/$USER_ID" | jget balance_micro)" "$(( 10000000 - CHARGE ))" +note "score: $(jget mbb_per_game < "$J") +- $(jget ci95_mbb < "$J") mbb/game, sandbox $(jget sandbox_seconds < "$J")s, our cost $(jget cogs_micro < "$J") micro-USD vs charge $CHARGE" + +# ---------------------------------------------------------------- a broken bot: free, not on the leaderboard, still torn down +if [ "$MODE" = worker ]; then + say "a bot that cannot even import is not charged and not recorded" + printf 'def act(:\n' >"$STATE/broken_bot.py" + tar czf "$STATE/broken.tgz" -C "$STATE" broken_bot.py + python3 - "$STATE/broken.tgz" "$STATE/submit2.json" "$USER_ID" <<'PY' +import base64, json, sys +tgz, out, user = sys.argv[1:4] +json.dump({"userId": user, "botName": "broken", "language": "python", "entry": "broken_bot.py", "track": "ladder-v1", "hands": 600, "lanes": 2, + "idempotencyKey": f"e2e-broken-{user}", "artifactTgzBase64": base64.b64encode(open(tgz, "rb").read()).decode()}, open(out, "w")) +PY + RUNS_BEFORE=$(curl -sS "$ARENA/v1/benchmarks/$TRACK/runs?limit=1000" | python3 -c 'import json,sys;print(len(json.load(sys.stdin)))') + api -o "$STATE/resp.json" -X POST --data-binary @"$STATE/submit2.json" "$RUNNER/v1/jobs" + JOB2=$(jget id < "$STATE/resp.json"); JOB_IDS="$JOB_IDS $JOB2" + for _ in $(seq 1 120); do + api "$RUNNER/v1/jobs/$JOB2" >"$STATE/job2.json" + [ "$(jget settled < "$STATE/job2.json")" = true ] && break + sleep 1 + done + J2="$STATE/job2.json" + check "broken bot: job failed, blamed on the bot" "$(jget status < "$J2") $(jget error_class < "$J2")" "failed bot" + check "broken bot: the user sees why (bot_log_tail has the SyntaxError)" "$(jget bot_log_tail < "$J2" | grep -c SyntaxError | sed 's/^[1-9].*/yes/')" "yes" + check "broken bot: charge 0, whole hold released" "$(jget charge_micro < "$J2") $(jget released_micro < "$J2")" "0 30000" + check "broken bot: balance unchanged" "$(api "$RUNNER/v1/credits/$USER_ID" | jget balance_micro)" "$(( 10000000 - CHARGE ))" + check "broken bot: nothing posted to the leaderboard" "$(curl -sS "$ARENA/v1/benchmarks/$TRACK/runs?limit=1000" | python3 -c 'import json,sys;print(len(json.load(sys.stdin)))')" "$RUNS_BEFORE" + check "broken bot: sandbox torn down" "$(jget sandbox_deleted < "$J2") $($ENGINE ps -a --filter "name=run-$JOB2" --format '{{.Names}}' | tr -d '\n')" "true " +fi + +say "$PASS passed, $FAIL failed" +[ "$FAIL" = 0 ] diff --git a/deploy/local/empty-models/.gitkeep b/deploy/local/empty-models/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/deploy/local/initdb/01-databases.sql b/deploy/local/initdb/01-databases.sql new file mode 100644 index 00000000..255a6a07 --- /dev/null +++ b/deploy/local/initdb/01-databases.sql @@ -0,0 +1,3 @@ +-- One Postgres, two databases: the arena's tables and the runner's (credit ledger + jobs) never share a schema. +CREATE DATABASE arena; +CREATE DATABASE runner; diff --git a/deploy/platinum/DESIGN.md b/deploy/platinum/DESIGN.md new file mode 100644 index 00000000..f34e2730 --- /dev/null +++ b/deploy/platinum/DESIGN.md @@ -0,0 +1,132 @@ +# Poker Sharingan on Platinum + +Status: the images, the runner (credit ledger, Stripe webhook, job API, `PlatinumClient`) and the local stack are built and tested end to end without Platinum or Stripe credentials: see [README.md](README.md). This document is the hosting design and the Platinum gap analysis; where it still says "skeleton" or "untested" the README's tables are authoritative. **Architecture change since this was written:** an eval job's sandbox runs the *match worker* (`sharingan-arena run --bot "sharingan pipe bot.py"`, signed `result.json`, `POST /v1/results`), not a WebSocket bot; the WebSocket path survives as `mode:"connect"`. Repo paths marked `PT:` are in `~/Projects/kortix/platinum` (read only). + +## 0. The three facts that shape everything + +1. **The arena loads the blueprint itself.** `arena/server/src/house.rs:41-47` opens `ARENA_BLUEPRINT` with `CompactPolicy::open` (mmap) and serves it as `house:sharingan-1`. Both benchmark tracks (`ladder-v1`, `sharingan-1`) need it, and the 4,800 hands/s hosted path only works in-process. So the arena and the ~140 GB blueprint belong on the same machine. `sharingan-serve` (stateless `/v1/act`, with turn/river search) is a separate product; running it in the same VM lets both share one page cache (two sandboxes never share guest page cache). That is what the `core` image target is for. +2. **Platinum cannot host a 140 GB mmapped file today.** Hard caps: RAM 32 GiB per sandbox (`PT:apps/api/src/api/sandboxes.ts:473`, config clamp `PT:apps/api/src/config.ts:813`), disk 100 GB (`sandboxes.ts:475`, `templates.ts:787,876,1005,1113,1199`, `config.ts:814`), volume 100 GiB (`PT:docs/volumes.md` Limits), template size 20 GiB default (`config.ts:805`). See G1/G2. +3. **Platinum has no custom domains and no private sandbox-to-sandbox network** (`PT:apps/api/src/tlsAsk.ts`, `PT:apps/api/src/sandboxProxy.ts:105-122`, `PT:infra/03-network.sh:64-66`). `arena.sharingan.poker` needs a front door we own, and bots reach the arena over its public URL. See G3/G4. + +``` + player -> sharingan.poker (Cloudflare, existing wrangler site) + -> Stripe Checkout -> our billing service (credit ledger) + | POST /jobs (credits reserved first) + v + runner service --Platinum SDK--> Platinum org "sharingan-bots" + | one ephemeral microVM per run + | (template sharingan-bot, egress = arena only) + | arena REST | wss://arena.sharingan.poker/v1/play + v v + arena.sharingan.poker --Cloudflare Worker--> Platinum org "sharingan-core" + app/sandbox "core": sharingan-arena :8080 + sharingan-serve :8081 + bigmem pool host, 256+ GB RAM, blueprint on local disk, SQLite or Postgres +``` + +Two Platinum orgs on purpose: at balance <= 0 Platinum auto-stops running sandboxes after a 60 minute grace (`PT:docs/billing.md` Zero balance). Bot spend must not be able to stop the arena. + +## 1. Mapping + +### (a) Arena server (`ghcr.io//sharingan-arena`, `docker/Dockerfile --target arena`) + +- **Shape: a Platinum App** (`/v1/apps`, `PT:apps/api/src/api/apps.ts`), source `{kind:"image"}` pinned tag, `port: 8080`, `health_path: "/healthz"` (arena route `arena/server/src/api.rs:27`). The app gives a stable URL `.apps.`, env/secret injection (`runtime_env`, secrets encrypted at rest), blue-green rollout (`PT:apps/rollout.ts` `deploy()`), rollback (`POST /v1/apps/:id/rollback`), and a GitHub push webhook if we use `{kind:"git"}` (Dockerfile in repo; `handleGitPush` in `apps.ts`, GitHub App connection `apps/github.ts`). WebSockets pass through the app/preview proxy (`sandboxProxy.ts` WS path). +- **Do not use the app path for the stateful production arena until G5 is fixed.** The rollout boots a fresh VM from the template on every deploy (`rollout.ts:128-148`, no `volumes` in `createBody`), so SQLite on the rootfs is lost on each release. Until then run the arena as a plain persistent sandbox: `sandboxes.create({template, type:"persistent", expose:[{port:8080, public:true}], env, backup_interval_min: 15})`, upgrade by snapshot + replace by hand. +- **Persistence.** `ARENA_DB=/data/arena.db`. Two honest options: + - SQLite on the sandbox disk (persistent sandbox, `auto_stop_minutes:0`, `auto_archive_days:0`), plus a 5 minute `sqlite3 .backup` to S3. Fine for launch traffic. + - SQLite on a Platinum volume: not recommended. A mount is a private working copy committed about every 5 s or on `fsync` (`PT:docs/volumes.md` Commit and pull); SQLite fsyncs every transaction and a second VM (rollout overlap) would fork the file. + - **Move to Postgres** when any of: more than one arena instance, blue-green deploys needed, or hand-history volume past ~50 GB. `store.rs` already has the `Store` trait; the Postgres impl is the work (about 1-2 days). Use a managed Postgres (not on Platinum). +- **Config:** `ARENA_BIND=0.0.0.0:8080` (default is loopback, already set in the image), `ARENA_ADMIN_TOKEN` from a Platinum secret/env, `ARENA_ENABLE_WEBHOOKS=false`, `ARENA_OPEN_REGISTRATION=true` behind Cloudflare rate limits (the arena has none; README Known gaps). +- **Without blueprint** (`USE_BLUEPRINT=0`) this fits Platinum today (4 vCPU, 8 GB): `ladder-v1` and `sharingan-1` return 400, but plain duplicate matches against the other house bots work. That is Phase 1. + +### (b) SHARINGAN-1 inference (needs big memory) + +- Target `core` (arena + serve in one VM, entrypoint `docker/entrypoint.sh`): 32+ vCPU (search threads 16, concurrency 2, plus arena), RAM >= 256 GB (140 GB page cache plus working set), disk >= 400 GB local NVMe. The blueprint is pulled once from S3 (`ASSETS_S3_URI`, bucket `pluribus-repro-2026` or a copy) and `cat`-warmed. Image carries no weights. +- **What Platinum needs (G1, G2):** raise the RAM and disk ceilings, enrol one large host into a dedicated pool. Pools already exist and are exactly the right fence (`PT:apps/api/src/hostPools.ts`: a non-`general` pool is only used by creates that name it; `sandboxes.create({pool:"bigmem", pool_fallback:"none"})`; host joins via bootstrap token body `{"pool":"bigmem"}`, `PT:DEPLOY.md` "Dedicated host pool"). Hosts are bare metal with `/dev/kvm`; pick one with >= 384 GB RAM and 2+ TB NVMe. +- Also set `backup_interval_min: 0` (the hourly rootfs backup would tar 140 GB) and `auto_archive_days: 0` for this sandbox; the weights are re-fetchable from S3. +- **Interim (no Platinum change):** run `core` outside Platinum on one rented big-RAM Linux box with `docker run` (same image, same env), reachable at `arena.sharingan.poker` through the same Cloudflare Worker/DNS. Everything else (runner, bot sandboxes, billing) is on Platinum and only sees a URL. When G1/G2 land, move the container into a bigmem Platinum host (even the same machine: install it as a Platinum host via `PT:DEPLOY.md` host installer) with zero client changes. A weaker interim: Phase 1 arena without blueprint. + +### (c) Eval runner (uploaded bots) + +`runner/` (TypeScript, `@platinum-dev/sdk`; the SDK is TS/Python only, and the arena runner is a Node service). One job = one sandbox = one benchmark run. +**Current flow (worker mode, see README.md):** the sandbox gets no network at all; it runs `sharingan-arena run` which plays the whole duplicate benchmark in-process (thousands of hands/s) with the user's bot as a `setpriv`-dropped stdin/stdout subprocess, signs `result.json` with an HMAC key (root-only file), and the runner POSTs it to `/v1/results`. Steps 4-6 below describe the original WebSocket design, kept as `mode:"connect"`: + +1. Template `sharingan-bot` (`docker/Dockerfile.bot`, `templates/sharingan-bot.json`): python 3.12 + `sdk/python` + node 22 + `poker-sharingan` + two launchers. Built once by `runner/src/provision.ts` (`Template.fromImage(...).build()`, `PT:docs/templates.md`). +2. Per run: `sandboxes.create({template, type:"ephemeral", cpu:1, ram_mb:1024, network:{allowOut:[arenaHost], denyOut:[all]}, metadata:{sharingan_job}}, {waitForRunning:true})`. Cold boot about 98 ms, warm claim about 14 ms (`PT:README.md` Performance). Egress is locked to the arena host (hostname rules read TLS SNI; `PT:docs/networking.md`). The doc says the egress policy is not a hard boundary (source-IP spoofing), but the arena is public anyway and the bot only holds a throwaway token. +3. Artifact (tar.gz, <= 8 MiB; `files.write` truncates above 16 MiB, SDK README) written with `files.write`, unpacked with `sh`. Python `requirements.txt`: PyPI added to the allowlist, `pip install`, then `updateNetwork` drops it. +4. Bot started with `sbx.process.start({cmd:[setpriv ... python3 launch_bot.py], env:{ARENA_TOKEN,...}, timeoutMs})`. It connects **out** over `wss://.../v1/play`. We do not use `sharingan play` (creates its own table vs house bots) or `sharingan serve` (webhook mode: needs `ARENA_ENABLE_WEBHOOKS`, a public URL per sandbox, an extra proxy hop per decision). `bot/launch_bot.py` is a thin wrapper over `sharingan connect` (python SDK); `launch_bot.mjs` is the TypeScript equivalent. +5. Runner retries `POST /v1/benchmarks/{track}/runs` (with the bot's own token) until the arena stops answering `409 not_connected`, polls `GET .../runs/{id}` (or listens for the `benchmark_progress` WS event) until `finished`, then `usage()` and `delete()` in a `finally`. +6. **Why not fork from a snapshot.** `sandbox.fork()/clone()` cold-boots from a disk copy (about 3.5 s) and reserves the parent's full shape (`PT:docs/snapshots.md`); a template create is faster and simpler. Use snapshot+clone only for the repeat-run case where a bot has heavy installed deps: build once per bot version (`snapshot()` after `pip install`), `clone({snapshotId})` per run. Not implemented. +7. **Leak protection.** Process-level `timeoutMs` (guest-side kill), runner wall-clock deadline plus arena abort, `auto_stop_minutes:30`, and `reapOrphans()` every 5 minutes (lists running sandboxes by `metadata.sharingan_job`). G9 is the real fix. +8. **Throughput.** A trivial Python bot does about 550 hands/s with `lanes:4` (TABLE_API 12b item 12); 20,000 hands is under a minute plus decision latency. The sandbox shape is the Python bot's limit, so offer `cpu` 1/2 as a price tier. +9. **Trust.** The arena flags remote bots `verified:false` (`benchmarks.rs:159`, `verified: rec.house`). A bot run in our sandbox is not "house", so it stays unverified. Arena change (small, not done): let an admin-authenticated run request carry `hosted:true` (admin token held only by the runner) to set `verified`. Also register bots with `owner = userId` (already a field on `POST /v1/bots`, `api.rs` `RegisterReq.owner`). +10. **Cost metering.** See (d). + +### (d) Credits and billing: two separate money flows + +- **Players -> us (our Stripe account).** Stripe Checkout sells credit packs; webhook `checkout.session.completed` credits an append-only ledger (per user, integer micro-USD, idempotent on the Stripe event id). Before `POST /jobs` the billing service **reserves** `reserveUsd(hands)` (`runner/src/cost.ts`); after the job settles it charges `chargeUsd` and releases the rest, idempotent on `idempotencyKey`. Failed runs caused by us (provisioning, arena down) are refunded in full; a bot crash or timeout is charged for time used. Prepaid credits, no Stripe metering. The README's "buy credits, run evals" fits this. +- **Platinum -> us.** Platinum is prepaid per org (`PT:docs/billing.md`): vCPU-seconds + GiB-seconds sampled every 60 s, storage per GiB-hour, requests metered. Fund the two orgs with Platinum's own checkout/auto-top-up (`PT:apps/api/src/autoTopup.ts`) on our card, set `PUT /v1/billing/limits` (`usage_limit_usd` as circuit breaker, `usage_alert_usd` with the `org.usage_alert` webhook, `PT:docs/webhooks.md`) on the bots org. +- **Per-run cost.** `GET /v1/sandboxes/:id/usage` (SDK `sbx.usage()`, `PT:packages/sdk-ts/src/index.ts:1872`) returns uptime and cost but 404s once the sandbox is deleted (`PT:apps/api/src/api/sandboxes.ts:5640-5643`) and lags up to a 60 s cycle. So the runner reads it before delete and also meters wall-clock x shape x our rates itself, and bills `max(local, platinum)` times `MARKUP`. The fixed arena/bigmem host is recovered per hand (`USD_PER_HAND_ARENA_SHARE`), not per second. Reconcile monthly against `GET /v1/billing/usage?group=sandbox` (needs a `*` key; the runner key is scoped `sandboxes:write`, `PT:docs/api-keys.md`). + +### (e) Platinum calls per step + +| Step | Call | Where | +|---|---|---| +| Build templates | `Template.fromImage(img).build(client,{name,default_cpu,default_ram_mb,default_disk_gb,entrypoint})` -> `POST /v1/templates/from-image` | `PT:packages/sdk-ts/src/template.ts`, `PT:apps/api/src/api/templates.ts:866` | +| Pre-stage for fast first boot | `POST /v1/templates/:id/prepare`, `/materialize` (no typed method: `client.request`) | `PT:docs/templates.md` | +| Deploy arena as app | `client.request("POST","/v1/apps",{slug,source:{kind:"image",image},port:8080,health_path:"/healthz",runtime_env,cpu,ram_mb,region},{wait_for_state:"live"})`; redeploy `POST /v1/apps/:id/deploy`, rollback `/rollback`, logs `/logs` | `PT:apps/api/src/api/apps.ts:257,478,522,546` (no SDK wrapper; flag `flags.apps_enabled` default off, `config.ts:668`) | +| Deploy core as sandbox | `sandboxes.create({template,pool:"bigmem",pool_fallback:"none",cpu,ram_mb,disk_gb,expose:[{port:8080,public:true},{port:8081}],env,backup_interval_min:0,auto_archive_days:0,type:"persistent"},{waitForRunning:true})` | `PT:packages/sdk-ts/src/index.ts:76-170` (`SandboxSpec`) | +| Public URL | `sbx.exposedUrl(8080)` -> `https://8080-.sbx.`; app: `https://.apps.` | `PT:docs/networking.md`, `apps.ts` `appUrl()` | +| Secrets/env | `env`, app `runtime_env {secret:true}`, org secrets with egress injection (not for inbound tokens) | `PT:docs/secrets.md`, `apps.ts` `encEnv` | +| Run sandbox | `sandboxes.create({template:"sharingan-bot-...", type:"ephemeral", network, metadata})` | SDK `SandboxSpec` | +| Upload bot | `sbx.files.write(path, bytes)` (<= 16 MiB), `sbx.sh(...)` | SDK `files`, `sh` | +| Run bot | `sbx.process.start({cmd,cwd,env,timeoutMs})`, `proc.logs()`, `proc.kill()` | `PT:packages/sdk-ts/src/process.ts` | +| Tighten egress | `sbx.updateNetwork({allowOut,denyOut})` | SDK index.ts:1807 | +| Meter | `sbx.usage()` | index.ts:1872 | +| Tear down | `sbx.delete()` | index.ts:1571 | +| Orphan sweep | `sandboxes.iterate({state:"running"})` + `metadata` | index.ts:1186 | +| Spend breaker | `PUT /v1/billing/limits {usage_limit_usd,usage_alert_usd}` | `PT:docs/billing.md` | +| Lifecycle events (optional) | webhooks `sandbox.state_updated`, `org.usage_alert` | `PT:docs/webhooks.md` | + +## 2. Gaps in Platinum, with the minimal fix + +| # | Gap (evidence) | Blocks | Minimal change | +|---|---|---|---| +| G1 | RAM per sandbox capped at 32 GiB: zod `max(32768)` at `sandboxes.ts:473` (and `:151,:6756`), config `limits.org_max_ram_mb max:32768` (`config.ts:813`), tier table `config.ts:891-900`. Reference hosts are 60 GB (`PT:README.md`). | Production blueprint (b) | Raise the zod/config max to 524288; set `limits.org_overrides[org].maxRamMb` for the core org; enrol a >= 384 GB host with `pool:"bigmem"`; check `memoryAdmission.ts` and consider disabling KSM scanning on that host (KSM over 256 GB burns CPU). | +| G2 | Disk per sandbox and template default capped at 100 GB (`sandboxes.ts:475`, `templates.ts:787,876,1005,1113,1199`, `config.ts:814`); volume max 100 GiB (`docs/volumes.md`); template size cap 20 GiB default (`config.ts:805`, per-org overridable up to 512000 MB). | Production blueprint | Raise the same maxes to >= 1024 GB behind the per-org override; weights come from S3 on first boot, so no template size change is needed. Host needs >= 1 TB NVMe free. | +| G3 | No custom domains. Only `.apps.` (`sandboxProxy.ts:105-122`) and `-.sbx.`; Caddy on-demand TLS is gated by `tlsAsk.ts` which says yes only to those names. | `arena.sharingan.poker` | Add `app_domains(hostname, app_id, verified_at)`, DNS TXT verification, let `lookupAppRoute` match an exact host, and let `tlsAsk` answer yes for verified hostnames. Interim: Cloudflare Worker (`edge/arena-proxy-worker.ts`). | +| G4 | No private path sandbox <-> sandbox/app: bridge-to-bridge forward is dropped (`infra/03-network.sh:64-66`); guest IPs are per-host (`10.42/16`). Bot traffic therefore hairpins through the public edge and is metered as external requests. | Latency/cost of the hot path; "internal network" requirement | Unverified whether a per-sandbox `allowOut` to a peer's `internalIp` overrides the bridge drop (test first; I believe not). Fix: org-scoped peer allow-rule (`network.allow_peers:[{sandbox, port}]`) rendered into the per-sandbox nft chain ahead of the drop, same-host only; add `colocate_with` placement so bots land on the arena's host. Cross-host needs an overlay (larger). Public path works today. | +| G5 | Apps cannot be stateful: `bootVm` passes no `volumes`, `network` or `secrets` (`rollout.ts:128-148`) and always blue-greens onto a fresh VM. | Arena as an App with SQLite | Pass `volumes` through `CreateBody` -> `createBody`; add `strategy:"recreate"` (stop old before booting new) for stateful apps. Or use Postgres and ignore this. | +| G6 | Volumes are commit/pull working copies, not a shared POSIX FS (`docs/volumes.md`). No documented mmap/lock semantics. | SQLite or weights on a volume | Document it; recommend Postgres. No Platinum change needed. | +| G7 | Template images must be pulled from a registry; I found no registry credential field on `from-image` (`templates.ts:866`) and the apps image must be a pinned tag (`apps.ts` `isPinned`). Unverified. | Private images | Publish public GHCR images (code is Apache-2.0, weights are not in the image). If private is wanted: add `registry_auth` (secret ref) to `from-image`/apps source. | +| G8 | No SDK wrapper for apps or billing (`PT:packages/sdk-parity.json`, SDK README "Not wrapped yet"); apps are flag-gated and undocumented (`config.ts:668`; no `docs/apps.md`). | Convenience only | Use `client.request`; enable via `limits.org_overrides[org].apps`. Optionally add `client.apps.*` (thin). | +| G9 | No hard per-sandbox lifetime or budget: only idle auto-stop and day-granular archive/delete (`docs/sandboxes.md` Retention). A runner crash leaves a billing sandbox. | Safe untrusted-code billing | Add `max_runtime_seconds` to `CreateBody`; reconciler deletes past `created_at + ttl` (reuse the auto-delete sweep, `reconciler.ts` near `auto_delete_days`). Optional `max_cost_usd`. Interim: guest `timeoutMs`, runner deadline, reaper. | +| G10 | Per-run cost is awkward: `/usage` 404s after delete, 60 s sampling, no tag/metadata grouping, `/v1/billing/*` needs a full-access key. | Exact metering | Keep `/v1/sandboxes/:id/usage` readable for N days after delete with a `cost_usd` field; allow `GET /v1/billing/usage?group=metadata.sharingan_job` or a read-only `billing:read` scope. Interim: own meter (`cost.ts`). | +| G11 | One prepaid balance per org, no reseller/sub-tenant mode; zero balance stops running sandboxes after 60 min. | Isolation of arena from bot spend | None required: use two orgs, auto top-up, usage-limit breaker on the bots org. | +| G12 | Concurrency caps by tier: `inflight`, total cpu/ram (`config.ts:891-900`) and create rate limits (`rateLimit.spawn.test.ts`). | Burst of many runs | Raise org overrides; runner `MAX_CONCURRENT_RUNS` below the cap. | +| G13 | Template first boot on a host needs the image present; custom templates are not in the warm pool by default. | Cold start latency | Call `prepare`/`materialize` after each template build; keep a few bot sandboxes warm only if needed. | +| G15 | Worker sandboxes need the blueprint: `ladder-v1`'s panel includes `house:sharingan-1`, so the in-sandbox worker mmaps it and `/v1/results` rejects a different `blueprint_fingerprint`. 140 GB per sandbox is impossible (G1, G2, G6; guest page caches are not shared). | `ladder-v1` / `sharingan-1` workers in production | Run the worker inside the `core` VM with a bubblewrap/gVisor bot jail, or let the worker's SHARINGAN-1 seat call `sharingan-serve` over HTTP (arena change), or a worker-sized blueprint. | +| G14 | Hostname egress allowlist reads SNI/Host; with everything else denied it is unclear whether DNS is still allowed. Unverified. | Locked-down bot sandboxes | Test on first run. If DNS is blocked, allow the resolver IP explicitly. | + +Arena-side changes needed (in this repo, not done): Postgres `Store`; `hosted` attestation so Platinum-run bots can be `verified`; rate limiting (or do it in Cloudflare); optional `/v1/health` alias. + +## 3. Phases + +1. **Phase 1, works on Platinum today:** `arena` image as a persistent sandbox (no blueprint), runner + bot template + bot sandboxes, Cloudflare Worker for `arena.sharingan.poker`. Only matches against the non-blueprint house bots. +2. **Phase 2, interim full product:** `core` image on one external big-RAM box (docker run), same Worker; everything else on Platinum. `ladder-v1` and `sharingan-1` live. +3. **Phase 3:** land G1/G2 (+G9), move `core` into the `bigmem` pool on Platinum; then G3 (custom domain) and G4 (private path) as optimizations; Postgres when scaling out. + +## 4. What the user must provide + +- Platinum: control-plane URL, an API key for each org (`sharingan-core` full access; `sharingan-bots` scoped `sandboxes:write`, `templates:write` for provisioning), the `apps` flag on the core org, prepaid balance or auto-top-up, region choice (same region for core and bots), and the decision on G1/G2/G9 (and a bigmem host). +- Registry: a GHCR (or other public registry) org to push `sharingan-arena|serve|core|bot:0.1.0`. +- Assets: read-only S3 credentials and URI for `sharingan-1.plcp` and `buckets-200/` (`ASSETS_S3_URI`); confirm the final blueprint file name and `ARENA_SIZING=medium`. +- DNS: `arena.sharingan.poker` on Cloudflare (Worker route, `UPSTREAM` var), and for G3 later a CNAME target from Platinum. +- Stripe: account, products/prices for credit packs, webhook endpoint and secret; refund policy for infra failures. +- Secrets: `ARENA_ADMIN_TOKEN`, `RUNNER_AUTH_TOKEN`, `SHARINGAN_API_KEYS`, billing webhook token. +- Decisions: price per 20k-hand run and `MARKUP`; Platinum's actual per-vCPU-second and per-GiB-second rates for `cost.ts`; Postgres provider. + +## 5. What is verified now, what is not + +Built and run (rootless podman on box A, `deploy/local/e2e.sh`): the `arena`, `serve`, `core` and bot images (clean SIGTERM, `entrypoint.sh` incl. `wait -n` supervision, mounted-blueprint path, non-root), the runner (typecheck clean, 106 tests), the full job flow in both modes against a real arena on Postgres with the tiny blueprint, the credit ledger, signed Stripe webhooks (fake secret), and sandbox teardown. + +Still unverified, all of it needs a live Platinum control plane: every SDK call shape in `runner/src/platinum/real.ts` (typed against SDK 0.9.0 and exercised against a mock `fetch` only), `network:{allow_out:[], deny_out:["0.0.0.0/0"]}` leaving exec/files/process usable, `setpriv` / `env -i` inside the guest, `process.start` `timeout_ms`, `usage()` cost field names, hostname egress with DNS (G14), and whether Platinum can pull the images (G7). The `ASSETS_S3_URI` fetch path of `entrypoint.sh` never ran (no S3 credentials); nor did the Cloudflare Worker. diff --git a/deploy/platinum/README.md b/deploy/platinum/README.md new file mode 100644 index 00000000..efd90198 --- /dev/null +++ b/deploy/platinum/README.md @@ -0,0 +1,182 @@ +# Hosted Poker Sharingan: Platinum + Stripe + +The hosted product: players buy credits (Stripe), submit a bot, the runner plays it against the house bots inside an isolated +sandbox, and the arena stores a **verified** score. Everything below runs end to end on one machine without Platinum or Stripe +credentials (`deploy/local/e2e.sh`); going live is configuration plus the Platinum gaps listed at the end. +The hosting design and the full Platinum gap analysis are in [DESIGN.md](DESIGN.md). + +| Path | What | +|---|---| +| `docker/Dockerfile` | `arena`, `serve`, `core` (arena + serve in one VM) targets. Built and run: yes. Non-root, tini, `ROLE` entrypoint | +| `docker/Dockerfile.bot` | the **match-worker sandbox** image: `sharingan-arena` binary + python/node SDKs. Takes the arena image as `ARENA_IMAGE` | +| `docker/Dockerfile.runner` | the runner service (Node 22, TypeScript via type stripping) | +| `runner/` | credit ledger, Stripe webhook, job API, sandbox orchestration. `npm run typecheck`, `npm test` (93 tests, 106 with Postgres) | +| `runner/src/platinum/` | `PlatinumClient` interface; `real.ts` (@platinum-dev/sdk) and `local.ts` (containers via the Docker Engine API) | +| `templates/`, `bot/`, `edge/` | Platinum template specs, in-sandbox launchers, Cloudflare Worker for `arena.sharingan.poker` | +| `../local/` | `compose.yml` (postgres + arena + runner), `e2e.sh`, the example bot | + +> **Production** (single bare-metal host, free mode, `BILLING_MODE=free`: no Stripe, per-player quotas, arena bot token as the credential) is +> documented in [../production/README.md](../production/README.md). New env: `BILLING_MODE`, `FREE_MAX_HANDS_PER_DAY`, `FREE_MAX_CONCURRENT_JOBS`, `ARENA_AUTH_CACHE_S`; +> new endpoints: `GET /v1/quota` (runner), `GET /v1/me` (arena: who owns this bearer token); SDK: `sharingan submit`. + +## Run it locally + +Needs podman (rootless is fine) or docker, a compose (docker-compose v2, `docker compose` or podman-compose), curl, openssl, python3. +Nothing leaves the machine: Stripe checkout is simulated and the webhook is signed with a fake secret by the script itself. + +```bash +# on the dev box (podman socket + docker-compose v2 installed, see "Box setup" below) +E2E_CPUSET=0-15 deploy/local/e2e.sh # worker mode (default): ~2 min cold (image builds), ~25 s warm +E2E_BUILD=0 E2E_MODE=connect deploy/local/e2e.sh # remote-bot mode (WebSocket + hosted:true run) +``` + +What it does and asserts (23 checks per mode, plus 6 for the broken-bot case in worker mode): + +1. builds `arena`, `bot` (worker sandbox) and `runner` images, starts postgres + arena (Postgres store, blueprint mounted read-only, + `ARENA_RUNNER_TOKEN` + `ARENA_WORKER_KEYS` set) + runner (`SANDBOX_BACKEND=local`); +2. submits with an empty balance -> **402 insufficient_credits**; +3. creates a (simulated) checkout session, sends a webhook signed with the **wrong** secret -> 400, then a correctly signed + `checkout.session.completed` -> credited $10.00; replaying it is a no-op; +4. submits `deploy/local/bots/tag_bot.py` (the SDK's TightAggressive example) for 2,000 hands of `ladder-v1` (rounded to 2,004); +5. waits, then asserts: job `finished`, **`verified: true`** (job and the arena's own run record: `finished true true`), hands = 2,004, + AIVAT score present, credits debited exactly `hands x price` (100,200 micro-USD at $0.05 per 1,000 hands), nothing left reserved, + ledger = topup, reserve, settle, sandbox container deleted, idempotent resubmit does not charge again; +6. worker mode only: a bot that cannot import (`def act(:`) is **failed, not charged, not posted** to the leaderboard, its traceback is + in `bot_log_tail`, and its sandbox is gone. + +Last run on the dev box (worker mode, tiny test blueprint): 2,004 hands in about 3 s, 23 passed, 0 failed (see the report for the paste). +`E2E_KEEP=1` leaves the stack up (runner `127.0.0.1:18090`, arena `127.0.0.1:18080`). Only loopback is bound. + +Local vs production, honestly: the sandbox is a container, not a microVM; "no network" is `NetworkMode: none`, and the connect-mode +egress allowlist is an `internal: true` network. The Platinum calls are covered by tests against the SDK with a mocked `fetch`, not +a live control plane. + +### Box setup (what was installed on box A) + +`sudo apt-get install -y --no-install-recommends podman uidmap slirp4netns fuse-overlayfs passt netavark aardvark-dns catatonit crun docker-compose-v2` +(no Docker daemon; `docker-compose-v2` is only the compose binary, linked as `/usr/local/bin/docker-compose`), then +`systemctl --user enable --now podman.socket`. Node 22 through nvm. Rootless images are tagged `localhost/sharingan-{arena,serve,core,bot,runner}:local`. + +## How a job runs + +``` +POST /v1/jobs (userId, bot tarball, track, hands, idempotencyKey) + 1 ledger.reserve(price of the hands requested) 402 if short; idempotent on the key + 2 arena POST /v1/bots a fresh player id for this job (owner = userId) + 3 sandbox create from the bot template, uploads the bot worker mode: NO network. connect mode: the arena only + 4 optional pip install (PyPI allowed only for this step) then egress goes back to the base list + 5 worker mode: sharingan-arena run --bot "env -i ... sharingan pipe bot.py" --rotation-uids 10010,...,10015 --track T --hands N + --lanes L --out /work/result.json --sign-key-file --player-id P + runner reads result.json, POST /v1/results (ARENA_RUNNER_TOKEN) -> arena checks the HMAC against + ARENA_WORKER_KEYS, the frozen panel + seed + blueprint fingerprint -> run stored verified:true + connect mode: sharingan connect (WebSocket) + POST /v1/benchmarks/T/runs {player_id, hosted:true} (runner token), poll + 6 usage(), delete() in a finally; COGS recorded (sandbox seconds x shape, max'ed with Platinum's own number, + per-hand share) + 7 ledger.settle(hands played x price); the rest of the hold is released. Our failure => charge 0 +``` + +Charging rules (`runner/src/service.ts` `chargeFor`): charge = hands the arena says were played x `PRICE_USD_PER_1K_HANDS` +(min `MIN_JOB_CHARGE_USD`); a job that fails because of **us** (provisioning, arena down, rejected signature, unverified result) +is refunded in full; a job that fails because of the **bot** is charged for hands played (`FAILED_BOT_CHARGE_USD` flat fee if none); +a bot that never answered a decision (all hands forfeited) fails without posting a result. Hands forfeited after a mid-run crash +are dealt, scored and billed (the compute happened) and reported as `forfeit_hands`. COGS and margin are recorded per job +(`cogs_micro` vs `charge_micro`), never billed. + +Crash safety: jobs and the ledger are in Postgres. On boot `recover()` fails jobs that were running (deletes their sandbox, +refunds), settles finished-but-unsettled jobs, releases stale reservations that have no job, and reaps orphaned sandboxes +(`metadata.sharingan_job`); the reaper also runs every 5 minutes. + +## Runner API + +Bearer `RUNNER_AUTH_TOKEN` on everything except `/healthz`, `/readyz` and the Stripe webhook (signature only). Money is +integer micro-USD (`*_micro`, with `*_usd` conveniences). + +| | | +|---|---| +| `GET /v1/credits/:userId` | balance, reserved, price per 1k hands | +| `GET /v1/credits/:userId/entries` | append-only ledger entries | +| `POST /v1/credits/checkout` | `{userId, pack \| amountUsd, successUrl?, cancelUrl?}` -> `{id, url}` (Stripe Checkout, or simulated without `STRIPE_SECRET_KEY`) | +| `POST /v1/webhooks/stripe` | verifies `Stripe-Signature` (HMAC-SHA256 over `t.rawBody`, 300 s tolerance); `checkout.session.completed` and `.async_payment_succeeded` credit once per session id; other products and unpaid sessions are acknowledged and ignored | +| `GET /v1/quote?hands=N` | price of a run | +| `POST /v1/jobs` | `{userId, botName, language, entry, artifactTgzBase64, requirementsFile?, track, hands, lanes?, mode?, idempotencyKey}` -> 202 `{id}`; 200 `deduped:true` on a repeat key; 402 when short | +| `GET /v1/jobs/:id`, `GET /v1/jobs?userId=` | status, progress, score, `verified`, charge, `bot_log_tail`, sandbox state | +| `POST /v1/jobs/:id/abort` | | + +## Configuration (runner) + +All env, validated at boot (`runner/src/config.ts`). The ones you must set: + +| env | | +|---|---| +| `RUNNER_AUTH_TOKEN` | bearer your web / billing backend uses | +| `RUNNER_DATABASE_URL` | Postgres for the ledger and jobs (separate database or schema from the arena's) | +| `ARENA_URL`, `ARENA_RUNNER_TOKEN` | the arena and its `ARENA_RUNNER_TOKEN` (not an admin token) | +| `WORKER_KEY_ID`, `WORKER_SIGN_KEY` | the key the worker signs with; the arena needs `ARENA_WORKER_KEYS==` | +| `WORKER_ENV_JSON` | env for the worker process, e.g. `{"ARENA_BLUEPRINT":"...","ARENA_BUCKETS":"tables:...","ARENA_SIZING":"medium"}` | +| `STRIPE_WEBHOOK_SECRET`, `STRIPE_SECRET_KEY` | webhook signing secret `whsec_...`; secret key (unset = simulated checkout, no network) | +| `PRICE_USD_PER_1K_HANDS` | **the price** (default 0.05 = $1 per 20,000 hands: a placeholder, decide it) | +| `SANDBOX_BACKEND` | `platinum` (default; needs `PT_TOKEN`, `PT_API_URL`, `BOT_TEMPLATE`, `PT_REGION`) or `local` | +| `CREDIT_PACKS` | JSON `[{id, price_usd, credit_usd, label}]` (defaults: $10, $50 -> $55, $200 -> $240) | + +Also: `BOT_CPU`/`BOT_RAM_MB`/`BOT_DISK_GB`, `MAX_CONCURRENT_RUNS`, `RUN_DEADLINE_S`, `MIN_HANDS`/`MAX_HANDS`, `FAILED_BOT_CHARGE_USD`, +`USD_PER_VCPU_SECOND`/`USD_PER_GIB_SECOND`/`USD_PER_HAND_ARENA_SHARE` (COGS model), `DEFAULT_JOB_MODE`, `WORKER_CMD_TEMPLATE`. + +## Tests + +```bash +cd deploy/platinum/runner && npm install && npm run typecheck +npm test # 92 pass, the Postgres contract tests are skipped +TEST_DATABASE_URL=postgres://user:pw@127.0.0.1:55432/db npm test # all 106, ledger + job store on Postgres (fresh schema per test) +``` + +Covers: Stripe signature scheme and event handling with a fake secret, checkout request shape with a fake fetch, ledger +(idempotency, concurrency, no overdraft, invariant) on memory and Postgres, the local backend against a fake Docker Engine on a +unix socket, the real SDK adapter through the SDK's `fetch` override, every job verdict (both modes) with fake sandbox + fake arena, +the service and HTTP layer (402, refunds, dedup, abort, concurrency cap, crash recovery). + +## Going live + +1. **Platinum.** Two orgs, as in DESIGN.md: `sharingan-bots` (runner key scoped `sandboxes:write` + `templates:write` for provisioning; + set `PUT /v1/billing/limits` as a circuit breaker; auto top-up) and `sharingan-core` (the arena). Set `PT_API_URL`, `PT_TOKEN`, `PT_REGION`. +2. **Images.** Push `sharingan-{arena,serve,core,bot,runner}:0.1.0` to a registry Platinum can pull anonymously (GHCR, public; no weights inside), + build the bot image from the pushed arena image (`--build-arg ARENA_IMAGE=ghcr.io//sharingan-arena:0.1.0`), replace `REPLACE_ORG` in `templates/*.json`, + then `PT_TOKEN=... npm run provision -- sharingan-bot`. Commit `Cargo.lock` with the arena's new deps and add `--locked` back to `docker/Dockerfile`. +3. **Big-RAM host for SHARINGAN-1** (384 GB RAM, 2+ TB NVMe, KVM) running the `core` image (`ASSETS_S3_URI`, read-only AWS creds for the blueprint + bucket, `ARENA_SIZING=medium`, `ARENA_ADMIN_TOKEN`, `ARENA_RUNNER_TOKEN`, `ARENA_WORKER_KEYS`, `ARENA_DATABASE_URL` for a managed Postgres, + `SHARINGAN_API_KEYS`). Interim: a plain `docker run` on the rented box; move into a Platinum `bigmem` pool when G1/G2 land. +4. **DNS.** `arena.sharingan.poker` on the existing Cloudflare zone -> `edge/arena-proxy-worker.ts` (`UPSTREAM` = the arena's public URL), WebSockets pass through. + Rate limiting in Cloudflare; the runner calls the arena directly (`ARENA_URL`) so job traffic does not pay for the edge. +5. **Stripe.** Account, products are created per session (no price ids needed). Set `STRIPE_SECRET_KEY` (test key first), add a webhook endpoint + `https:///v1/webhooks/stripe` for `checkout.session.completed` and `checkout.session.async_payment_succeeded`, put its signing secret in + `STRIPE_WEBHOOK_SECRET`, set `PUBLIC_BASE_URL` (success/cancel return). Refund policy for infra failures is already automatic (credits). + Stripe refunds / disputes (`charge.refunded`, `charge.dispute.created`) are acknowledged but do nothing: handle them by hand until policy is decided. +6. **Run the runner** (any small always-on service, not necessarily on Platinum) with the env above; expose only to your web / billing backend + (it is bearer-token authenticated, not a player-facing API) and publicly only `/v1/webhooks/stripe`. +7. Secrets to mint: `ARENA_ADMIN_TOKEN`, `ARENA_RUNNER_TOKEN`, worker key (`openssl rand -hex 32`), `RUNNER_AUTH_TOKEN`, `SHARINGAN_API_KEYS`, DB passwords. +8. Decisions: price per 1,000 hands, credit packs, Platinum's real per-vCPU/GiB-second rates for the COGS model, free-credit grants (use a `topup` with a `grant:` event id). + +## Remaining Platinum product gaps (exact) + +From DESIGN.md (unchanged unless noted), ordered by what blocks launch: + +| # | Gap | Blocks | +|---|---|---| +| G1/G2 | RAM per sandbox capped at 32 GiB, disk and volumes at 100 GB (`sandboxes.ts:473-475`, `config.ts:813-814`) | SHARINGAN-1 on Platinum itself (interim: external big-RAM box) | +| **G15 (new)** | **Worker sandboxes need the blueprint.** `ladder-v1`'s panel contains `house:sharingan-1`, so `sharingan-arena run` mmaps the blueprint in-process and `/v1/results` rejects a mismatched `blueprint_fingerprint`. A 140 GB mmap per sandbox is impossible on Platinum today (G1/G2/G6: no shared read-only volume with a shared page cache; two sandboxes never share guest page cache) | `ladder-v1` / `sharingan-1` workers in production. Options: run the worker inside the `core` VM (isolate the bot with bubblewrap/gVisor, weaker than a microVM), or have the worker's SHARINGAN-1 seat query `sharingan-serve` over HTTP (arena change), or a worker-sized blueprint | +| G3 | no custom domains | `arena.sharingan.poker` (interim: Cloudflare Worker) | +| G4 | no private sandbox-to-arena network | connect-mode latency/cost only; worker mode has no network at all | +| G5 | apps cannot be stateful (no volumes, always blue-green) | arena as an App with SQLite (moot with Postgres) | +| G9 | no hard per-sandbox lifetime or budget | runner-crash leak window (mitigated: guest `timeoutMs`, `auto_stop_minutes`, 5-minute reaper) | +| G10 | `usage()` 404s after delete, 60 s sampling, no tag grouping, billing endpoints need a full-access key | exact COGS (we meter ourselves; margin figures are estimates) | +| G12 | tier concurrency caps | burst capacity (raise org overrides; runner `MAX_CONCURRENT_RUNS`) | +| G7, G13, G14 | private images, `prepare` for cold start, DNS under deny-all | worker sandboxes need no DNS (no egress at all); only the pip window and connect mode do | +| (unverified) | `network:{allow_out:[], deny_out:["0.0.0.0/0"]}` is accepted and still leaves exec / file / process APIs working; `setpriv` and `env -i` inside the guest image; `files.write` then `chmod 0400` for the key; `process.start` `timeout_ms` kill semantics; `usage()` cost field name; `allow_out` hostname rules and DNS (G14) | first live run; every call shape is typed against SDK 0.9.0 and exercised against a mock transport only | + +Arena-side items (not in `deploy/`, owned by the worker agent): commit `Cargo.lock` with the new dependencies; the worker key is a long-lived +HMAC secret that sits (root-only) in the sandbox for the run, so a per-job derived key (`HMAC(master, job_id)` verified by the arena) would shrink the blast radius of a +sandbox escape; `/v1/results` accepts all-forfeit results (the runner filters those out itself). + +## What is mocked + +| Real | Mocked / stubbed | +|---|---| +| podman, images, compose, Postgres (arena and runner), the arena, the signed match worker, `sharingan pipe` / `connect`, the ledger, the HTTP API, webhook signature verification | **Platinum** (the local backend replaces microVMs with containers; the real adapter is tested with a mock fetch), **Stripe** (fake signing secret, simulated checkout, checkout REST call tested with a fake fetch), **S3 asset fetch** (only the mounted-blueprint path ran), Cloudflare Worker | diff --git a/deploy/platinum/bot/launch_bot.mjs b/deploy/platinum/bot/launch_bot.mjs new file mode 100644 index 00000000..f3ef223e --- /dev/null +++ b/deploy/platinum/bot/launch_bot.mjs @@ -0,0 +1,22 @@ +// Connect a user-uploaded TypeScript/JavaScript bot to the arena (connect mode; ran in deploy/local with a .ts bot). +// env: BOT_FILE (path to .ts/.js/.mjs), ARENA_URL, ARENA_TOKEN, MAX_HANDS (optional) +// Runs under node 22 with --experimental-strip-types (set via NODE_OPTIONS in the image), so .ts bots load directly +// (type-stripping only: no enums, no namespaces, no path aliases). +import { pathToFileURL } from "node:url"; +import { run } from "poker-sharingan"; + +const mod = await import(pathToFileURL(process.env.BOT_FILE).href); +let bot = mod.bot ?? mod.default; +if (typeof bot === "function") { + // a Bot subclass, or a plain act(state) function + try { bot = new bot(); } catch { bot = { act: mod.default }; } +} +if (!bot && typeof mod.act === "function") bot = { act: mod.act }; +if (!bot || typeof bot.act !== "function") { + console.error("sharingan-bot: no `bot` export, default export with act(), or act() function in", process.env.BOT_FILE); + process.exit(2); +} +const maxHands = Number(process.env.MAX_HANDS || 0) || undefined; +process.on("SIGTERM", () => process.exit(0)); +console.log("sharingan-bot: connecting"); +await run(bot, process.env.ARENA_URL, process.env.ARENA_TOKEN, { maxHands }); diff --git a/deploy/platinum/bot/launch_bot.py b/deploy/platinum/bot/launch_bot.py new file mode 100644 index 00000000..90984779 --- /dev/null +++ b/deploy/platinum/bot/launch_bot.py @@ -0,0 +1,29 @@ +"""Connect a user-uploaded Python bot to the arena and play until stopped. Thin wrapper over `sharingan connect`. + +env: BOT_FILE (path to bot .py), ARENA_URL (https://arena.sharingan.poker), ARENA_TOKEN (bot token), MAX_HANDS (optional), + LOG_LEVEL (optional) +Connect mode only (worker mode uses `sharingan pipe` inside `sharingan-arena run`). +The runner service starts the benchmark run (POST /v1/benchmarks/{track}/runs, runner token, hosted:true) after this process is connected; +the arena answers 409 not_connected until the websocket is up, and the runner retries. + +Why `connect` and not `play` / `serve`: `play` creates its own table against house bots, `serve` is webhook mode +(arena -> bot HTTP, needs a public URL per sandbox). Connect mode is outbound-only and the fastest path. +""" +import logging +import os +import sys + +from sharingan.cli import main + +logging.basicConfig(level=os.environ.get("LOG_LEVEL", "WARNING"), stream=sys.stderr) + + +def argv_from_env() -> list: + argv = ["connect", os.environ["BOT_FILE"], "--server", os.environ["ARENA_URL"], "--token", os.environ["ARENA_TOKEN"]] + if int(os.environ.get("MAX_HANDS", "0") or 0): + argv += ["--max-hands", os.environ["MAX_HANDS"]] + return argv + + +if __name__ == "__main__": + sys.exit(main(argv_from_env())) diff --git a/deploy/platinum/bot/sharingan-scrub b/deploy/platinum/bot/sharingan-scrub new file mode 100755 index 00000000..51568153 --- /dev/null +++ b/deploy/platinum/bot/sharingan-scrub @@ -0,0 +1,63 @@ +#!/bin/sh +# sharingan-scrub UID [--keep DIR]: end every process of UID and remove everything it left behind (files on every mount, +# SysV IPC), so nothing a bot wrote down reaches whatever runs next in the sandbox. The match worker runs it (as root) after +# each rotation of duplicate deals; the runner after a requirements install, keeping the installed packages (--keep, which +# the runner then seals root-owned and read-only). Exit 0 only when UID is gone without a trace (outside DIR). +set -u +u="${1:-}" +keep="" +[ "${2:-}" = "--keep" ] && keep="${3:-}" +case "$u" in '' | *[!0-9]*) echo "usage: sharingan-scrub UID [--keep DIR]" >&2; exit 2 ;; esac +case "$keep" in '' | /?*) ;; *) echo "sharingan-scrub: --keep needs an absolute directory" >&2; exit 2 ;; esac +[ "$u" -ge 1000 ] || { echo "sharingan-scrub: refusing uid $u" >&2; exit 2; } + +# live (non-zombie) processes of $u; zombies hold nothing and are reaped by init +alive() { + for s in /proc/[0-9]*/status; do + awk -v u="$u" '/^State:/ { z = ($2 == "Z") } /^Uid:/ { for (i = 2; i <= 5; i++) if ($i == u && !z) f = 1 } END { exit !f }' "$s" 2>/dev/null && return 0 + done + return 1 +} +i=0 +while alive; do + # kill(-1) as $u reaches every process $u owns (and nothing else) + setpriv --reuid="$u" --regid="$u" --clear-groups --inh-caps=-all --bounding-set=-all sh -c 'kill -9 -1' 2>/dev/null + i=$((i + 1)) + [ "$i" -lt 200 ] || { echo "sharingan-scrub: processes of uid $u survive" >&2; exit 1; } + sleep 0.05 +done + +# SysV shared memory, semaphores, message queues it created or owns: removed by id as root (an owner can re-mode an +# object so even it can't list it), then checked gone. Columns: shm/sem/msg id is field 2, uid/cuid are named in the header. +ipc_left() { + for t in shm sem msg; do + f=/proc/sysvipc/$t + [ -r "$f" ] || continue + awk -v u="$u" -v t="$t" 'NR == 1 { for (i = 1; i <= NF; i++) { if ($i == "uid") cu = i; if ($i == "cuid") cc = i } next } + ($cu == u || $cc == u) { print t, $2 }' "$f" + done +} +ipc_left | while read -r t id; do + case $t in shm) ipcrm -m "$id" ;; sem) ipcrm -s "$id" ;; msg) ipcrm -q "$id" ;; esac 2>/dev/null +done +if [ -n "$(ipc_left)" ]; then + echo "sharingan-scrub: SysV IPC of uid $u survives" >&2 + exit 1 +fi + +# every file or directory it owns, on every real filesystem (tmpfs mounts included) +awk '$3 !~ /^(proc|sysfs|cgroup|cgroup2|devpts|securityfs|debugfs|tracefs|bpf|pstore|configfs|fusectl|binfmt_misc|autofs|hugetlbfs|overlay_skip)$/ { print $2 }' /proc/mounts | + while read -r m; do + if [ -n "$keep" ]; then + find "$m" -xdev -path "$keep" -prune -o \( -user "$u" -o -group "$u" \) -print0 2>/dev/null | sort -rz | xargs -0 -r rm -rf 2>/dev/null + else + find "$m" -xdev \( -user "$u" -o -group "$u" \) -depth -exec rm -rf {} + 2>/dev/null + fi + done +if find / /tmp /var/tmp /dev/shm -xdev ${keep:+-path "$keep" -prune -o} \( -user "$u" -o -group "$u" \) -print -quit 2>/dev/null | grep -q .; then + echo "sharingan-scrub: files of uid $u survive" >&2 + exit 1 +fi +# directory times are the last thing it touched there: reset them +touch /tmp /var/tmp /dev/shm 2>/dev/null +exit 0 diff --git a/deploy/platinum/bot/test_isolation.sh b/deploy/platinum/bot/test_isolation.sh new file mode 100755 index 00000000..3c142a40 --- /dev/null +++ b/deploy/platinum/bot/test_isolation.sh @@ -0,0 +1,48 @@ +#!/bin/sh +# Isolation check against the REAL bot image (run on a host with podman, as root): a sandbox-like container (no network, +# tmpfs scratch, init, no-new-privileges) plays a short run with test_isolation_cheater.py, a bot that tries to carry +# notes from one rotation of duplicate deals into the next. With --rotation-uids no note may cross from one rotation's +# user to another's (lanes of one rotation share a user and different deals: that is fine); without it (all rotations as +# one user, no scrub) the same bot must find notes of earlier processes, which proves the probe works. +# sudo sh deploy/platinum/bot/test_isolation.sh localhost/sharingan-bot:candidate /srv/sharingan/models +# MODELS holds sharingan-1.plcp and buckets-200 (every track seats SHARINGAN-1). +set -u +IMG="${1:?usage: test_isolation.sh IMAGE MODELS_DIR}" +MODELS="${2:?usage: test_isolation.sh IMAGE MODELS_DIR}" +HERE=$(cd "$(dirname "$0")" && pwd) +C=sharingan-isolation-test +fresh() { # a new sandbox-like container for each run (the worker changes it: loopback down, users wiped). $1: sealed | open (access times as the runner leaves them, or not) + at=$1 + podman rm -f "$C" >/dev/null 2>&1 + podman run -d --name "$C" --network none --memory 4g --pids-limit 512 --security-opt no-new-privileges --init \ + --security-opt apparmor="${APPARMOR:-sharingan-sandbox}" --cap-add NET_ADMIN \ + --tmpfs /tmp:rw,nosuid,nodev,size=2g,mode=1777 --tmpfs /var/tmp:rw,nosuid,nodev,size=256m,mode=1777 \ + --tmpfs /opt/sharingan/bot:rw,nosuid,nodev,size=1g,mode=0755 --tmpfs /opt/sharingan/deps:rw,nosuid,nodev,size=2g,mode=0755 \ + --tmpfs /opt/sharingan/run:rw,nosuid,nodev,size=64m,mode=0700 --ulimit core=0 \ + -v "$MODELS:/models:ro" -e ARENA_BLUEPRINT=/models/sharingan-1.plcp -e ARENA_BUCKETS=tables:/models/buckets-200 -e ARENA_SIZING=medium \ + "$IMG" sleep infinity >/dev/null || exit 1 + podman cp "$HERE/test_isolation_cheater.py" "$C:/opt/sharingan/bot/bot.py" && podman exec "$C" sh -c 'chown root:root /opt/sharingan/bot/bot.py && chmod 0644 /opt/sharingan/bot/bot.py && for i in $(seq 0 15); do echo $i > /opt/sharingan/bot/m$i; done && chmod 0644 /opt/sharingan/bot/m*' + [ "$at" = sealed ] && podman exec "$C" sh -c 'find -P /opt/sharingan/bot -exec touch -a -h -d 2099-01-01 {} +' +} +BOT='env -i HOME=/tmp PATH=/usr/local/bin:/usr/bin:/bin PYTHONPATH=/opt/sharingan/deps PYTHONUNBUFFERED=1 python3 /opt/sharingan/bot/bot.py' +run() { # $1 = label, $2 = log layout (private: as the runner does it | shared: a world-readable log), rest = worker args + label=$1; layout=$2; shift 2 + if [ "$layout" = private ]; then pre='umask 077; mkdir -p -m 0700 /opt/sharingan/run/proc'; log=/opt/sharingan/run/proc/w; else pre='umask 022'; log=/tmp/proc-1; fi + podman exec "$C" sh -c "$pre; mkdir -p /work && cd /work && exec sharingan-arena run --bot \"\$0\" --track ladder-v1 --hands 1200 --lanes 2 --out /work/r.json --quiet $* > $log.out 2> $log.err" "$BOT" + rc=$? + podman exec "$C" cat "$log.err" > /tmp/iso-$label.err + echo "$label: exit $rc | hands $(podman exec "$C" python3 -c 'import json; r=json.load(open("/work/r.json")); print(r["hands"], "isolated:", r["worker"].get("isolated_rotations"))')" + # notes seen across users (rotations), and notes seen at all + echo " privileges a bot got: $(grep -c '^PRIV' /tmp/iso-$label.err)" + echo " crossed between users: $(awk '/^SEEN/ { split($(NF-2), a, ":"); split($NF, b, ":"); if (a[1] != b[1]) n++ } END { print n+0 }' /tmp/iso-$label.err) | seen from other processes: $(grep -c '^SEEN' /tmp/iso-$label.err)" +} +fresh sealed +run isolated private --rotation-uids 10010,10011,10012,10013,10014,10015 +awk '/^SEEN/ { split($(NF-2), a, ":"); split($NF, b, ":"); if (a[1] != b[1]) print }' /tmp/iso-isolated.err | head +podman exec "$C" sh -c 'for u in 10010 10011 10012 10013 10014 10015; do n=$(find / -xdev -user $u 2>/dev/null | wc -l); [ "$n" = 0 ] || echo "files of $u left: $n"; done; ps -eo user,pid,cmd 2>/dev/null | grep -c rot || true' +fresh open +# control: every rotation as the same user, no scrub, a world-readable log, access times not sealed -> the cheater must see its notes +BOT="exec setpriv --reuid=10002 --regid=10002 --clear-groups $BOT" +run control shared +grep '^SEEN' /tmp/iso-control.err | sed -e 's/ from .*//' -e 's/proc-1\.[a-z]*/proc-1.*/' | sort | uniq -c | head -12 +podman rm -f "$C" >/dev/null diff --git a/deploy/platinum/bot/test_isolation_cheater.py b/deploy/platinum/bot/test_isolation_cheater.py new file mode 100644 index 00000000..294bb466 --- /dev/null +++ b/deploy/platinum/bot/test_isolation_cheater.py @@ -0,0 +1,222 @@ +"""A bot that tries every way it can to carry notes from one rotation of duplicate deals into the next. + +Used by deploy/platinum/bot/test_isolation.sh against the real bot image: each new bot process first looks for notes +left by an earlier process (files in every writable place, POSIX shared memory, a daemon on an abstract unix socket, +/tmp's timestamp, its own stderr, and every file it can read in the scratch and run directories: it prints a note on +stderr on every turn, so a log that carries bot output and is readable later would show up) and prints `SEEN from by ` on stderr for every one it finds, then leaves +its own notes and plays on. +Speaks the pipe protocol directly. (That a process never meets a deal twice is tested in arena/server/tests/worker.rs.) +""" +import json +import os +import re +import socket +import stat +import sys + +ME = f"{os.getuid()}:{os.getpid()}" +MARK_PORTS = {40000 + u % 1000 for u in (10002, 10010, 10011, 10012, 10013, 10014, 10015)} +SOCK = "\0sharingan-cheat" +PLACES = ["/tmp/notes", "/var/tmp/notes", "/dev/shm/notes", os.path.expanduser("~/notes"), "/opt/sharingan/bot/notes", + "/opt/sharingan/deps/notes", "/work/notes", "/run/lock/notes"] + + +def seen(how, src): + """A note from another process got through: `SEEN from by ` (the harness decides).""" + src = src.strip() + if src and src != ME: + print(f"SEEN {how} from {src} by {ME}", file=sys.stderr, flush=True) + + +def priv(what): + print(f"PRIV {what} (as {ME})", file=sys.stderr, flush=True) + + +def probe_privileges(): + """Anything a bot user must not be able to do; `PRIV ` for each that works.""" + try: + for ln in open("/proc/self/status"): + if ln.split(":")[0] in ("CapEff", "CapPrm", "CapInh", "CapAmb") and int(ln.split()[1], 16): + priv(ln.strip()) + except OSError: + pass + try: + os.setuid(0) + priv("setuid(0)") + except OSError: + pass + for pid in os.listdir("/proc"): + try: + if pid.isdigit() and open(f"/proc/{pid}/comm").read().strip() == "sharingan-arena": + try: + os.kill(int(pid), 0) + priv(f"signal the worker ({pid})") + except OSError: + pass + try: + open(f"/proc/{pid}/environ").read(1) + priv("read the worker's environment") + except OSError: + pass + except OSError: + pass + for path in ("/opt/sharingan/worker.key", "/opt/sharingan/run.seed", "/models/sharingan-1.plcp"): + try: + open(path, "rb").read(1) + priv(f"read {path}") + except OSError: + pass + try: + os.listdir("/opt/sharingan/run") + priv("list the runner's directory") + except OSError: + pass + + +def look(): + # access times: a file of the (root-owned) bot directory read by an earlier user, m + for i in range(16): + try: + st = os.stat(f"/opt/sharingan/bot/m{i}") + # moved by a read: later than the file's change time, and not the far-future value the runner seals it with + if st.st_ctime_ns < st.st_atime_ns < 3786825600 * 10**9: + seen(f"atime m{i}", f"{10000 + i}:atime") + except OSError: + pass + for p in PLACES: + try: + with open(p) as f: + seen(f"file {p}", f.read(40)) + except OSError: + pass + try: + from multiprocessing import shared_memory + s = shared_memory.SharedMemory(name="sharingan-cheat") + seen("shared memory", bytes(s.buf[:40]).rstrip(b"\0").decode()) + s.close() + except Exception: + pass + try: + c = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + c.settimeout(0.5) + c.connect(SOCK) + seen("daemon", c.recv(64).decode()) + except OSError: + pass + # its own stderr: a shared regular file would carry (or at least measure) what earlier processes printed + try: + st = os.fstat(2) + if stat.S_ISREG(st.st_mode) and st.st_size > 0: + seen("stderr is a shared file", f"{st.st_size}:size") + except OSError: + pass + # every readable file in the places a log could live + for top in ("/tmp", "/var/tmp", "/dev/shm", "/run", "/work", "/opt/sharingan"): + for root, dirs, files in os.walk(top): + for fn in files: + path = os.path.join(root, fn) + try: + if os.path.getsize(path) > 64 << 20: + continue + with open(path, "rb") as f: + for m in set(re.findall(rb"CHEATNOTE (\d+:\d+)", f.read())): + seen(f"readable file {path}", m.decode()) + except OSError: + pass + # TCP TIME_WAIT state outlives the process that made it: ports 40000+uid%1000 left by an earlier user + for tab in ("/proc/net/tcp", "/proc/net/tcp6"): + try: + for ln in open(tab).read().splitlines()[1:]: + f = ln.split() + if len(f) > 3 and f[3] == "06": + for ep in (f[1], f[2]): + port = int(ep.rsplit(":", 1)[1], 16) + if port in MARK_PORTS: # only the ports a cheater binds (ephemeral ports fall in this range too) + seen("tcp time_wait", f"{10000 + port - 40000}:tw") + except OSError: + pass + try: + tag = os.stat("/tmp").st_mtime_ns % 100000 # an earlier process may have written its uid into /tmp's timestamp + if 10000 <= tag < 10100: + seen("/tmp mtime", f"{tag}:mtime") + except OSError: + pass + + +def write_notes(): + try: + open(f"/opt/sharingan/bot/m{os.getuid() % 16}").read() # moves its access time, unless the mount says noatime + except OSError: + pass + for p in PLACES: + try: + with open(p, "w") as f: + f.write(ME) + os.chmod(p, 0o666) + except OSError: + pass + try: + from multiprocessing import shared_memory, resource_tracker + try: + s = shared_memory.SharedMemory(name="sharingan-cheat", create=True, size=64) + except FileExistsError: + s = shared_memory.SharedMemory(name="sharingan-cheat") + b = ME.encode()[:40] + s.buf[:40] = b + b"\0" * (40 - len(b)) + resource_tracker.unregister(s._name, "shared_memory") # keep it after we exit + except Exception: + pass + try: + ns = os.stat("/tmp").st_mtime_ns + os.utime("/tmp", ns=(ns, ns - ns % 100000 + os.getuid() % 100000)) + except OSError: + pass + # TCP to itself over loopback from a port that names this user, closed client-first: the TIME_WAIT entry stays ~60 s + try: + srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + srv.bind(("127.0.0.1", 0)) + srv.listen(1) + cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + cli.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + cli.bind(("127.0.0.1", 40000 + os.getuid() % 1000)) + cli.settimeout(1) + cli.connect(srv.getsockname()) + conn, _ = srv.accept() + cli.close() + conn.close() + srv.close() + except OSError: + pass + # a daemon that outlives this process and serves notes on an abstract socket + if os.fork() == 0: + os.setsid() + if os.fork() == 0: + try: + srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + srv.bind(SOCK) + srv.listen(8) + for fd in (0, 1, 2): + os.close(fd) + while True: + c, _ = srv.accept() + c.sendall(ME.encode()) + c.close() + except OSError: + pass + os._exit(0) + os._exit(0) + + +probe_privileges() +look() +write_notes() +print(json.dumps({"v": 1, "type": "hello", "data": {"protocol": 1}}), flush=True) +for line in sys.stdin: + m = json.loads(line) + if m["type"] == "your_turn": + d = m["data"] + print(f"CHEATNOTE {ME} hand {d['hand_id']} cards {d.get('hole_cards')}", file=sys.stderr, flush=True) + t = "check" if d["legal"].get("check") else "call" + print(json.dumps({"v": 1, "type": "act", "data": {"hand_id": d["hand_id"], "decision_id": d["decision_id"], "type": t}}), flush=True) + elif m["type"] == "bye": + break diff --git a/deploy/platinum/docker/Dockerfile b/deploy/platinum/docker/Dockerfile new file mode 100644 index 00000000..806a7bb0 --- /dev/null +++ b/deploy/platinum/docker/Dockerfile @@ -0,0 +1,81 @@ +# syntax=docker/dockerfile:1.7 +# Poker Sharingan server images (arena / serve / core). Built and run with rootless podman; see deploy/local/e2e.sh. +# +# Build from the repo root (context = repo root): +# podman build -f deploy/platinum/docker/Dockerfile --target arena -t ghcr.io//sharingan-arena:0.1.0 . +# podman build -f deploy/platinum/docker/Dockerfile --target serve -t ghcr.io//sharingan-serve:0.1.0 . +# podman build -f deploy/platinum/docker/Dockerfile --target core -t ghcr.io//sharingan-core:0.1.0 . +# (add --build-arg CARGO_BUILD_JOBS=16 to cap the compiler; default 16) +# +# Targets +# arena : sharingan-arena only (REST + WS; SQLite, or Postgres with ARENA_DATABASE_URL). Without a blueprint there is no +# house:sharingan-1, so ladder-v1 / sharingan-1 return 400. +# serve : sharingan-serve only (stateless /v1/act inference with turn/river search). Needs a blueprint. +# core : both, in ONE VM, so they share a single page cache of the ~140 GB blueprint +# (two Platinum sandboxes never share guest page cache). This is the production target. +# +# Platinum builds a template from a PINNED registry tag (no :latest), see apps/api/src/api/apps.ts isPinned(). +# The image carries NO weights: either mount them at $ASSETS_DIR (blueprint file + buckets-200/), or let the entrypoint pull +# them from object storage on first boot (ASSETS_S3_URI). Runs as uid 10001 (sharingan). + +ARG RUST_IMAGE=docker.io/library/rust:1-bookworm +ARG RUNTIME_IMAGE=docker.io/library/debian:bookworm-slim + +# ---------------------------------------------------------------- build +FROM ${RUST_IMAGE} AS build +WORKDIR /src +# Set e.g. RUSTFLAGS="-C target-cpu=x86-64-v3" if every Platinum host in the pool has AVX2 (EPYC does). +ARG RUSTFLAGS="" +ARG CARGO_BUILD_JOBS=16 +ENV RUSTFLAGS=${RUSTFLAGS} CARGO_BUILD_JOBS=${CARGO_BUILD_JOBS} CARGO_TERM_COLOR=never +# Only the Rust workspace goes in (keeps the compile layer cached when the runner / SDK / docs change). +COPY Cargo.toml Cargo.lock ./ +COPY engine engine +COPY sharingan-1 sharingan-1 +COPY arena arena +COPY research research +# `serve` profile = release + panic=unwind (Cargo.toml [profile.serve]) so a panicking search is caught per request. +RUN --mount=type=cache,target=/usr/local/cargo/registry,sharing=locked \ + --mount=type=cache,target=/src/target,sharing=locked \ + cargo build --locked --profile serve -p sharingan-arena -p sharingan-serve \ + && install -D -m0755 target/serve/sharingan-arena /out/sharingan-arena \ + && install -D -m0755 target/serve/sharingan-serve /out/sharingan-serve + +# ---------------------------------------------------------------- runtime base +FROM ${RUNTIME_IMAGE} AS runtime-base +RUN apt-get update \ + && apt-get install -y --no-install-recommends ca-certificates curl awscli tini \ + && rm -rf /var/lib/apt/lists/* \ + && useradd --uid 10001 --create-home --shell /usr/sbin/nologin sharingan \ + && mkdir -p /data /models \ + && chown sharingan:sharingan /data /models +COPY deploy/platinum/docker/entrypoint.sh /usr/local/bin/sharingan-entrypoint +RUN chmod 0755 /usr/local/bin/sharingan-entrypoint +ENV ARENA_BIND=0.0.0.0:8080 \ + ARENA_DB=/data/arena.db \ + SHARINGAN_BIND=0.0.0.0:8081 \ + ASSETS_DIR=/models +USER sharingan +WORKDIR /data +ENTRYPOINT ["/usr/bin/tini", "--", "/usr/local/bin/sharingan-entrypoint"] + +# ---------------------------------------------------------------- arena +FROM runtime-base AS arena +COPY --from=build /out/sharingan-arena /usr/local/bin/sharingan-arena +ENV ROLE=arena +EXPOSE 8080 +VOLUME ["/data"] + +# ---------------------------------------------------------------- serve +FROM runtime-base AS serve +COPY --from=build /out/sharingan-serve /usr/local/bin/sharingan-serve +ENV ROLE=serve +EXPOSE 8081 + +# ---------------------------------------------------------------- core (arena + serve, shared page cache) +FROM runtime-base AS core +COPY --from=build /out/sharingan-arena /usr/local/bin/sharingan-arena +COPY --from=build /out/sharingan-serve /usr/local/bin/sharingan-serve +ENV ROLE=core +EXPOSE 8080 8081 +VOLUME ["/data"] diff --git a/deploy/platinum/docker/Dockerfile.bot b/deploy/platinum/docker/Dockerfile.bot new file mode 100644 index 00000000..9807d50a --- /dev/null +++ b/deploy/platinum/docker/Dockerfile.bot @@ -0,0 +1,68 @@ +# syntax=docker/dockerfile:1.7 +# Sandbox template image for UPLOADED USER BOTS (Python and TypeScript): the "match worker" sandbox. +# +# Build the arena image first (it carries the compiled sharingan-arena binary), then this one, from the repo root: +# podman build -f deploy/platinum/docker/Dockerfile --target arena -t ghcr.io//sharingan-arena:0.1.0 . +# podman build -f deploy/platinum/docker/Dockerfile.bot --build-arg ARENA_IMAGE=ghcr.io//sharingan-arena:0.1.0 \ +# -t ghcr.io//sharingan-bot:0.1.0 . +# Then register it as a Platinum template (deploy/platinum/runner/src/provision.ts, templates/sharingan-bot.json). +# +# Contents +# /usr/local/bin/sharingan-arena the match worker (`sharingan-arena run --bot "" ...`): engine + house bots + AIVAT, +# spawns the user's bot as a stdin/stdout subprocess (`sharingan pipe mybot.py`) +# python3 + `sharingan` CLI (sdk/python; `sharingan pipe`, and `sharingan connect` for the remote-bot mode) +# node 22 + poker-sharingan (sdk/typescript) + ws, launch_bot.mjs +# /opt/sharingan/launch_bot.{py,mjs} thin wrappers that CONNECT a bot to /v1/play (remote-bot mode only) +# The image has no entrypoint process: the runner starts everything with sandbox.process.start(). +# The user's bot runs unprivileged (each rotation of duplicate deals as its own uid, 10010..10015; installs as 10002); the worker runs as root and keeps its signing key (written at run time, +# mode 0400) out of the bot's reach. + +ARG ARENA_IMAGE=localhost/sharingan-arena:local + +FROM ${ARENA_IMAGE} AS arena-bin + +FROM docker.io/library/node:22-bookworm-slim AS node +FROM docker.io/library/node:22-bookworm-slim AS tsbuild +WORKDIR /sdk +COPY sdk/typescript/ ./ +RUN npm install --no-audit --no-fund && npm run build +# runtime dependency of the SDK's WebSocket client, installed on its own (the SDK lists ws as a peer) +RUN mkdir /wsdep && cd /wsdep && npm init -y >/dev/null && npm install --omit=dev --no-audit --no-fund ws@8 + +FROM docker.io/library/python:3.12-slim-bookworm +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates tar util-linux coreutils && rm -rf /var/lib/apt/lists/* + +# match worker (built on debian bookworm, same glibc as this base) +COPY --from=arena-bin /usr/local/bin/sharingan-arena /usr/local/bin/sharingan-arena + +# node 22 runtime (copied from the official image; no apt repo needed) +COPY --from=node /usr/local/bin/node /usr/local/bin/node +ENV NODE_OPTIONS="--experimental-strip-types --no-warnings" + +# Python SDK +COPY sdk/python /tmp/sdk-python +RUN pip install --no-cache-dir /tmp/sdk-python && rm -rf /tmp/sdk-python + +# TypeScript SDK: laid out so `import "poker-sharingan"` resolves for any file under /opt/sharingan +RUN mkdir -p /opt/sharingan/node_modules/poker-sharingan /opt/sharingan/bot +COPY --from=tsbuild /sdk/dist /opt/sharingan/node_modules/poker-sharingan/dist +COPY --from=tsbuild /sdk/package.json /opt/sharingan/node_modules/poker-sharingan/package.json +COPY --from=tsbuild /wsdep/node_modules/ws /opt/sharingan/node_modules/ws + +COPY deploy/platinum/bot/launch_bot.py /opt/sharingan/launch_bot.py +COPY deploy/platinum/bot/launch_bot.mjs /opt/sharingan/launch_bot.mjs +COPY deploy/platinum/bot/sharingan-scrub /usr/local/bin/sharingan-scrub +RUN chmod -R a+rX /opt/sharingan && chmod 0755 /usr/local/bin/sharingan-scrub \ + && mkdir -p /opt/sharingan/bot /opt/sharingan/deps /work && chmod 0755 /opt/sharingan/bot /opt/sharingan/deps /work + +# Unprivileged users. The bot's install (pip) and the remote-bot mode run as 10002; the hosted worker runs each rotation of +# duplicate deals as its own user, 10010..10015, and wipes what it left before the next (sharingan-scrub). No home +# directories: HOME is /tmp, a size-capped tmpfs in the sandbox. Nothing on the image is writable by them. +RUN useradd -u 10002 -M -d /tmp -s /usr/sbin/nologin bot \ + && for i in 0 1 2 3 4 5; do useradd -u $((10010 + i)) -M -d /tmp -s /usr/sbin/nologin "rot$i" || exit 1; done \ + && { [ ! -d /run/lock ] || chmod 0755 /run/lock; } \ + && find / -xdev -perm /6000 -type f -exec chmod a-s {} + \ + && ww="$(find / -xdev -perm -0002 \( -type d -o -type f \) ! -path /tmp ! -path /var/tmp 2>/dev/null)" \ + && { [ -z "$ww" ] || { echo "world-writable paths in the bot image (a bot could keep notes there): $ww" >&2; exit 1; }; } +WORKDIR /opt/sharingan/bot +CMD ["sleep", "infinity"] diff --git a/deploy/platinum/docker/Dockerfile.bot.dockerignore b/deploy/platinum/docker/Dockerfile.bot.dockerignore new file mode 100644 index 00000000..944c365c --- /dev/null +++ b/deploy/platinum/docker/Dockerfile.bot.dockerignore @@ -0,0 +1,15 @@ +.git +target +**/target +site +.wrangler +data +logs +**/__pycache__ +**/node_modules +**/.venv +deploy/platinum/runner/dist +deploy/platinum/runner/jobs.json +docs +scripts +*.log diff --git a/deploy/platinum/docker/Dockerfile.dockerignore b/deploy/platinum/docker/Dockerfile.dockerignore new file mode 100644 index 00000000..944c365c --- /dev/null +++ b/deploy/platinum/docker/Dockerfile.dockerignore @@ -0,0 +1,15 @@ +.git +target +**/target +site +.wrangler +data +logs +**/__pycache__ +**/node_modules +**/.venv +deploy/platinum/runner/dist +deploy/platinum/runner/jobs.json +docs +scripts +*.log diff --git a/deploy/platinum/docker/Dockerfile.runner b/deploy/platinum/docker/Dockerfile.runner new file mode 100644 index 00000000..e3a10665 --- /dev/null +++ b/deploy/platinum/docker/Dockerfile.runner @@ -0,0 +1,17 @@ +# syntax=docker/dockerfile:1.7 +# The eval runner + credit ledger service (deploy/platinum/runner). Plain Node 22, TypeScript run via type stripping. +# +# podman build -f deploy/platinum/docker/Dockerfile.runner -t ghcr.io//sharingan-runner:0.1.0 . +# +# Config is all env (runner/src/config.ts). In local mode (SANDBOX_BACKEND=local) mount a Docker-compatible engine socket +# at $CONTAINER_HOST (default /var/run/engine.sock) so the runner can start sandbox containers beside itself. + +FROM docker.io/library/node:22-bookworm-slim +WORKDIR /app +COPY deploy/platinum/runner/package.json deploy/platinum/runner/package-lock.json* ./ +RUN if [ -f package-lock.json ]; then npm ci --omit=dev --no-audit --no-fund; else npm install --omit=dev --no-audit --no-fund; fi +COPY deploy/platinum/runner/src ./src +ENV NODE_ENV=production PORT=8090 +EXPOSE 8090 +USER node +CMD ["node", "--experimental-strip-types", "--no-warnings", "src/server.ts"] diff --git a/deploy/platinum/docker/Dockerfile.runner.dockerignore b/deploy/platinum/docker/Dockerfile.runner.dockerignore new file mode 100644 index 00000000..944c365c --- /dev/null +++ b/deploy/platinum/docker/Dockerfile.runner.dockerignore @@ -0,0 +1,15 @@ +.git +target +**/target +site +.wrangler +data +logs +**/__pycache__ +**/node_modules +**/.venv +deploy/platinum/runner/dist +deploy/platinum/runner/jobs.json +docs +scripts +*.log diff --git a/deploy/platinum/docker/entrypoint.sh b/deploy/platinum/docker/entrypoint.sh new file mode 100755 index 00000000..7df83c4f --- /dev/null +++ b/deploy/platinum/docker/entrypoint.sh @@ -0,0 +1,94 @@ +#!/bin/bash +# Entry point for the arena / serve / core images. +# +# Env contract +# ROLE arena | serve | core +# ASSETS_DIR where the blueprint lives (default /models): BLUEPRINT_FILE + buckets-200/ +# BLUEPRINT_FILE file name under $ASSETS_DIR (default sharingan-1.plcp) +# BUCKETS_DIR abstraction tables directory (default $ASSETS_DIR/buckets-200; "coarse" for toy blueprints) +# SIZING bet-size menu the blueprint was trained with (default medium); ARENA_SIZING / SHARINGAN_SIZING win +# USE_BLUEPRINT 1 | 0. Default: 1 when $ASSETS_DIR/$BLUEPRINT_FILE exists or ASSETS_S3_URI is set, else 0 +# (arena then runs with house bots only: no house:sharingan-1, ladder-v1 and sharingan-1 return 400) +# ASSETS_S3_URI s3://bucket/prefix holding the blueprint file and buckets-200/. Only used when the blueprint file is +# not already present (a mounted/baked blueprint never touches S3) +# AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY / AWS_DEFAULT_REGION / AWS_ENDPOINT_URL (read-only creds for that prefix) +# ARENA_ADMIN_TOKEN, SHARINGAN_API_KEYS secrets (inject via Platinum env / secrets, never bake) +# Everything in arena/server/README.md and sharingan-1/serve/README.md also applies. +set -eu + +ROLE="${ROLE:-arena}" +ASSETS_DIR="${ASSETS_DIR:-/models}" +BLUEPRINT_FILE="${BLUEPRINT_FILE:-sharingan-1.plcp}" +BUCKETS_DIR="${BUCKETS_DIR:-$ASSETS_DIR/buckets-200}" +SIZING="${SIZING:-medium}" +USE_BLUEPRINT="${USE_BLUEPRINT:-}" +if [ -z "$USE_BLUEPRINT" ]; then + if [ -f "$ASSETS_DIR/$BLUEPRINT_FILE" ] || [ -n "${ASSETS_S3_URI:-}" ]; then USE_BLUEPRINT=1; else USE_BLUEPRINT=0; fi +fi +[ "$ROLE" = serve ] && USE_BLUEPRINT=1 + +log() { echo "{\"entrypoint\":\"$1\"}" >&2; } + +fetch_assets() { + [ "$USE_BLUEPRINT" = 1 ] || return 0 + if [ -f "$ASSETS_DIR/$BLUEPRINT_FILE" ] && { [ -f "$ASSETS_DIR/.complete" ] || [ -z "${ASSETS_S3_URI:-}" ]; }; then + log "blueprint present at $ASSETS_DIR/$BLUEPRINT_FILE; no fetch" + else + [ -n "${ASSETS_S3_URI:-}" ] || { log "no blueprint at $ASSETS_DIR/$BLUEPRINT_FILE and ASSETS_S3_URI is unset"; exit 3; } + mkdir -p "$ASSETS_DIR" + local ep="" + [ -n "${AWS_ENDPOINT_URL:-}" ] && ep="--endpoint-url $AWS_ENDPOINT_URL" # awscli 2.9 (Debian) ignores the env var + aws configure set default.s3.max_concurrent_requests 64 + aws configure set default.s3.multipart_chunksize 256MB + log "fetching assets from $ASSETS_S3_URI (first boot, ~140 GB)" + # shellcheck disable=SC2086 + aws $ep s3 sync "$ASSETS_S3_URI/buckets-200" "$ASSETS_DIR/buckets-200" --only-show-errors + # shellcheck disable=SC2086 + aws $ep s3 cp "$ASSETS_S3_URI/$BLUEPRINT_FILE" "$ASSETS_DIR/$BLUEPRINT_FILE.part" --only-show-errors + mv "$ASSETS_DIR/$BLUEPRINT_FILE.part" "$ASSETS_DIR/$BLUEPRINT_FILE" + touch "$ASSETS_DIR/.complete" + fi + # Warm the page cache (cheap if already resident). The 140 GB file must fit in guest RAM or lookups page-fault from disk. + # Skipped for small files? No: cat of a 250 MB file is instant. Set WARM=0 to disable. + if [ "${WARM:-1}" = 1 ]; then ( cat "$ASSETS_DIR/$BLUEPRINT_FILE" > /dev/null 2>&1 & ) || true; fi +} + +# "coarse" is a built-in bucketer name; anything else is a directory of tables. +arena_buckets() { if [ "$BUCKETS_DIR" = coarse ]; then echo coarse; else echo "tables:$BUCKETS_DIR"; fi; } + +run_arena() { + if [ "$USE_BLUEPRINT" = 1 ]; then + export ARENA_BLUEPRINT="$ASSETS_DIR/$BLUEPRINT_FILE" + export ARENA_BUCKETS="${ARENA_BUCKETS:-$(arena_buckets)}" + export ARENA_SIZING="${ARENA_SIZING:-$SIZING}" + fi + exec sharingan-arena +} + +run_serve() { + export SHARINGAN_BLUEPRINT="$ASSETS_DIR/$BLUEPRINT_FILE" + export SHARINGAN_BUCKETS="${SHARINGAN_BUCKETS:-$BUCKETS_DIR}" + export SHARINGAN_SIZING="${SHARINGAN_SIZING:-$SIZING}" + exec sharingan-serve +} + +case "$ROLE" in + arena) fetch_assets; run_arena ;; + serve) fetch_assets; run_serve ;; + core) + USE_BLUEPRINT=1 + fetch_assets + ( run_arena ) & A=$! + ( run_serve ) & S=$! + TERMED=0 + trap 'TERMED=1; kill $A $S 2>/dev/null' TERM INT + # If either dies, take the VM's service down so Platinum/our health check notices. + # `wait -n` returns as soon as one child exits; a TERM/INT trap interrupts it too. + wait -n || true + kill $A $S 2>/dev/null || true + wait 2>/dev/null || true # let the arena drain (ARENA_SHUTDOWN_GRACE_MS) + [ "$TERMED" = 1 ] && exit 0 # asked to stop: clean exit + exit 1 # one half died on its own: fail the unit + ;; + *) echo "unknown ROLE=$ROLE" >&2; exit 2 ;; +esac diff --git a/deploy/platinum/edge/arena-proxy-worker.test.ts b/deploy/platinum/edge/arena-proxy-worker.test.ts new file mode 100644 index 00000000..5cbbee1b --- /dev/null +++ b/deploy/platinum/edge/arena-proxy-worker.test.ts @@ -0,0 +1,74 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import worker from "./arena-proxy-worker.ts"; +import type { Env } from "./arena-proxy-worker.ts"; + +const env: Env = { UPSTREAM: "https://origin.example", EDGE_SECRET: "test-only-secret" }; + +test("public access fails closed before any origin request", async (t) => { + let calls = 0; + t.mock.method(globalThis, "fetch", async () => { calls++; return new Response("origin"); }); + for (const flag of [undefined, "false", "TRUE", "1", ""]) { + for (const path of [ + "/", "/v1/leaderboard", "/v1/leaderboard?public=true", + "/v1/benchmarks/sharingan-1", "/v1/benchmarks/sharingan-1/runs/w_example", + "/v1/players/example", "/v1/matches", "/v1/hands/example", + "/%76%31/leaderboard", "/v1/play", "/v1/act", "/readyz", + ]) { + const response = await worker.fetch(new Request("https://arena.example" + path, { + headers: { authorization: "Bearer test-token", "x-edge-secret": "forged" }, + }), { ...env, PUBLIC_ARENA_ENABLED: flag }); + assert.equal(response.status, 503, path); + assert.equal(response.headers.get("cache-control"), "no-store"); + assert.equal(response.headers.get("x-robots-tag"), "noindex, nofollow"); + assert.deepEqual(await response.json(), { error: { + code: "public_arena_unavailable", message: "The public arena is temporarily unavailable.", + } }); + } + } + assert.equal(calls, 0); +}); + +test("writes and WebSocket handshakes cannot bypass maintenance", async (t) => { + let calls = 0; + t.mock.method(globalThis, "fetch", async () => { calls++; return new Response("origin"); }); + for (const method of ["POST", "PUT", "PATCH", "DELETE", "OPTIONS"]) { + assert.equal((await worker.fetch(new Request("https://arena.example/v1/jobs", { method }), env)).status, 503); + } + assert.equal((await worker.fetch(new Request("https://arena.example/v1/play", { + headers: { upgrade: "websocket", connection: "Upgrade" }, + }), env)).status, 503); + assert.equal(calls, 0); +}); + +test("HEAD responses are empty and still fail closed", async () => { + const response = await worker.fetch(new Request("https://arena.example/v1/leaderboard", { method: "HEAD" }), env); + assert.equal(response.status, 503); + assert.equal(await response.text(), ""); +}); + +test("explicit reopening retains forwarding and replaces untrusted proxy headers", async (t) => { + const seen: Request[] = []; + t.mock.method(globalThis, "fetch", async (request: Request) => { + seen.push(request); + return new Response("operator-enabled-origin"); + }); + const response = await worker.fetch(new Request("https://arena.example/v1/leaderboard?track=sharingan-1", { + headers: { "x-edge-secret": "forged", "cf-connecting-ip": "192.0.2.4" }, + }), { ...env, PUBLIC_ARENA_ENABLED: "true" }); + assert.equal(await response.text(), "operator-enabled-origin"); + assert.equal(seen.length, 1); + assert.equal(seen[0].url, "https://origin.example/v1/leaderboard?track=sharingan-1"); + assert.equal(seen[0].headers.get("x-edge-secret"), env.EDGE_SECRET); + assert.equal(seen[0].headers.get("x-forwarded-host"), "arena.example"); + assert.equal(seen[0].headers.get("x-client-ip"), "192.0.2.4"); +}); + +test("the enabled root redirect does not hit the origin", async (t) => { + let calls = 0; + t.mock.method(globalThis, "fetch", async () => { calls++; return new Response("origin"); }); + const response = await worker.fetch(new Request("https://arena.example/"), { ...env, PUBLIC_ARENA_ENABLED: "true" }); + assert.equal(response.status, 302); + assert.equal(response.headers.get("location"), "https://sharingan.poker/docs/"); + assert.equal(calls, 0); +}); diff --git a/deploy/platinum/edge/arena-proxy-worker.ts b/deploy/platinum/edge/arena-proxy-worker.ts new file mode 100644 index 00000000..9c60a357 --- /dev/null +++ b/deploy/platinum/edge/arena-proxy-worker.ts @@ -0,0 +1,39 @@ +// Cloudflare Worker `sharingan-arena-edge`: serves https://arena.sharingan.poker by forwarding every request (REST, WebSocket +// /v1/play, runner job API, inference) to the origin, which does the path routing (Caddy: runner / serve / arena). +// +// The origin only accepts traffic that carries the shared secret header, so the Worker is the only way in: +// wrangler secret put EDGE_SECRET (same value as EDGE_SECRET in /srv/sharingan/secrets/caddy.env on the host) +// vars.UPSTREAM e.g. https://51-158-206-42.sslip.io +// Public access is closed unless explicitly enabled. Internal origin access is unchanged. +// WebSocket upgrades pass through fetch() unchanged when public access is enabled. +export interface Env { UPSTREAM: string; EDGE_SECRET: string; PUBLIC_ARENA_ENABLED?: string } + +export default { + async fetch(req: Request, env: Env): Promise { + if (env.PUBLIC_ARENA_ENABLED !== "true") { + return new Response(req.method === "HEAD" ? null : JSON.stringify({ + error: { code: "public_arena_unavailable", message: "The public arena is temporarily unavailable." }, + }), { + status: 503, + headers: { + "content-type": "application/json; charset=utf-8", + "cache-control": "no-store", + "retry-after": "3600", + "x-robots-tag": "noindex, nofollow", + "access-control-allow-origin": "*", + }, + }); + } + const url = new URL(req.url); + // The API has no page of its own: send people who open it in a browser to the docs. + if (url.pathname === "/" && (req.method === "GET" || req.method === "HEAD")) return Response.redirect("https://sharingan.poker/docs/", 302); + const target = new URL(url.pathname + url.search, env.UPSTREAM); + const headers = new Headers(req.headers); + headers.delete("host"); + headers.set("x-edge-secret", env.EDGE_SECRET); + headers.set("x-forwarded-host", url.host); + const ip = req.headers.get("cf-connecting-ip"); + if (ip) headers.set("x-client-ip", ip); // Caddy turns it into X-Forwarded-For (the arena rate-limits anonymous callers per IP) + return fetch(new Request(target, { method: req.method, headers, body: req.body, redirect: "manual" })); + }, +}; diff --git a/deploy/platinum/edge/wrangler.jsonc b/deploy/platinum/edge/wrangler.jsonc new file mode 100644 index 00000000..f67e6c73 --- /dev/null +++ b/deploy/platinum/edge/wrangler.jsonc @@ -0,0 +1,10 @@ +{ + // Cloudflare Worker for https://arena.sharingan.poker (proxy to the production host). Secret: `wrangler secret put EDGE_SECRET`. + "name": "sharingan-arena-edge", + "main": "arena-proxy-worker.ts", + "compatibility_date": "2026-10-01", + "workers_dev": false, + "preview_urls": false, + "vars": { "UPSTREAM": "https://51-158-206-42.sslip.io", "PUBLIC_ARENA_ENABLED": "false" }, + "routes": [{ "pattern": "arena.sharingan.poker", "custom_domain": true }] +} diff --git a/deploy/platinum/runner/.gitignore b/deploy/platinum/runner/.gitignore new file mode 100644 index 00000000..a478a9bb --- /dev/null +++ b/deploy/platinum/runner/.gitignore @@ -0,0 +1,2 @@ +node_modules +jobs.json diff --git a/deploy/platinum/runner/README.md b/deploy/platinum/runner/README.md new file mode 100644 index 00000000..f91a763c --- /dev/null +++ b/deploy/platinum/runner/README.md @@ -0,0 +1,73 @@ +# Hosted-job runner + +Runs uploaded Sharingan bots in disposable sandboxes and posts the signed result to the arena. HTTP skin: `src/app.ts`, +product logic: `src/service.ts`, one job: `src/job.ts`. Design and operations: `../README.md` and `../DESIGN.md`. + +## Public API (browser-callable) + +`/v1/jobs`, `/v1/jobs/:id`, `/v1/jobs/:id/abort` and `/v1/quota` are called straight from sharingan.poker with the player's arena bot +token (`Authorization: Bearer `, free billing mode). Every response carries + +``` +access-control-allow-origin: * +access-control-allow-methods: GET, POST, DELETE, OPTIONS +access-control-allow-headers: authorization, content-type +access-control-max-age: 86400 +``` + +and `OPTIONS` is answered `204` without authentication. + +### `POST /v1/jobs` + +`{botName, language, entry, artifactTgzBase64, requirementsFile?, track, hands?, lanes?, idempotencyKey, contact, profile}` -> `202 {id, status, hands, deduped}` +(`200` with `deduped: true` for a repeated key; the same key with a different track, size, name or entry is `409 idempotency_conflict`). +snake_case field names (`bot_name`, `artifact_tgz_base64`, `idempotency_key`, ...) are accepted as well. Every error is +`{error: {code, message, details}}`. Aborting a job that is already over is `409 job_not_abortable`. Free mode also caps running jobs +per client address across all its bots (`FREE_MAX_CONCURRENT_JOBS_PER_IP`, `429 quota_concurrent_ip`). + +Checks run cheapest first and **before** the quota, so a malformed request is always a `400` and never a `429`/`402`: +JSON body, field types, `hands` range, `contact` (an email) and `profile` (an http(s) link to a public profile: X, LinkedIn, GitHub, a personal page; scheme optional, `@handle` means X; stored as https), both max 200 characters and **required on every player submit** (the service token may omit them), valid base64, the upload is a gzip tarball, `entry` (and `requirementsFile`) exist in it, +and only then the per-player quota (`429`) or credit reservation (`402`). + +**Hands**: the request must be in `MIN_HANDS`..`MAX_HANDS` (default 600..200,000); the number actually played is **rounded up to a multiple +of 6** (whole deals), and that rounded value is what every response echoes (`hands: 601` is answered as `hands: 606`, matching `hands_total`; +quotas and prices use it too). So: rounded up to a multiple of 6, min 600, max 200,000 (a request of 200,000 plays 200,004). The leaderboard ranks +only a verified run of the full 20,004 hands (`ARENA_RANKED_MIN_HANDS`); a shorter run scores but never ranks. + +**Limits on the public arena (free mode)**: 1M hands per bot per rolling 24 h (on sharingan-1 also per person: all of one person's bots together, by profile or email), where every accepted job counts its planned hands even if it is aborted or +fails (only our own infra failures are free); 2 jobs at a time per bot and 2 per client address (`FREE_MAX_CONCURRENT_JOBS`, `FREE_MAX_CONCURRENT_JOBS_PER_IP`); +10 submits a minute per address (`SUBMITS_PER_MINUTE_PER_IP`); a run must finish within 30 minutes (`RUN_DEADLINE_S=1800`, so roughly under 50 ms per decision +on average; a single decision may take up to 5 s). The sandbox has Python, no network, 4 CPU and 12 GB. A 20,004-hand job of a fast bot takes about 15 s. +### Job view + +A public player (arena bot token) sees only: `id, status, bot_name, track, hands, hands_total, hands_done, mbb_per_game, ci95_mbb, verified, +forfeit_hands, error, bot_log_tail, run_id, arena_player_id, artifact_sha256 (sha256 of the uploaded .tar.gz), deals_seed (once the job is over), created_at, finished_at`. Failures on our side show a generic +`error`. The service token (`RUNNER_AUTH_TOKEN`) still gets the full view (sandbox, cost and ledger fields, `contact` and `profile`). `contact` and `profile` are never in the public view. + +`error` for a failing bot is one clear first line (for example `the bot never answered a decision (600/600 hands forfeited); nothing was +submitted.`) followed by one de-duplicated traceback / log excerpt. Progress lines are removed, and a forfeited or rejected run never +shows a score line. `bot_log_tail` is de-duplicated the same way. + +## Kept bots and reproducible evaluations + +Every accepted job keeps its upload in Postgres (job_artifacts). +GET /v1/jobs/:id/artifact is restricted to the service token and returns the exact +submitted archive. Check it against the job's artifact_sha256 before reproducing a run. +Retaining the original upload and installed dependency versions supports debugging +and evaluation on fresh deals. Owner contact/profile fields remain private. + +## Fresh secret deals + +Every worker-mode job gets its own seed `run:<64 lowercase hex>` (`crypto.randomBytes(32)`), written into the sandbox at +`/opt/sharingan/run.seed` with mode 0400 (root only, like `/opt/sharingan/worker.key`; the bot runs as uids 10010-10015, one per rotation) and handed to the worker +as `--seed-file /opt/sharingan/run.seed`. It is never in the bot's environment or arguments. The seed is recorded on the job as +`deals_seed` only once the job is over (`finished`, `failed` or `aborted`); before that it is `null` in every view. + +`WORKER_CMD_TEMPLATE` accepts `{seedfile}`; a custom template without it still gets `--seed-file` appended. The arena side (the worker's +`--seed-file` flag and acceptance of results carrying a seed) must be deployed before this runner. + +## Tests + +``` +npm ci && npm run typecheck && npm test +``` diff --git a/deploy/platinum/runner/package-lock.json b/deploy/platinum/runner/package-lock.json new file mode 100644 index 00000000..8495de58 --- /dev/null +++ b/deploy/platinum/runner/package-lock.json @@ -0,0 +1,222 @@ +{ + "name": "sharingan-eval-runner", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "sharingan-eval-runner", + "version": "0.1.0", + "dependencies": { + "@platinum-dev/sdk": "0.9.0", + "pg": "^8.13.1" + }, + "devDependencies": { + "@types/node": "^22", + "@types/pg": "^8.11.10", + "typescript": "^5.8" + }, + "engines": { + "node": ">=22.6" + } + }, + "node_modules/@platinum-dev/sdk": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/@platinum-dev/sdk/-/sdk-0.9.0.tgz", + "integrity": "sha512-u1l7mV9Wtj//d8o68SL8QNSAhrhIei3q0SQHL6E9fusV+TpORnO6Zp4rNrKP/YlNA+6nRCUBpAJYzEPIDjT1HQ==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@types/node": { + "version": "22.20.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", + "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@types/pg": { + "version": "8.23.1", + "resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.23.1.tgz", + "integrity": "sha512-fKVHpikPdg4GKks3JuLEhvwSyvwzF23hnabPy6DD8ljVbC7+6J5dQzdv4arV6jqq57djnMgs1HKBxX4P8aBI3A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "pg-protocol": "*", + "pg-types": "^2.2.0" + } + }, + "node_modules/pg": { + "version": "8.23.1", + "resolved": "https://registry.npmjs.org/pg/-/pg-8.23.1.tgz", + "integrity": "sha512-aL96AHANtWjPLDOLqnhx+ngp9+UK7ETEU8VJrDCGvsSSi/mGLcWYsS6Herg7lmaBJe4uwrfqsa7gTEFaSizDoQ==", + "license": "MIT", + "dependencies": { + "pg-connection-string": "^2.14.1", + "pg-pool": "^3.14.0", + "pg-protocol": "^1.16.1", + "pg-types": "2.2.0", + "pgpass": "1.0.5" + }, + "engines": { + "node": ">= 16.0.0" + }, + "optionalDependencies": { + "pg-cloudflare": "^1.4.1" + }, + "peerDependencies": { + "pg-native": ">=3.0.1" + }, + "peerDependenciesMeta": { + "pg-native": { + "optional": true + } + } + }, + "node_modules/pg-cloudflare": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.4.1.tgz", + "integrity": "sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ==", + "license": "MIT", + "optional": true + }, + "node_modules/pg-connection-string": { + "version": "2.14.1", + "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.14.1.tgz", + "integrity": "sha512-qR3kGNPBLpCNtz0evbKA0Y/MRFXwSSdT+pTJvYp/bXTcReZbvX1kzF0IyTc1QnxqF7AZbOeBhNL8R5mYQZV/MA==", + "license": "MIT" + }, + "node_modules/pg-int8": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz", + "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==", + "license": "ISC", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/pg-pool": { + "version": "3.14.0", + "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.14.0.tgz", + "integrity": "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==", + "license": "MIT", + "peerDependencies": { + "pg": ">=8.0" + } + }, + "node_modules/pg-protocol": { + "version": "1.16.1", + "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.16.1.tgz", + "integrity": "sha512-p9VOFMiHB/ZbJATetbg+99PxssTVSQRnyuPSQ67mN1+1KBOjZaZ83ZQzltnxPhJwSsC3nwVjJ10DVJlerbFzLg==", + "license": "MIT" + }, + "node_modules/pg-types": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz", + "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==", + "license": "MIT", + "dependencies": { + "pg-int8": "1.0.1", + "postgres-array": "~2.0.0", + "postgres-bytea": "~1.0.0", + "postgres-date": "~1.0.4", + "postgres-interval": "^1.1.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/pgpass": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz", + "integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==", + "license": "MIT", + "dependencies": { + "split2": "^4.1.0" + } + }, + "node_modules/postgres-array": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz", + "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/postgres-bytea": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz", + "integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postgres-date": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz", + "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postgres-interval": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz", + "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==", + "license": "MIT", + "dependencies": { + "xtend": "^4.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/split2": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", + "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", + "license": "ISC", + "engines": { + "node": ">= 10.x" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "license": "MIT", + "engines": { + "node": ">=0.4" + } + } + } +} diff --git a/deploy/platinum/runner/package.json b/deploy/platinum/runner/package.json new file mode 100644 index 00000000..12315417 --- /dev/null +++ b/deploy/platinum/runner/package.json @@ -0,0 +1,23 @@ +{ + "name": "sharingan-eval-runner", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "Runs uploaded Sharingan bots in isolated sandboxes (Platinum, or local containers) and drives an arena benchmark run, with a prepaid credit ledger.", + "engines": { "node": ">=22.6" }, + "scripts": { + "typecheck": "tsc --noEmit", + "test": "node --experimental-strip-types --no-warnings --test --test-concurrency=1 \"test/*.test.ts\"", + "start": "node --experimental-strip-types --no-warnings src/server.ts", + "provision": "node --experimental-strip-types --no-warnings src/provision.ts" + }, + "dependencies": { + "@platinum-dev/sdk": "0.9.0", + "pg": "^8.13.1" + }, + "devDependencies": { + "@types/node": "^22", + "@types/pg": "^8.11.10", + "typescript": "^5.8" + } +} diff --git a/deploy/platinum/runner/src/app.ts b/deploy/platinum/runner/src/app.ts new file mode 100644 index 00000000..8cc57ab8 --- /dev/null +++ b/deploy/platinum/runner/src/app.ts @@ -0,0 +1,275 @@ +// HTTP skin over Service. Called only by our own web / billing backend (Bearer RUNNER_AUTH_TOKEN), except the Stripe +// webhook, which is authenticated by its signature. +// +// GET /healthz liveness +// GET /readyz 200 when the database answers +// POST /v1/webhooks/stripe Stripe-Signature verified; checkout.session.completed -> credits +// GET /v1/credits/:userId balance +// GET /v1/credits/:userId/entries ledger entries (newest first) +// POST /v1/credits/checkout {userId, pack | amountUsd, successUrl?, cancelUrl?} -> {id, url} +// GET /v1/quote?hands=N price of a run +// POST /v1/jobs submit (credits reserved first; 402 when short) -> 202 {id, status} +// GET /v1/jobs?userId=U recent jobs +// GET /v1/jobs/:id status, progress, result, cost +// POST /v1/jobs/:id/abort +// +// Every response carries CORS headers (any origin: auth is a bearer token, never a cookie) and OPTIONS is answered 204 +// without auth, so the sharingan.poker web page can call the public routes (/v1/jobs*, /v1/quota) straight from the browser. +// A public player (arena bot token) gets publicJobView(); the service token gets the full jobView(). +import { isIPv6 } from "node:net"; +import { createHash, timingSafeEqual } from "node:crypto"; +import type { ArenaClient } from "./arena.ts"; +import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"; +import type { Config } from "./config.ts"; +import type { Logger } from "./log.ts"; +import { microToUsd } from "./money.ts"; +import { Service, ServiceError } from "./service.ts"; +import { TERMINAL, type Job } from "./store.ts"; + +export const CORS_HEADERS = { + "access-control-allow-origin": "*", + "access-control-allow-methods": "GET, POST, DELETE, OPTIONS", + "access-control-allow-headers": "authorization, content-type", + "access-control-max-age": "86400", +} as const; + +/** One key per subscriber: IPv4 as is, IPv6 by its /64 (a host gets a whole /64 to rotate through), IPv4-mapped as IPv4. */ +export function addrKey(ip: string): string { + if (!isIPv6(ip)) return ip; + const m = ip.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i); + if (m) return m[1]!; + const [head = "", tail = ""] = ip.split("::"); + const h = head ? head.split(":") : [], t = ip.includes("::") && tail ? tail.split(":") : []; + const groups = ip.includes("::") ? [...h, ...Array(8 - h.length - t.length).fill("0"), ...t] : h; + return `${groups.slice(0, 4).map((g) => parseInt(g, 16).toString(16)).join(":")}::/64`; +} + +/** Public submits per client address (SUBMITS_PER_MINUTE_PER_IP): a burst of that many, then that many a minute. */ +class Bucket { + private m = new Map(); + private readonly cap: number; + private readonly perMs: number; + constructor(cap: number, perMs: number) { + this.cap = cap; + this.perMs = perMs; + } + take(k: string): boolean { + const now = Date.now(); + const b = this.m.get(k) ?? { n: this.cap, t: now }; + b.n = Math.min(this.cap, b.n + (now - b.t) / this.perMs); + b.t = now; + if (this.m.size > 50_000) this.m.clear(); + this.m.set(k, b); + if (b.n < 1) return false; + b.n -= 1; + return true; + } +} +export function jobView(j: Job) { + return { + id: j.id, + status: j.status, + mode: j.input.mode, + user_id: j.input.userId, + bot_name: j.input.botName, + contact: j.input.contact ?? null, + profile: j.input.profile ?? null, + track: j.input.track, + hands: j.input.hands, + hands_done: j.handsDone ?? 0, + hands_total: j.handsTotal ?? j.input.hands, + run_id: j.runId ?? null, + verified: j.verified ?? false, + forfeit_hands: j.forfeitHands ?? null, + arena_player_id: j.arenaPlayerId ?? null, + mbb_per_game: j.mbbPerGame ?? null, + ci95_mbb: j.ci95Mbb ?? null, + running_mbb_per_game: j.runningMbb ?? null, + error: j.error ?? null, + error_class: j.errorClass ?? null, + sandbox_id: j.sandboxId ?? null, + sandbox_deleted: j.sandboxDeleted ?? null, + sandbox_seconds: j.sandboxSeconds ?? null, + reserved_micro: j.reservedMicro, + charge_micro: j.chargeMicro ?? null, + released_micro: j.releasedMicro ?? null, + charge_usd: j.chargeMicro === undefined ? null : microToUsd(j.chargeMicro), + settled: j.settled, + cogs_micro: j.cogsMicro ?? null, + platinum_usd: j.platinumUsd ?? null, + bot_log_tail: j.botLogTail ?? null, + artifact_sha256: j.input.artifactSha256 ?? null, + deals_seed: TERMINAL.has(j.status) ? j.dealsSeed ?? null : null, // secret while the run is in flight + created_at: new Date(j.createdAt).toISOString(), + finished_at: j.finishedAt ? new Date(j.finishedAt).toISOString() : null, + }; +} + +/** What a public player needs to see about their own job, and nothing about our sandboxes, money or config. */ +export function publicJobView(j: Job) { + const ours = j.status === "failed" && j.errorClass !== "bot"; // infrastructure failure: details stay in our logs + return { + id: j.id, + status: j.status, + bot_name: j.input.botName, + track: j.input.track, + hands: j.input.hands, + hands_total: j.handsTotal ?? j.input.hands, + hands_done: j.handsDone ?? 0, + mbb_per_game: j.mbbPerGame ?? null, + ci95_mbb: j.ci95Mbb ?? null, + verified: j.verified ?? false, + forfeit_hands: j.forfeitHands ?? null, + error: ours ? "internal error while running your bot; it does not count against your quota, please retry" : j.error ?? null, + bot_log_tail: j.botLogTail ?? null, + run_id: j.runId ?? null, + arena_player_id: j.arenaPlayerId ?? null, + artifact_sha256: j.input.artifactSha256 ?? null, + deals_seed: TERMINAL.has(j.status) ? j.dealsSeed ?? null : null, + created_at: new Date(j.createdAt).toISOString(), + finished_at: j.finishedAt ? new Date(j.finishedAt).toISOString() : null, + }; +} + +class HttpError extends Error { + status: number; + code: string; + constructor(status: number, code: string, message: string) { super(message); this.status = status; this.code = code; } +} + +const digest = (s: string) => createHash("sha256").update(s).digest(); + +async function readBody(req: IncomingMessage, limit: number): Promise { + const chunks: Buffer[] = []; + let n = 0; + for await (const c of req) { + n += (c as Buffer).length; + if (n > limit) throw new HttpError(413, "payload_too_large", `body larger than ${limit} bytes`); + chunks.push(c as Buffer); + } + return Buffer.concat(chunks); +} + +export function createApp(svc: Service, cfg: Config, opts: { ready?: () => Promise; log?: Logger; arena?: ArenaClient } = {}): Server { + const jobBodyLimit = Math.ceil(cfg.limits.maxArtifactBytes * 1.4) + 64 * 1024; + const want = digest(cfg.authToken); + const bearerOf = (req: IncomingMessage) => (req.headers.authorization ?? "").replace(/^Bearer /i, "").trim(); + const authed = (req: IncomingMessage) => timingSafeEqual(digest(bearerOf(req)), want); + // FREE mode: a public player authenticates with their arena bot token; validated against the arena (GET /v1/me), cached briefly. + const tokenCache = new Map(); + const playerOf = async (req: IncomingMessage): Promise => { + if (cfg.billing.mode !== "free" || !opts.arena) return undefined; + const tok = bearerOf(req); + if (!tok || tok.length > 200) return undefined; + const key = digest(tok).toString("hex"); + const hit = tokenCache.get(key); + if (hit && hit.exp > Date.now()) return hit.playerId ?? undefined; + const who = await opts.arena.whoami(tok).catch(() => undefined); + const playerId = who && !who.admin && (who.kind ?? "bot") === "bot" ? who.playerId : null; + if (tokenCache.size > 5000) tokenCache.clear(); + tokenCache.set(key, { playerId, exp: Date.now() + (playerId ? cfg.billing.authCacheS : 10) * 1000 }); + return playerId ?? undefined; + }; + + const submitBucket = cfg.limits.submitsPerMinutePerIp > 0 ? new Bucket(cfg.limits.submitsPerMinutePerIp, 60_000 / cfg.limits.submitsPerMinutePerIp) : undefined; + const send = (res: ServerResponse, code: number, body: unknown) => { + // one error envelope for every error, like the arena's: {error: {code, message, details}} + const b = body as { error?: unknown }; + if (b && typeof b === "object" && b.error && typeof b.error === "object" && (b.error as { details?: unknown }).details === undefined) { + (b.error as { details?: unknown }).details = {}; + } + const text = JSON.stringify(body); + res.writeHead(code, { ...CORS_HEADERS, "content-type": "application/json", "content-length": Buffer.byteLength(text) }); + res.end(text); + }; + const json = async (req: IncomingMessage, limit = 64 * 1024): Promise => { + const raw = await readBody(req, limit); + try { return raw.length ? JSON.parse(raw.toString("utf8")) : {}; } catch { throw new HttpError(400, "bad_request", "body is not JSON"); } + }; + + return createServer(async (req, res) => { + try { + const url = new URL(req.url ?? "/", "http://x"); + const path = url.pathname; + const method = req.method ?? "GET"; + + // CORS preflight: no auth (browsers never send credentials on it) + if (method === "OPTIONS") { res.writeHead(204, { ...CORS_HEADERS, "content-length": 0 }); return res.end(); } + + if (path === "/healthz") return send(res, 200, { ok: true, backend: svc.d.platinum.kind, in_flight: svc.inFlight() }); + if (path === "/readyz") { + try { await opts.ready?.(); return send(res, 200, { ok: true }); } catch (e) { return send(res, 503, { ok: false, error: String(e) }); } + } + + if (path === "/v1/webhooks/stripe" && method === "POST" && !(cfg.billing.mode === "free" && !cfg.stripe.webhookSecret)) { + const raw = await readBody(req, 1024 * 1024); + const out = await svc.stripeWebhook(raw, req.headers["stripe-signature"] as string | undefined); + return send(res, 200, { received: true, ...out }); + } + + // service token = trusted backend (any userId); in FREE mode an arena bot token = that one player, scoped to their own jobs + let player: string | undefined; + if (!authed(req)) { + player = await playerOf(req); + if (!player) return send(res, 401, { error: { code: "unauthorized", message: "bad or missing bearer token (use your arena bot token)" } }); + } + const own = (userId: string) => { if (player && player !== userId) throw new ServiceError(403, "forbidden", "not your account"); }; + + let m: RegExpMatchArray | null; + if (method === "GET" && path === "/v1/quota") return send(res, 200, await svc.quota(player ?? (url.searchParams.get("userId") ?? ""))); + if (method === "GET" && (m = path.match(/^\/v1\/credits\/([^/]+)$/))) { own(decodeURIComponent(m[1]!)); return send(res, 200, await svc.credits(decodeURIComponent(m[1]!))); } + if (method === "GET" && (m = path.match(/^\/v1\/credits\/([^/]+)\/entries$/))) { + own(decodeURIComponent(m[1]!)); + return send(res, 200, { entries: await svc.entries(decodeURIComponent(m[1]!), Number(url.searchParams.get("limit") ?? 50)) }); + } + if (method === "POST" && path === "/v1/credits/checkout") { + if (player) throw new ServiceError(403, "forbidden", "service token only"); + const s = await svc.checkout(await json(req)); + return send(res, 201, { id: s.id, url: s.url, simulated: s.simulated, price_cents: s.plan.priceCents, credit_micro: s.plan.creditMicro }); + } + if (method === "GET" && path === "/v1/quote") { + const hands = Number(url.searchParams.get("hands") ?? cfg.limits.defaultHands); + if (!Number.isInteger(hands) || hands < cfg.limits.minHands || hands > cfg.limits.maxHands) throw new ServiceError(400, "bad_request", "bad hands"); + return send(res, 200, svc.quote(hands)); + } + if (method === "POST" && path === "/v1/jobs") { + // behind our proxy chain (Cloudflare edge -> Caddy) X-Forwarded-For is the client address; the edge overwrites it + const ip = addrKey(String(req.headers["x-forwarded-for"] ?? "").split(",")[0]!.trim() || req.socket.remoteAddress || "") || undefined; + if (player && ip && submitBucket && !submitBucket.take(ip)) { + return send(res, 429, { error: { code: "rate_limited", message: "too many submits from this address; wait a minute", details: { per_minute: cfg.limits.submitsPerMinutePerIp } } }); + } + const { job, deduped } = await svc.submit(await json(req, jobBodyLimit), player, ip); + return send(res, deduped ? 200 : 202, { id: job.id, status: job.status, deduped, hands: job.input.hands, ...(player ? {} : { reserved_micro: job.reservedMicro }) }); + } + if (method === "GET" && path === "/v1/jobs") { + const userId = player ?? url.searchParams.get("userId"); + if (!userId) throw new ServiceError(400, "bad_request", "userId required"); + return send(res, 200, { jobs: (await svc.listJobs(userId, Number(url.searchParams.get("limit") ?? 20))).map(player ? publicJobView : jobView) }); + } + if (method === "GET" && (m = path.match(/^\/v1\/jobs\/([\w-]+)$/))) { + const j = await svc.getJob(m[1]!); + if (j && player && j.input.userId !== player) return send(res, 404, { error: { code: "not_found", message: "no such job" } }); + return j ? send(res, 200, player ? publicJobView(j) : jobView(j)) : send(res, 404, { error: { code: "not_found", message: "no such job" } }); + } + if (method === "GET" && (m = path.match(/^\/v1\/jobs\/([\w-]+)\/artifact$/))) { + if (player) throw new ServiceError(403, "forbidden", "service token only"); + const tgz = await svc.getArtifact(m[1]!); + if (!tgz) return send(res, 404, { error: { code: "not_found", message: "no artifact for this job" } }); + res.writeHead(200, { ...CORS_HEADERS, "content-type": "application/gzip", "content-length": tgz.length }); + return res.end(Buffer.from(tgz)); + } + if (method === "POST" && (m = path.match(/^\/v1\/jobs\/([\w-]+)\/abort$/))) { + if (player) { const j = await svc.getJob(m[1]!); if (!j || j.input.userId !== player) return send(res, 404, { error: { code: "not_found", message: "no such job" } }); } + const aborted = await svc.abort(m[1]!); + if (!aborted) throw new ServiceError(409, "job_not_abortable", "the job is already over (finished, failed or aborted)"); + return send(res, 202, { ok: true, aborted }); + } + return send(res, 404, { error: { code: "not_found", message: `no such route: ${method} ${path}` } }); + } catch (e) { + if (e instanceof ServiceError) return send(res, e.status, { error: { code: e.code, message: e.message, ...(e.details ? { details: e.details } : {}) } }); + if (e instanceof HttpError) return send(res, e.status, { error: { code: e.code, message: e.message } }); + opts.log?.("request_failed", { error: String((e as Error)?.stack ?? e) }); + return send(res, 500, { error: { code: "internal", message: "internal error" } }); + } + }); +} diff --git a/deploy/platinum/runner/src/archive.ts b/deploy/platinum/runner/src/archive.ts new file mode 100644 index 00000000..517188e8 --- /dev/null +++ b/deploy/platinum/runner/src/archive.ts @@ -0,0 +1,124 @@ +// Cheap pre-flight look inside a bot upload: is it a gzip tar, and are the files the job needs in it? Streams the +// decompression (never buffers the unpacked archive), reads only tar headers, and stops as soon as everything wanted was +// seen or `maxBytes` of tar data went by. When the answer is not cheap to get we say "unknown" and let the sandbox decide. +import { createGunzip } from "node:zlib"; + +/** The upload is not a gzip tarball (or is corrupt). A 400 for the caller. */ +export class ArchiveError extends Error {} + +export interface ArchiveScan { + /** Wanted paths that are definitely not in the archive. Empty when the scan could not finish (see `complete`). */ + missing: string[]; + /** The whole archive was walked. false = stopped early because the answer was already known or it was too big to scan. */ + complete: boolean; +} + +const normName = (n: string): string => n.replace(/^(\.\/)+/, "").replace(/\/+$/, ""); +const cstr = (b: Buffer, from: number, len: number): string => { + const s = b.subarray(from, from + len); + const z = s.indexOf(0); + return s.subarray(0, z < 0 ? s.length : z).toString("utf8"); +}; +const octal = (b: Buffer, from: number, len: number): number => { + if (b[from]! & 0x80) { let v = 0; for (let i = from + 1; i < from + len; i++) v = v * 256 + b[i]!; return v; } // base-256 (huge files) + const t = cstr(b, from, len).trim(); + return t === "" ? 0 : /^[0-7]+$/.test(t) ? parseInt(t, 8) : NaN; +}; +const checksumOk = (h: Buffer): boolean => { + let sum = 0; + for (let i = 0; i < 512; i++) sum += i >= 148 && i < 156 ? 32 : h[i]!; + return sum === octal(h, 148, 8); +}; +const pax = (data: Buffer): string | undefined => { + let p = 0; + while (p < data.length) { + const sp = data.indexOf(32, p); + if (sp < 0) break; + const len = Number(data.subarray(p, sp).toString()); + if (!Number.isInteger(len) || len <= 0) break; + const rec = data.subarray(sp + 1, p + len - 1).toString("utf8"); + if (rec.startsWith("path=")) return rec.slice(5); + p += len; + } + return undefined; +}; + +export async function scanTgz(tgz: Uint8Array, wanted: string[], opts: { maxBytes?: number } = {}): Promise { + if (tgz.length < 2 || tgz[0] !== 0x1f || tgz[1] !== 0x8b) throw new ArchiveError("the artifact is not a gzip tarball (.tar.gz)"); + const maxBytes = opts.maxBytes ?? 128 * 1024 * 1024; + const want = new Set(wanted.map(normName)); + const found = new Set(); + let buf: Buffer = Buffer.alloc(0); + let skip = 0; + let collect: { kind: "L" | "x"; size: number; pad: number } | undefined; + let longName: string | undefined; + let paxPath: string | undefined; + let first = true; + let total = 0; + let complete = false; // reached the end-of-archive marker + let unknown = false; // gave up: too big or unparseable header after the first + + const done = () => unknown || complete || [...want].every((w) => found.has(w)); + + const feed = (chunk: Buffer): void => { + total += chunk.length; + if (total > maxBytes) { unknown = true; return; } + buf = buf.length ? Buffer.concat([buf, chunk]) : chunk; + for (;;) { + if (skip > 0) { + const take = Math.min(skip, buf.length); + buf = buf.subarray(take); skip -= take; + if (skip > 0) return; + } + if (collect) { + if (buf.length < collect.size + collect.pad) return; + const content = buf.subarray(0, collect.size); + buf = buf.subarray(collect.size + collect.pad); + if (collect.kind === "L") longName = cstr(content, 0, content.length); + else paxPath = pax(content); + collect = undefined; + continue; + } + if (buf.length < 512) return; + const h = buf.subarray(0, 512); + buf = buf.subarray(512); + if (h.every((x) => x === 0)) { complete = true; return; } + if (!checksumOk(h)) { + if (first) throw new ArchiveError("the artifact is a gzip file but not a tar archive"); + unknown = true; return; + } + first = false; + const type = String.fromCharCode(h[156] || 48); + const size = octal(h, 124, 12); + if (!Number.isFinite(size)) { unknown = true; return; } + const pad = (512 - (size % 512)) % 512; + if (type === "L" || type === "x") { + if (size > 64 * 1024) { unknown = true; return; } + collect = { kind: type, size, pad }; + continue; + } + if (type === "g" || type === "K") { skip = size + pad; continue; } + let name = cstr(h, 0, 100); + if (cstr(h, 257, 5) === "ustar") { const prefix = cstr(h, 345, 155); if (prefix) name = `${prefix}/${name}`; } + name = longName ?? paxPath ?? name; + longName = paxPath = undefined; + if (type !== "5") found.add(normName(name)); + if (done()) return; + skip = size + pad; + } + }; + + const gz = createGunzip(); + try { + gz.end(Buffer.from(tgz.buffer, tgz.byteOffset, tgz.byteLength)); + for await (const chunk of gz) { feed(chunk as Buffer); if (done()) break; } + if (!done()) complete = true; // stream ended: we saw everything there is + } catch (e) { + if (e instanceof ArchiveError) throw e; + throw new ArchiveError(`the artifact is not a valid gzip file: ${String((e as Error).message).slice(0, 120)}`); + } finally { + gz.destroy(); + } + const sawAll = complete && !unknown; + return { missing: sawAll ? [...want].filter((w) => !found.has(w)) : [], complete: sawAll }; +} diff --git a/deploy/platinum/runner/src/arena.ts b/deploy/platinum/runner/src/arena.ts new file mode 100644 index 00000000..d02a2183 --- /dev/null +++ b/deploy/platinum/runner/src/arena.ts @@ -0,0 +1,114 @@ +// Arena REST client (docs/TABLE_API.md 12b items 11-16, arena/server/README.md). +// +// Auth model used by the runner: +// * ARENA_RUNNER_TOKEN: start/abort hosted (verified) benchmark runs, attest hosted bots, POST signed worker results. +// It is NOT an admin token: the arena answers 403 to the runner everywhere else. +// * bot registration needs no token while ARENA_OPEN_REGISTRATION=true; set ARENA_ADMIN_TOKEN on the runner only if +// registration is closed. +import type { Config } from "./config.ts"; + +export interface BenchRun { + run_id: string; + track: string; + player_id: string; + match_id?: string; + status: "running" | "finished" | "aborted" | string; + verified: boolean; + hosted?: boolean; + hands_planned?: number; + hands_total?: number; + hands_done: number; + mbb_per_game: number | null; + ci95_mbb: number | null; + running_mbb_per_game?: number | null; + running_ci95_mbb?: number | null; + method?: string | null; +} + +/** The arena's answer to POST /v1/results (worker mode). Fields are read leniently; see worker.ts. */ +export interface ResultAck { + run_id?: string; + verified?: boolean; + status?: string; + hands_done?: number; + hands?: number; + mbb_per_game?: number | null; + ci95_mbb?: number | null; + [k: string]: unknown; +} + +export class ArenaError extends Error { + status: number; + code: string; + constructor(status: number, code: string, message: string) { + super(`arena ${status} ${code}: ${message}`); + this.status = status; + this.code = code; + } +} + +export class ArenaClient { + private readonly cfg: Config["arena"]; + private readonly doFetch: typeof fetch; + + constructor(cfg: Config["arena"], doFetch: typeof fetch = fetch) { + this.cfg = cfg; + this.doFetch = doFetch; + } + + /** Whose bot token is this? Calls GET /v1/me with the player's own token. Returns undefined for an unknown token. */ + async whoami(token: string): Promise<{ playerId: string; name: string; admin: boolean; kind?: string } | undefined> { + const r = await this.doFetch(new URL("/v1/me", this.cfg.url), { headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(10_000) }); + if (r.status === 401 || r.status === 403) return undefined; + if (!r.ok) throw new ArenaError(r.status, "whoami_failed", `GET /v1/me -> ${r.status}`); + const j = (await r.json()) as { player_id?: string; name?: string; admin?: boolean; kind?: string }; + if (!j.player_id) return undefined; + return { playerId: j.player_id, name: j.name ?? "", admin: j.admin === true, ...(j.kind ? { kind: j.kind } : {}) }; + } + + private async call(method: string, path: string, token: string | undefined, body?: string | Uint8Array | object): Promise { + const raw = body === undefined ? undefined : typeof body === "string" || body instanceof Uint8Array ? body : JSON.stringify(body); + const res = await this.doFetch(new URL(path, this.cfg.url), { + method, + headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) }, + body: raw as BodyInit | undefined, + signal: AbortSignal.timeout(30_000), + }); + const text = await res.text(); + let json: any = {}; + try { json = text ? JSON.parse(text) : {}; } catch { json = { error: { message: text.slice(0, 200) } }; } + if (!res.ok) throw new ArenaError(res.status, json?.error?.code ?? json?.code ?? "error", json?.error?.message ?? json?.message ?? text.slice(0, 200)); + return json as T; + } + + /** A fresh bot identity for one job. The token is shown once. */ + async registerBot(name: string, owner: string): Promise<{ playerId: string; token: string }> { + const r = await this.call<{ player_id: string; token: string }>("POST", "/v1/bots", this.cfg.adminToken, { name, kind: "bot", owner }); + return { playerId: r.player_id, token: r.token }; + } + + /** Connect mode: start the hosted run for a bot that is already connected to /v1/play. 409 not_connected until it is. */ + startHostedRun(track: string, playerId: string, opts: { hands: number; lanes?: number }): Promise { + return this.call("POST", `/v1/benchmarks/${encodeURIComponent(track)}/runs`, this.cfg.runnerToken, { + player_id: playerId, hands: opts.hands, lanes: opts.lanes, hosted: true, + }); + } + + getRun(track: string, runId: string): Promise { + return this.call("GET", `/v1/benchmarks/${encodeURIComponent(track)}/runs/${encodeURIComponent(runId)}`, undefined); + } + + abortRun(track: string, runId: string): Promise { + return this.call("POST", `/v1/benchmarks/${encodeURIComponent(track)}/runs/${encodeURIComponent(runId)}/abort`, this.cfg.runnerToken, {}); + } + + /** Worker mode: submit the worker's signed result.json verbatim (the signature covers the exact bytes). */ + postResult(signedBody: string | Uint8Array): Promise { + return this.call("POST", "/v1/results", this.cfg.runnerToken, signedBody); + } + + async tracks(): Promise> { + const r = await this.call("GET", "/v1/benchmarks", undefined); + return (Array.isArray(r) ? r : (r as { tracks?: unknown[] }).tracks ?? []) as Array<{ track?: string; id?: string; available?: boolean }>; + } +} diff --git a/deploy/platinum/runner/src/config.ts b/deploy/platinum/runner/src/config.ts new file mode 100644 index 00000000..08749cd6 --- /dev/null +++ b/deploy/platinum/runner/src/config.ts @@ -0,0 +1,241 @@ +// Runner configuration. Everything comes from env; `loadConfig(env)` is pure so tests pass their own. +// +// Required in every mode: RUNNER_AUTH_TOKEN, ARENA_URL, ARENA_RUNNER_TOKEN, STRIPE_WEBHOOK_SECRET +// Required with Postgres: RUNNER_DATABASE_URL (or DATABASE_URL) (RUNNER_STORAGE=memory for throwaway runs) +// Required on Platinum: PT_TOKEN (SANDBOX_BACKEND=platinum, the default) +// Required locally: SANDBOX_BACKEND=local, LOCAL_BOT_IMAGE, LOCAL_BOT_NETWORK, a container engine socket + +export type Env = Record; +export type JobMode = "worker" | "connect"; + +export interface CreditPack { id: string; priceUsd: number; creditUsd: number; label: string } + +export interface Config { + backend: "platinum" | "local"; + host: string; + port: number; + authToken: string; + /** + * BILLING_MODE=paid (default): credits are reserved/settled in the ledger, Stripe tops them up. + * BILLING_MODE=free: jobs cost nothing; per-player quotas apply; public players authenticate with their ARENA bot token + * (validated against GET /v1/me on the arena). RUNNER_AUTH_TOKEN stays the trusted service token. + */ + billing: { mode: "paid" | "free"; freeMaxHandsPerDay: number; freeMaxConcurrent: number; freeMaxConcurrentPerIp: number; authCacheS: number }; + storage: "postgres" | "memory"; + databaseUrl?: string; + + arena: { + url: string; // runner -> arena + botUrl: string; // what a sandboxed bot connects to (connect mode); defaults to `url` + runnerToken: string; // ARENA_RUNNER_TOKEN: may start/attest hosted runs and POST worker results + adminToken?: string; // only if the arena has ARENA_OPEN_REGISTRATION=false + }; + + platinum: { apiUrl: string; token?: string; region?: string; botTemplate: string }; + + local: { + engineHost: string; // unix:///path/to/docker-compatible.sock | tcp://host:port + botImage: string; + network: string; // sandbox network (should be `internal` so it can reach only the arena) + egressNetwork?: string; // joined temporarily for `pip install` + binds: string[]; // extra bind mounts, "host:container[:ro]" (e.g. the test blueprint) + pidsLimit: number; + apparmor?: string; // AppArmor profile for the sandboxes (deploy/production/apparmor/sharingan-sandbox) + }; + + sandbox: { cpu: number; ramMb: number; diskGb: number; autoStopMinutes: number }; + + worker: { + defaultMode: JobMode; + /** Shell command run inside the sandbox in worker mode. Placeholders are shell-quoted by the runner. */ + cmdTemplate: string; + /** Per language: the `--bot` command the worker spawns (the user's entry file path is appended). */ + pipeCmd: { python: string; typescript?: string }; + env: Record; // extra env for the worker process (ARENA_BLUEPRINT=..., etc.) + keyId?: string; // id of the arena's ARENA_WORKER_KEYS entry (`id=secret`) + signKey?: string; // the secret; written (as `id=secret`) to a root-only --sign-key-file inside the sandbox for the run + resultPath: string; + /** Public (player) submits may carry a requirements file (installed in a short network window). Off until that install runs unprivileged. */ + publicRequirements: boolean; + }; + + limits: { + submitsPerMinutePerIp: number; // public submits per client address per minute (0 = no limit) + maxArtifactBytes: number; + runDeadlineS: number; + connectTimeoutS: number; + pollIntervalMs: number; + pollFailureLimit: number; + maxConcurrentRuns: number; + minHands: number; + maxHands: number; + defaultHands: number; + defaultLanes: number; + maxLanes: number; + }; + + pricing: { + usdPerKHands: number; // THE price: credits charged per 1,000 hands played + minChargeUsd: number; // floor for a job that played at least one hand + failedBotChargeUsd: number; // flat charge when the user's bot made the run fail before any result (0 = free) + // COGS model, only used to record cost/margin per job (not billed): + usdPerVcpuSecond: number; + usdPerGibSecond: number; + usdPerHandArenaShare: number; + }; + + stripe: { + webhookSecret: string; + secretKey?: string; // unset = simulated checkout (no network) + apiBase: string; + publicBaseUrl: string; // where Checkout returns the player + toleranceS: number; + packs: CreditPack[]; + minTopupUsd: number; + maxTopupUsd: number; + }; +} + +function bad(msg: string): never { throw new Error(`config: ${msg}`); } + +export function loadConfig(env: Env = process.env): Config { + const str = (k: string, d?: string): string | undefined => (env[k] !== undefined && env[k] !== "" ? env[k] : d); + const req = (k: string): string => str(k) ?? bad(`missing env ${k}`); + const num = (k: string, d: number): number => { + const raw = str(k); + if (raw === undefined) return d; + const n = Number(raw); + if (!Number.isFinite(n)) bad(`${k} must be a number, got ${raw}`); + return n; + }; + const bool = (k: string, d: boolean): boolean => { + const raw = str(k); + if (raw === undefined) return d; + if (!/^(true|false|1|0)$/i.test(raw)) bad(`${k} must be true or false, got ${raw}`); + return /^(true|1)$/i.test(raw); + }; + const json = (k: string, d: T): T => { + const raw = str(k); + if (raw === undefined) return d; + try { return JSON.parse(raw) as T; } catch { return bad(`${k} must be JSON`); } + }; + + const backend = (str("SANDBOX_BACKEND", "platinum") as string); + if (backend !== "platinum" && backend !== "local") bad("SANDBOX_BACKEND must be platinum|local"); + const storage = (str("RUNNER_STORAGE", "postgres") as string); + if (storage !== "postgres" && storage !== "memory") bad("RUNNER_STORAGE must be postgres|memory"); + const databaseUrl = str("RUNNER_DATABASE_URL") ?? str("DATABASE_URL"); + if (storage === "postgres" && !databaseUrl) bad("missing env RUNNER_DATABASE_URL (or RUNNER_STORAGE=memory)"); + if (backend === "platinum" && !str("PT_TOKEN")) bad("missing env PT_TOKEN (or SANDBOX_BACKEND=local)"); + const defaultMode = (str("DEFAULT_JOB_MODE", "worker") as string); + if (defaultMode !== "worker" && defaultMode !== "connect") bad("DEFAULT_JOB_MODE must be worker|connect"); + + const billingMode = str("BILLING_MODE", "paid") as string; + if (billingMode !== "paid" && billingMode !== "free") bad("BILLING_MODE must be paid|free"); + const arenaUrl = req("ARENA_URL"); + const packs = json>("CREDIT_PACKS", [ + { id: "starter", price_usd: 10, credit_usd: 10, label: "$10" }, + { id: "plus", price_usd: 50, credit_usd: 55, label: "$50 (+10%)" }, + { id: "pro", price_usd: 200, credit_usd: 240, label: "$200 (+20%)" }, + ]).map((p) => ({ id: p.id, priceUsd: p.price_usd, creditUsd: p.credit_usd, label: p.label ?? p.id })); + + return { + backend: backend as Config["backend"], + host: str("HOST", "0.0.0.0") as string, + port: num("PORT", 8090), + authToken: req("RUNNER_AUTH_TOKEN"), + billing: { + mode: billingMode, + freeMaxHandsPerDay: num("FREE_MAX_HANDS_PER_DAY", 1_000_000), + freeMaxConcurrent: num("FREE_MAX_CONCURRENT_JOBS", 2), + // per client address across all its bots (0 = off): one person cannot fill the queue by minting bots + freeMaxConcurrentPerIp: num("FREE_MAX_CONCURRENT_JOBS_PER_IP", 0), + authCacheS: num("ARENA_AUTH_CACHE_S", 60), + }, + storage: storage as Config["storage"], + databaseUrl, + + arena: { + url: arenaUrl, + botUrl: str("ARENA_BOT_URL", arenaUrl) as string, + runnerToken: req("ARENA_RUNNER_TOKEN"), + adminToken: str("ARENA_ADMIN_TOKEN"), + }, + + platinum: { + apiUrl: str("PT_API_URL", "https://api.platinum.dev") as string, + token: str("PT_TOKEN"), + region: str("PT_REGION"), + botTemplate: str("BOT_TEMPLATE", "sharingan-bot-0-1-0") as string, + }, + + local: { + engineHost: str("CONTAINER_HOST", "unix:///var/run/engine.sock") as string, + botImage: str("LOCAL_BOT_IMAGE", str("BOT_TEMPLATE", "localhost/sharingan-bot:local")) as string, + network: str("LOCAL_BOT_NETWORK", "sharingan-botnet") as string, + egressNetwork: str("LOCAL_EGRESS_NETWORK"), + binds: (str("LOCAL_SANDBOX_BINDS", "") as string).split(",").map((s) => s.trim()).filter(Boolean), + pidsLimit: num("LOCAL_PIDS_LIMIT", 512), + apparmor: str("LOCAL_SANDBOX_APPARMOR"), + }, + + sandbox: { + cpu: num("BOT_CPU", 2), + ramMb: num("BOT_RAM_MB", 2048), + diskGb: num("BOT_DISK_GB", 5), + autoStopMinutes: num("BOT_AUTO_STOP_MINUTES", 30), + }, + + worker: { + defaultMode: defaultMode as JobMode, + cmdTemplate: str( + "WORKER_CMD_TEMPLATE", + "sharingan-arena run --bot {bot} --track {track} --hands {hands} --lanes {lanes} --out {out} --sign-key-file {keyfile} --player-id {player_id} --seed-file {seedfile}", + ) as string, + pipeCmd: { + python: str("PIPE_CMD_PYTHON", "sharingan pipe") as string, + typescript: str("PIPE_CMD_TYPESCRIPT"), + }, + env: json>("WORKER_ENV_JSON", {}), + keyId: str("WORKER_KEY_ID"), + signKey: str("WORKER_SIGN_KEY"), + resultPath: str("WORKER_RESULT_PATH", "/work/result.json") as string, + publicRequirements: bool("PUBLIC_REQUIREMENTS", false), + }, + + limits: { + maxArtifactBytes: num("MAX_ARTIFACT_BYTES", 8 * 1024 * 1024), + runDeadlineS: num("RUN_DEADLINE_S", 3 * 3600), + connectTimeoutS: num("CONNECT_TIMEOUT_S", 60), + pollIntervalMs: num("POLL_INTERVAL_MS", 2000), + pollFailureLimit: num("POLL_FAILURE_LIMIT", 8), + maxConcurrentRuns: num("MAX_CONCURRENT_RUNS", 8), + minHands: num("MIN_HANDS", 600), + submitsPerMinutePerIp: num("SUBMITS_PER_MINUTE_PER_IP", 0), + maxHands: num("MAX_HANDS", 200_000), + defaultHands: num("DEFAULT_HANDS", 20_000), + defaultLanes: num("DEFAULT_LANES", 1), + maxLanes: num("MAX_LANES", 8), + }, + + pricing: { + usdPerKHands: num("PRICE_USD_PER_1K_HANDS", 0.05), + minChargeUsd: num("MIN_JOB_CHARGE_USD", 0), + failedBotChargeUsd: num("FAILED_BOT_CHARGE_USD", 0), + usdPerVcpuSecond: num("USD_PER_VCPU_SECOND", 0.0000125), + usdPerGibSecond: num("USD_PER_GIB_SECOND", 0.000003), + usdPerHandArenaShare: num("USD_PER_HAND_ARENA_SHARE", 0.0000025), + }, + + stripe: { + webhookSecret: billingMode === "free" ? (str("STRIPE_WEBHOOK_SECRET") ?? "") : req("STRIPE_WEBHOOK_SECRET"), + secretKey: str("STRIPE_SECRET_KEY"), + apiBase: str("STRIPE_API_BASE", "https://api.stripe.com") as string, + publicBaseUrl: str("PUBLIC_BASE_URL", "http://localhost:3000") as string, + toleranceS: num("STRIPE_TOLERANCE_S", 300), + packs, + minTopupUsd: num("MIN_TOPUP_USD", 5), + maxTopupUsd: num("MAX_TOPUP_USD", 1000), + }, + }; +} diff --git a/deploy/platinum/runner/src/cost.ts b/deploy/platinum/runner/src/cost.ts new file mode 100644 index 00000000..9bd3d575 --- /dev/null +++ b/deploy/platinum/runner/src/cost.ts @@ -0,0 +1,60 @@ +// Pricing and cost metering. +// +// PRICE (what the player pays): credits per hand played. `PRICE_USD_PER_1K_HANDS`, integer micro-USD per job. +// reserve = price of the hands requested (rounded up to whole deals), charged = price of hands actually played. +// COGS (what the job cost us, recorded for margin, never billed): sandbox seconds x shape x our Platinum rates, +// max'ed with Platinum's own number read just before delete, plus an amortised per-hand share of the fixed +// arena / bigmem host. +// +// Why we meter COGS ourselves instead of trusting Platinum's number: GET /v1/sandboxes/:id/usage 404s once the sandbox +// is deleted (apps/api/src/api/sandboxes.ts:5640-5643) and Platinum settles usage in 60 s cycles, so a short run may +// under-report right before delete. +import type { Config } from "./config.ts"; +import { usdToMicro } from "./money.ts"; + +export type Pricing = Config["pricing"]; + +/** Deals are 6 hands (one per rotation); the arena rounds a request up to a multiple of 6. */ +export const roundHands = (hands: number): number => Math.ceil(hands / 6) * 6; + +export function pricePerHandMicro(p: Pricing): number { + return (p.usdPerKHands * 1_000_000) / 1000; +} + +/** What to hold before the job starts: the price of every hand we might be asked to play. */ +export function reserveMicro(p: Pricing, handsRequested: number): number { + return Math.max(usdToMicro(p.minChargeUsd), Math.ceil(roundHands(handsRequested) * pricePerHandMicro(p))); +} + +/** What to charge once the job settled. `handsPlayed` comes from the arena (authoritative), never from the bot. */ +export function chargeMicro(p: Pricing, handsPlayed: number): number { + if (!(handsPlayed > 0)) return 0; + return Math.max(usdToMicro(p.minChargeUsd), Math.round(handsPlayed * pricePerHandMicro(p))); +} + +export interface CogsInput { + cpu: number; + ramMb: number; + seconds: number; // sandbox running time + handsPlayed: number; + platinumUsd?: number; // from sandbox.usage(), if parsable +} + +export function platinumUsdFromUsage(u: Record | undefined): number | undefined { + if (!u) return undefined; + for (const k of ["cost_usd", "total_cost_usd", "cost", "total_usd"]) { + const v = u[k]; + if (typeof v === "number" && Number.isFinite(v)) return v; + } + return undefined; +} + +export function sandboxCogsUsd(p: Pricing, i: CogsInput): number { + const local = i.seconds * (i.cpu * p.usdPerVcpuSecond + (i.ramMb / 1024) * p.usdPerGibSecond); + return Math.max(local, i.platinumUsd ?? 0); +} + +/** Our cost for the job, micro-USD. */ +export function cogsMicro(p: Pricing, i: CogsInput): number { + return usdToMicro(sandboxCogsUsd(p, i) + i.handsPlayed * p.usdPerHandArenaShare); +} diff --git a/deploy/platinum/runner/src/db.ts b/deploy/platinum/runner/src/db.ts new file mode 100644 index 00000000..d65f0d06 --- /dev/null +++ b/deploy/platinum/runner/src/db.ts @@ -0,0 +1,114 @@ +// Postgres plumbing: pool + forward-only migrations (own database/schema, separate from the arena's). +import pg from "pg"; + +export type Pool = pg.Pool; +export type Client = pg.PoolClient; + +export function createPool(connectionString: string, opts: { schema?: string } = {}): Pool { + // int8 (bigint) comes back as a JS number: micro-USD amounts stay far below 2^53. + pg.types.setTypeParser(20, (v: string) => Number(v)); + return new pg.Pool({ + connectionString, + max: Number(process.env.RUNNER_DB_POOL ?? 8), + ...(opts.schema ? { options: `-c search_path=${opts.schema}` } : {}), + }); +} + +export async function tx(pool: Pool, fn: (c: Client) => Promise): Promise { + const c = await pool.connect(); + try { + await c.query("BEGIN"); + const out = await fn(c); + await c.query("COMMIT"); + return out; + } catch (e) { + await c.query("ROLLBACK").catch(() => {}); + throw e; + } finally { + c.release(); + } +} + +const MIGRATIONS: Array<{ version: number; name: string; sql: string }> = [ + { + version: 1, + name: "ledger-and-jobs", + sql: ` + CREATE TABLE credit_accounts ( + user_id text PRIMARY KEY, + balance_micro bigint NOT NULL DEFAULT 0 CHECK (balance_micro >= 0), -- spendable + reserved_micro bigint NOT NULL DEFAULT 0 CHECK (reserved_micro >= 0), -- held for jobs in flight + created_at timestamptz NOT NULL DEFAULT now() + ); + -- append-only audit trail; amount_micro is a magnitude, direction is implied by kind + CREATE TABLE credit_entries ( + id bigserial PRIMARY KEY, + user_id text NOT NULL REFERENCES credit_accounts(user_id), + kind text NOT NULL CHECK (kind IN ('topup','reserve','settle','release')), + amount_micro bigint NOT NULL CHECK (amount_micro >= 0), + ref text NOT NULL, + idempotency_key text NOT NULL UNIQUE, + meta jsonb NOT NULL DEFAULT '{}'::jsonb, + created_at timestamptz NOT NULL DEFAULT now() + ); + CREATE INDEX credit_entries_user ON credit_entries(user_id, id DESC); + CREATE TABLE credit_reservations ( + key text PRIMARY KEY, + user_id text NOT NULL REFERENCES credit_accounts(user_id), + amount_micro bigint NOT NULL CHECK (amount_micro >= 0), + state text NOT NULL CHECK (state IN ('held','settled')), + charged_micro bigint, + created_at timestamptz NOT NULL DEFAULT now(), + settled_at timestamptz + ); + CREATE INDEX credit_reservations_held ON credit_reservations(created_at) WHERE state = 'held'; + CREATE TABLE jobs ( + id text PRIMARY KEY, + idempotency_key text NOT NULL UNIQUE, + user_id text NOT NULL, + status text NOT NULL, + settled boolean NOT NULL DEFAULT false, + doc jsonb NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now() + ); + CREATE INDEX jobs_user ON jobs(user_id, created_at DESC); + CREATE INDEX jobs_open ON jobs(status, settled); + `, + }, + { + version: 2, + name: "job_artifacts", + sql: ` + CREATE TABLE job_artifacts ( + job_id text PRIMARY KEY REFERENCES jobs(id) ON DELETE CASCADE, + tgz bytea NOT NULL, + created_at timestamptz NOT NULL DEFAULT now() + ); + `, + }, +]; + +export async function migrate(pool: Pool): Promise { + const c = await pool.connect(); + try { + await c.query("SELECT pg_advisory_lock(7351001)"); + await c.query("CREATE TABLE IF NOT EXISTS runner_migrations (version int PRIMARY KEY, name text NOT NULL, applied_at timestamptz NOT NULL DEFAULT now())"); + const done = new Set((await c.query("SELECT version FROM runner_migrations")).rows.map((r: { version: number }) => r.version)); + for (const m of MIGRATIONS) { + if (done.has(m.version)) continue; + await c.query("BEGIN"); + try { + await c.query(m.sql); + await c.query("INSERT INTO runner_migrations(version, name) VALUES ($1, $2)", [m.version, m.name]); + await c.query("COMMIT"); + } catch (e) { + await c.query("ROLLBACK"); + throw e; + } + } + } finally { + await c.query("SELECT pg_advisory_unlock(7351001)").catch(() => {}); + c.release(); + } +} diff --git a/deploy/platinum/runner/src/job.ts b/deploy/platinum/runner/src/job.ts new file mode 100644 index 00000000..b6c02e43 --- /dev/null +++ b/deploy/platinum/runner/src/job.ts @@ -0,0 +1,439 @@ +// One eval job = one sandbox = one benchmark result. Credits are NOT touched here (service.ts reserves before and settles +// after); this module only runs the job, records what happened on the Job document, and always tears the sandbox down. +// +// Two modes (Job.input.mode): +// +// worker (default, scales) the sandbox runs the MATCH WORKER: `sharingan-arena run --bot "" ...` plays the +// whole benchmark in-process against the house bots, the user's bot is a stdin/stdout +// subprocess (`sharingan pipe bot.py`, uid 10002). The sandbox has NO network. The worker signs +// result.json (HMAC, key written into the sandbox for the run, readable by root only); the runner +// reads it back and POSTs it to the arena (POST /v1/results), which checks the signature against +// ARENA_WORKER_KEYS and the frozen panel / seed and stores the run as verified. +// connect (remote-bot path) the sandbox runs `sharingan connect` (a WebSocket client of /v1/play); the runner registers a +// bot identity, starts the benchmark run with the RUNNER token + hosted:true (verified) and +// polls progress. Slower (network round trip per decision) but needs no worker support. +// +// Steps (each names the sandbox / arena call): +// 1 provisioning arena POST /v1/bots fresh bot identity (+ token, connect mode) for this job, +// unless a public player submitted with their own token (then the run is theirs) +// 2 sandbox create from the bot template, egress locked down +// 3 upload artifact (writeFile + tar), optional pip install, then drop PyPI from the allowlist +// 4 running worker: start worker, wait for exit, read result.json, POST /v1/results +// connect: start launcher, POST /v1/benchmarks/{track}/runs (retry 409 not_connected), poll +// 5 finalizing usage(), delete() in `finally`, meter COGS +import { randomBytes } from "node:crypto"; +import type { ArenaClient, BenchRun, ResultAck } from "./arena.ts"; +import { ArenaError } from "./arena.ts"; +import type { Config } from "./config.ts"; +import { cogsMicro, platinumUsdFromUsage } from "./cost.ts"; +import { cleanLog } from "./logclean.ts"; +import type { Logger } from "./log.ts"; +import type { PlatinumClient, ProcessHandle, Sandbox } from "./platinum/types.ts"; +import { sleep } from "./platinum/types.ts"; +import type { ErrorClass, Job, JobStore } from "./store.ts"; + +export interface JobDeps { + cfg: Config; + platinum: PlatinumClient; + arena: ArenaClient; + store: JobStore; + log: Logger; + sleep?: (ms: number, signal?: AbortSignal) => Promise; +} + +/** An error with a verdict: whose fault is the failure. */ +export class JobFailure extends Error { + cls: ErrorClass; + constructor(cls: ErrorClass, message: string) { super(message); this.cls = cls; } +} +class AbortedError extends Error {} + +const PYPI_HOSTS = ["pypi.org", "files.pythonhosted.org"]; +const BOT_DIR = "/opt/sharingan/bot"; +/** pip --target for the bot's requirements; on PYTHONPATH. Installed as BOT_UID, then root-owned and read-only. */ +const DEPS_DIR = "/opt/sharingan/deps"; +/** pip's working copy of the bot directory (owned by BOT_UID; removed with everything else of that user by sharingan-scrub). */ +const PIP_SRC = "/tmp/pip-src"; +const BOT_UID = 10002; +/** The worker runs rotation r of the duplicate deals as uid ROTATION_UIDS[r] and wipes it before the next (sharingan-scrub). */ +export const ROTATION_UIDS = [10010, 10011, 10012, 10013, 10014, 10015]; +/** + * Access times of the bot's (root-owned, read-only) files set far ahead: under relatime a read then never moves them, so + * which files a rotation read is no mark the next rotation could see. (podman's tmpfs takes no noatime.) + */ +const futureAtime = (dir: string): string => `find -P ${dir} -exec touch -a -h -d 2099-01-01 {} +`; +/** Become BOT_UID with no capabilities at all (permitted, inheritable, ambient, bounding). */ +const DROP = `setpriv --reuid=${BOT_UID} --regid=${BOT_UID} --clear-groups --inh-caps=-all --bounding-set=-all`; +const KEY_PATH = "/opt/sharingan/worker.key"; +/** Per-job secret deal seed, same protection as the key: root-only, never in the bot's env or args. */ +export const SEED_PATH = "/opt/sharingan/run.seed"; +const BOT_ENV = `HOME=/tmp PATH=/usr/local/bin:/usr/bin:/bin PYTHONPATH=${DEPS_DIR} PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1`; + +export const shq = (s: string): string => `'${s.replace(/'/g, `'\\''`)}'`; + +/** Fill `{name}` placeholders with shell-quoted values. Unknown placeholders are an error (a typo must not run). */ +export function renderCommand(template: string, vars: Record): string { + return template.replace(/\{(\w+)\}/g, (_m, k: string) => { + const v = vars[k]; + if (v === undefined) throw new JobFailure("infra", `worker command template uses {${k}}, which is not available`); + return shq(String(v)); + }); +} + +export function botCommand(cfg: Config, input: Job["input"]): string { + const pipe = input.language === "python" ? cfg.worker.pipeCmd.python : cfg.worker.pipeCmd.typescript; + if (!pipe) throw new JobFailure("infra", `worker mode has no pipe command for ${input.language} (set PIPE_CMD_${input.language.toUpperCase()})`); + const entry = `${BOT_DIR}/${input.entry}`; + // no setpriv here: the worker runs each rotation as its own uid (--rotation-uids) + return `env -i ${BOT_ENV} ${pipe} ${shq(entry)}`; +} + +/** Best-effort progress from worker output: a JSON line carrying hands_done/hands_total, or "N/M hands". */ +export function parseProgress(text: string): { done: number; total: number } | undefined { + const lines = text.split("\n").slice(-40).reverse(); + for (const line of lines) { + const t = line.trim(); + if (t.startsWith("{")) { + try { + const j = JSON.parse(t); + const done = Number(j.hands_done ?? j.data?.hands_done); + const total = Number(j.hands_total ?? j.data?.hands_total ?? j.hands_planned); + if (Number.isFinite(done) && Number.isFinite(total) && total > 0) return { done, total }; + } catch { /* not json */ } + } + // only short lines: the worker's progress line is short, and a long digit run (a bot can print anything to its + // stderr, which ends up in this log) would make the regex crawl + const m = t.length <= 200 ? t.match(/(\d+)\s*\/\s*(\d+)\s*hands/i) : null; + if (m) return { done: Number(m[1]), total: Number(m[2]) }; + } + return undefined; +} + +const pickNum = (o: Record, keys: string[]): number | undefined => { + for (const k of keys) if (typeof o[k] === "number" && Number.isFinite(o[k] as number)) return o[k] as number; + return undefined; +}; + +export async function executeJob(deps: JobDeps, jobId: string, artifact: Uint8Array, ac: AbortController): Promise { + const { cfg, platinum, arena, store, log } = deps; + const nap = deps.sleep ?? sleep; + const job0 = (await store.get(jobId))!; + const input = job0.input; + const set = (p: Partial) => store.patch(jobId, p); + const deadline = Date.now() + cfg.limits.runDeadlineS * 1000; + const arenaHost = new URL(cfg.arena.botUrl).hostname; + + let sbx: Sandbox | undefined; + let proc = undefined as ProcessHandle | undefined; // assigned inside the mode functions + let runStartedAt = 0; + let verdict: { status: "finished" | "failed" | "aborted"; error?: string; cls?: ErrorClass } = { status: "finished" }; + let handsDone = 0; + let dealsSeed: string | undefined; // worker mode: revealed on the job record only once the job is over + + try { + await set({ status: "provisioning" }); + const needsPip = input.language === "python" && !!input.requirementsFile; + + // 1 ---- identity: the arena attributes the run to this player (worker mode: signed into result.json via --player-id). + // A public player's own job is credited to them, so every submit with the same token lands on one leaderboard row. + const bot = input.playerId && input.mode === "worker" + ? { playerId: input.playerId, token: "" } + : await infra(() => arena.registerBot(`${input.botName}-${jobId.slice(-6)}`, input.userId)); + await set({ arenaPlayerId: bot.playerId }); + + // 2 ---- sandbox. Worker mode: no egress at all. Connect mode: the arena only. PyPI only while installing. + const baseAllow = input.mode === "connect" ? [arenaHost] : []; + sbx = await infra(() => platinum.createSandbox({ + name: `run-${jobId}`, + template: cfg.backend === "local" ? cfg.local.botImage : cfg.platinum.botTemplate, + cpu: cfg.sandbox.cpu, ramMb: cfg.sandbox.ramMb, diskGb: cfg.sandbox.diskGb, + region: cfg.platinum.region, + autoStopMinutes: cfg.sandbox.autoStopMinutes, + metadata: { sharingan_job: jobId, user: input.userId, track: input.track, mode: input.mode }, + allowOut: needsPip ? [...baseAllow, ...PYPI_HOSTS] : baseAllow, + }, { signal: ac.signal, timeoutMs: 120_000 })); + runStartedAt = Date.now(); + await set({ sandboxId: sbx.id }); + log("sandbox_created", { job: jobId, sandbox: sbx.id, backend: platinum.kind }); + + // 3 ---- artifact + if (artifact.length > cfg.limits.maxArtifactBytes) throw new JobFailure("bot", `artifact too large (${artifact.length} > ${cfg.limits.maxArtifactBytes})`); + await infra(() => sbx!.writeFile("/tmp/bot.tgz", artifact)); + const unpack = await infra(() => sbx!.sh( + // unpacked by the unprivileged user (a crafted archive can't write outside the bot directory through a link it made), + // then root-owned and read-only + `mkdir -p ${BOT_DIR} && chown ${BOT_UID}:${BOT_UID} ${BOT_DIR} && chmod 0644 /tmp/bot.tgz ` + + `&& ${DROP} tar xzf /tmp/bot.tgz -C ${BOT_DIR} --no-same-owner --no-same-permissions && rm -f /tmp/bot.tgz ` + + `&& chown -R root:root ${BOT_DIR} && chmod -R a+rX,go-w ${BOT_DIR} && chmod 0755 ${BOT_DIR} && ${futureAtime(BOT_DIR)}`, { timeoutMs: 30_000 }, + )); + if (unpack.exitCode !== 0) throw new JobFailure("bot", `could not unpack the artifact: ${unpack.stderr.trim().slice(0, 300)}`); + const has = await infra(() => sbx!.sh(`test -f ${shq(`${BOT_DIR}/${input.entry}`)}`)); + if (has.exitCode !== 0) throw new JobFailure("bot", `entry file ${input.entry} not found in the archive`); + + // 4 ---- deps, then drop PyPI again + if (needsPip) { + // Unprivileged (BOT_UID) into DEPS_DIR: a package's setup code must not reach the worker, the key or the seed. pip works + // in a private copy of the bot directory (local packages like `./mypkg` build in place; relative paths resolve from it). + const pip = await infra(() => sbx!.sh( + `mkdir -p ${DEPS_DIR} && rm -rf ${PIP_SRC} && cp -r ${BOT_DIR} ${PIP_SRC} && chown -R ${BOT_UID}:${BOT_UID} ${DEPS_DIR} ${PIP_SRC} ` + + `&& cd ${PIP_SRC} && ${DROP} ` + + `env -i HOME=/tmp PATH=/usr/local/bin:/usr/bin:/bin pip install --no-cache-dir --disable-pip-version-check --no-warn-script-location ` + + `--target ${DEPS_DIR} -r ${shq(`${PIP_SRC}/${input.requirementsFile!}`)}`, { timeoutMs: 300_000 }, + )); + if (pip.exitCode !== 0) throw new JobFailure("bot", `pip install failed: ${(pip.stderr || pip.stdout).trim().slice(-400)}`); + await infra(() => sbx!.setEgress(baseAllow)); + // First end everything the install started (nothing of BOT_UID may still run while root walks DEPS_DIR), then seal + // DEPS_DIR root-owned and read-only. Nothing the install wrote outside DEPS_DIR survives into the run. + const lock = await infra(() => sbx!.sh(`sharingan-scrub ${BOT_UID} --keep ${DEPS_DIR} && chown -R root:root ${DEPS_DIR} && chmod -R a+rX,go-w ${DEPS_DIR} && ${futureAtime(DEPS_DIR)}`, { timeoutMs: 60_000 })); + if (lock.exitCode !== 0) throw new JobFailure("infra", `could not seal the install: ${(lock.stderr || lock.stdout).trim().slice(-300)}`); + } + + // 5 ---- play + await set({ status: input.mode === "worker" ? "running" : "connecting" }); + if (input.mode === "worker") { + const r = await runWorker(bot); + handsDone = r.handsDone; + } else { + const r = await runConnect(bot); + handsDone = r.handsDone; + } + } catch (e) { + if (e instanceof AbortedError) verdict = { status: "aborted", error: "aborted" }; + else if (e instanceof JobFailure) verdict = { status: "failed", error: e.message.slice(0, 1000), cls: e.cls }; + else verdict = { status: "failed", error: String((e as Error)?.message ?? e).slice(0, 1000), cls: "infra" }; + log("job_error", { job: jobId, status: verdict.status, cls: verdict.cls, error: verdict.error }); + } finally { + // 6 ---- meter + teardown. Always runs. usage() must be read BEFORE delete (404 afterwards). + const patch: Partial = {}; + if (proc) { + try { + const l = await proc.logs(); + // one copy of each traceback; the closing "mbb/game" line is dropped unless the run actually finished + const o = { maxChars: 4000, dropScore: verdict.status !== "finished" }; + const out = cleanLog(l.stdout, o); + patch.botLogTail = `${cleanLog(l.stderr, o)}${out ? `\n--- stdout ---\n${out}` : ""}`.slice(-4000); + } catch { /* best effort */ } + try { if ((await proc.status()).running) await proc.kill(); } catch { /* the sandbox is about to be deleted */ } + } + let platinumUsd: number | undefined; + if (sbx) { + try { platinumUsd = platinumUsdFromUsage(await sbx.usage()); } catch { /* best effort */ } + try { await sbx.delete(); patch.sandboxDeleted = true; } catch (e) { + patch.sandboxDeleted = false; + log("sandbox_leak", { job: jobId, sandbox: sbx.id, error: String(e) }); // the reaper retries + } + } + const seconds = runStartedAt ? (Date.now() - runStartedAt) / 1000 : 0; + const j = (await store.get(jobId))!; + const done = Math.max(handsDone, j.handsDone ?? 0); + await set({ + ...patch, + status: verdict.status, + ...(verdict.error ? { error: verdict.error, errorClass: verdict.cls } : {}), + ...(dealsSeed ? { dealsSeed } : {}), + handsDone: done, + sandboxSeconds: seconds, + platinumUsd, + cogsMicro: cogsMicro(cfg.pricing, { cpu: cfg.sandbox.cpu, ramMb: cfg.sandbox.ramMb, seconds, handsPlayed: done, platinumUsd }), + finishedAt: Date.now(), + }); + } + + // ------------------------------------------------------------------------------------------ worker mode + async function runWorker(bot: { playerId: string }): Promise<{ handsDone: number }> { + const w = cfg.worker; + if (!w.signKey) throw new JobFailure("infra", "worker mode needs WORKER_SIGN_KEY (the worker signs result.json with it)"); + // --sign-key-file takes `id=secret` (matching an entry of the arena's ARENA_WORKER_KEYS) or a bare secret + const keyFile = w.keyId ? `${w.keyId}=${w.signKey}` : w.signKey; + await infra(() => sbx!.writeFile(KEY_PATH, new TextEncoder().encode(keyFile), { mode: 0o400 })); + // Fresh secret deals for every verified run: the worker deals from this seed, the arena checks it is well formed. + // The bot (uid 10002) cannot read the file, and the seed is not in anybody's env or argv. + const seed = `run:${randomBytes(32).toString("hex")}`; + dealsSeed = seed; + await infra(() => sbx!.writeFile(SEED_PATH, new TextEncoder().encode(seed), { mode: 0o400 })); + const dir = w.resultPath.slice(0, w.resultPath.lastIndexOf("/")) || "/"; + let cmd = renderCommand(w.cmdTemplate, { + bot: botCommand(cfg, input), + track: input.track, + hands: input.hands, + lanes: input.lanes ?? cfg.limits.defaultLanes, + out: w.resultPath, + keyfile: KEY_PATH, + seedfile: SEED_PATH, + player_id: bot.playerId, + job_id: jobId, + name: input.botName, + owner: input.userId, + key_id: w.keyId, + }); + if (!w.cmdTemplate.includes("{seedfile}")) cmd += ` --seed-file ${shq(SEED_PATH)}`; // a custom template must not drop the seed + if (!w.cmdTemplate.includes("--rotation-uids")) cmd += ` --rotation-uids ${ROTATION_UIDS.join(",")}`; // nor the isolation + // the pip window's network must be gone (a failed disconnect must not leave it attached): only loopback may remain + const nets = await infra(() => sbx!.sh("ls /sys/class/net")); + const ifs = nets.stdout.split(/\s+/).filter(Boolean); + if (nets.exitCode !== 0 || ifs.some((i) => i !== "lo")) throw new JobFailure("infra", `the sandbox still has a network (${ifs.join(", ")}); not starting the run`); + const wp = await infra(() => sbx!.startProcess({ + cmd: ["sh", "-c", `mkdir -p ${shq(dir)} && cd ${shq(dir)} && exec ${cmd}`], + env: { ...w.env, SHARINGAN_JOB_ID: jobId, SHARINGAN_OWNER: input.userId, SHARINGAN_BOT_NAME: input.botName, SHARINGAN_TRACK: input.track }, + timeoutMs: Math.max(1000, deadline - Date.now()), + })); + proc = wp; + await set({ status: "running", handsTotal: input.hands, ranBot: true }); + + // wait for the worker to exit + let failures = 0; + let exitCode: number | undefined; + for (;;) { + if (ac.signal.aborted) throw new AbortedError(); + if (Date.now() > deadline) throw new JobFailure("bot", `run deadline (${cfg.limits.runDeadlineS}s) exceeded`); + try { + const st = await wp.status(); + failures = 0; + if (!st.running) { exitCode = st.exitCode ?? 0; break; } + const l = await wp.logs(); + const p = parseProgress(`${l.stderr}\n${l.stdout}`); + if (p) await set({ handsDone: Math.min(p.done, input.hands), handsTotal: p.total }); + } catch (e) { + if (++failures >= cfg.limits.pollFailureLimit) throw new JobFailure("infra", `sandbox unreachable: ${String(e).slice(0, 200)}`); + } + await nap(cfg.limits.pollIntervalMs, ac.signal).catch(() => { throw new AbortedError(); }); + } + if (exitCode !== 0) { + const l = await wp.logs().catch(() => ({ stdout: "", stderr: "" })); + throw new JobFailure("bot", `worker exited with code ${exitCode}${logExcerpt(l)}`); + } + + // result.json -> arena + await set({ status: "finalizing" }); + const raw = await infra(() => sbx!.readFile(w.resultPath)); + let result: Record; + try { result = JSON.parse(new TextDecoder().decode(raw)); } catch { throw new JobFailure("infra", "worker wrote an unreadable result.json"); } + // A bot that never answered a single decision (import error, crash on startup) forfeits every hand. The worker still + // produces a valid signed result, but posting it would put a junk run on the leaderboard: fail the job instead. + const forfeited = pickNum(result, ["forfeit_hands"]) ?? 0; + const played = pickNum(result, ["hands", "hands_done"]) ?? 0; + if (played > 0 && forfeited >= played) { + const l = await wp.logs().catch(() => ({ stdout: "", stderr: "" })); + await set({ handsDone: 0, forfeitHands: forfeited }); + // one clear first line, then ONE de-duplicated excerpt (lanes repeat the same crash); no progress, no score line + throw new JobFailure("bot", `the bot never answered a decision (${forfeited}/${played} hands forfeited); nothing was submitted.${logExcerpt(l)}`); + } + let ack: ResultAck; + try { + ack = await arena.postResult(raw); + } catch (e) { + if (e instanceof ArenaError && e.status >= 400 && e.status < 500) throw new JobFailure("infra", `arena rejected the signed result: ${e.message}`); + throw new JobFailure("infra", `could not submit the result to the arena: ${String(e).slice(0, 200)}`); + } + const handsPlayed = pickNum(ack, ["hands_done", "hands"]) ?? pickNum(result, ["hands_done", "hands_played", "hands"]) ?? 0; + await set({ + handsDone: handsPlayed, + handsTotal: pickNum(ack, ["hands_total", "hands_planned"]) ?? pickNum(result, ["hands_total", "hands_planned"]) ?? input.hands, + runId: typeof ack.run_id === "string" ? ack.run_id : typeof result.run_id === "string" ? result.run_id : undefined, + mbbPerGame: ack.mbb_per_game ?? pickNum(result, ["mbb_per_game"]) ?? null, + ci95Mbb: ack.ci95_mbb ?? pickNum(result, ["ci95_mbb"]) ?? null, + verified: ack.verified === true, + forfeitHands: pickNum(ack, ["forfeit_hands"]) ?? pickNum(result, ["forfeit_hands"]), + resultAck: ack, + }); + if (ack.verified !== true) throw new JobFailure("infra", "arena accepted the result but did not mark it verified (check ARENA_WORKER_KEYS / WORKER_KEY_ID)"); + return { handsDone: handsPlayed }; + } + + // ------------------------------------------------------------------------------------------ connect mode + async function runConnect(bot: { playerId: string; token: string }): Promise<{ handsDone: number }> { + // The token goes in the process env only, never in the sandbox's create-time env. + const launcher = input.language === "python" ? ["python3", "/opt/sharingan/launch_bot.py"] : ["node", "/opt/sharingan/launch_bot.mjs"]; + const cp = await infra(() => sbx!.startProcess({ + cmd: ["setpriv", `--reuid=${BOT_UID}`, `--regid=${BOT_UID}`, "--clear-groups", "--inh-caps=-all", "--bounding-set=-all", ...launcher], + cwd: BOT_DIR, + env: { BOT_FILE: `${BOT_DIR}/${input.entry}`, ARENA_URL: cfg.arena.botUrl, ARENA_TOKEN: bot.token, PYTHONUNBUFFERED: "1", HOME: "/home/bot" }, + timeoutMs: Math.max(1000, deadline - Date.now()), // guest-side hard stop for the bot process + })); + proc = cp; + + // start the run once the bot's websocket is up (409 not_connected until then) + let run: BenchRun | undefined; + const connectBy = Date.now() + cfg.limits.connectTimeoutS * 1000; + while (!run) { + if (ac.signal.aborted) throw new AbortedError(); + try { + run = await arena.startHostedRun(input.track, bot.playerId, { hands: input.hands, lanes: input.lanes ?? cfg.limits.defaultLanes }); + } catch (e) { + if (!(e instanceof ArenaError) || e.code !== "not_connected") { + if (e instanceof ArenaError && e.status >= 400 && e.status < 500) throw new JobFailure("infra", `arena refused the run: ${e.message}`); + throw new JobFailure("infra", String(e).slice(0, 300)); + } + if ((await cp.status().catch(() => ({ running: true }))).running === false) { + const l = await cp.logs().catch(() => ({ stdout: "", stderr: "" })); + throw new JobFailure("bot", `bot exited before connecting${logExcerpt(l)}`); + } + if (Date.now() > connectBy) { + const l = await cp.logs().catch(() => ({ stdout: "", stderr: "" })); + throw new JobFailure("bot", `bot did not connect in ${cfg.limits.connectTimeoutS}s${logExcerpt(l)}`); + } + await nap(300, ac.signal).catch(() => { throw new AbortedError(); }); + } + } + await set({ status: "running", runId: run.run_id, handsTotal: run.hands_planned ?? run.hands_total ?? input.hands }); + + // poll progress + let failures = 0; + while (run.status === "running") { + if (ac.signal.aborted || Date.now() > deadline) { + await arena.abortRun(input.track, run.run_id).catch(() => {}); + if (ac.signal.aborted) throw new AbortedError(); + throw new JobFailure("bot", `run deadline (${cfg.limits.runDeadlineS}s) exceeded`); + } + await nap(cfg.limits.pollIntervalMs, ac.signal).catch(() => { throw new AbortedError(); }); + try { + run = await arena.getRun(input.track, run.run_id); + failures = 0; + } catch (e) { + if (++failures >= cfg.limits.pollFailureLimit) throw new JobFailure("infra", `arena unreachable while polling: ${String(e).slice(0, 200)}`); + continue; + } + await set({ handsDone: run.hands_done, runningMbb: run.running_mbb_per_game ?? null }); + if (run.status === "running" && (await cp.status().catch(() => ({ running: true }))).running === false) { + await arena.abortRun(input.track, run.run_id).catch(() => {}); + const l = await cp.logs().catch(() => ({ stdout: "", stderr: "" })); + handsDone = run.hands_done; + await set({ handsDone }); + throw new JobFailure("bot", `bot process exited mid-run${logExcerpt(l)}`); + } + } + await set({ + status: "finalizing", handsDone: run.hands_done, handsTotal: run.hands_planned ?? run.hands_total, + mbbPerGame: run.mbb_per_game, ci95Mbb: run.ci95_mbb, verified: run.verified, + }); + if (run.status !== "finished") throw new JobFailure("bot", `run ended as ${run.status}`); + return { handsDone: run.hands_done }; + } +} + +/** "\n" of a process's output for an error message, or "" when there is none. */ +function logExcerpt(l: { stdout: string; stderr: string }): string { + const e = cleanLog(`${l.stderr}\n${l.stdout}`, { maxChars: 600, dropScore: true }); + return e ? `\n${e}` : ""; +} + +/** Anything thrown by `fn` is our infrastructure's fault unless it already carries a verdict. */ +async function infra(fn: () => Promise): Promise { + try { return await fn(); } catch (e) { + if (e instanceof JobFailure || e instanceof AbortedError) throw e; + if (e instanceof Error && e.message === "aborted") throw new AbortedError(); + throw new JobFailure("infra", String((e as Error)?.message ?? e).slice(0, 500)); + } +} + +/** Delete run sandboxes that no active job owns (runner crash, lost delete). Call on boot and every few minutes. */ +export async function reapOrphans(deps: Pick, minAgeMs = 120_000): Promise { + const owned = new Set((await deps.store.active()).map((j) => j.sandboxId).filter(Boolean)); + let n = 0; + for await (const s of deps.platinum.listSandboxes()) { + if (!s.metadata.sharingan_job || owned.has(s.id)) continue; + if (Date.now() - s.createdAtMs < minAgeMs) continue; // the create may not be recorded in the store yet + try { await deps.platinum.deleteSandbox(s.id); n++; deps.log("reaped_sandbox", { sandbox: s.id, job: s.metadata.sharingan_job }); } catch { /* next sweep */ } + } + return n; +} diff --git a/deploy/platinum/runner/src/ledger.ts b/deploy/platinum/runner/src/ledger.ts new file mode 100644 index 00000000..e2b9a786 --- /dev/null +++ b/deploy/platinum/runner/src/ledger.ts @@ -0,0 +1,253 @@ +// Prepaid credit ledger: reserve-then-settle per job, idempotent on every write. +// +// topup(user, amount, stripeEventId) balance += amount (Stripe webhook; replays are no-ops) +// reserve(user, jobKey, amount) balance -= amount, reserved += amount (before the job is accepted) +// settle(jobKey, charge) reserved -= amount, balance += amount - charge (after teardown) +// +// Invariant per user: balance + reserved + (sum of settle charges) == (sum of top-ups). Accounts never go negative: +// reserve refuses (InsufficientCredits) instead. All amounts are integer micro-USD. Two implementations with one contract +// test suite: MemoryLedger (tests, RUNNER_STORAGE=memory) and PgLedger. +import type { Pool } from "./db.ts"; +import { tx } from "./db.ts"; + +export class InsufficientCredits extends Error { + balanceMicro: number; + neededMicro: number; + constructor(balanceMicro: number, neededMicro: number) { + super(`insufficient credits: have ${balanceMicro} micro-USD available, need ${neededMicro}`); + this.balanceMicro = balanceMicro; + this.neededMicro = neededMicro; + } +} + +export class LedgerConflict extends Error {} + +export interface Balance { userId: string; balanceMicro: number; reservedMicro: number } +export interface Reservation { + key: string; + userId: string; + amountMicro: number; + state: "held" | "settled"; + chargedMicro?: number; + createdAt: number; +} +export interface LedgerEntry { + id: number; + userId: string; + kind: "topup" | "reserve" | "settle" | "release"; + amountMicro: number; + ref: string; + idempotencyKey: string; + meta: Record; + createdAt: number; +} +export interface SettleResult { settledNow: boolean; reservation: Reservation; chargedMicro: number; releasedMicro: number } + +export interface Ledger { + balance(userId: string): Promise; + topup(userId: string, amountMicro: number, eventId: string, meta?: Record): Promise<{ applied: boolean; balance: Balance }>; + /** Idempotent on `key`: a retry returns the existing reservation (`created:false`). Throws InsufficientCredits. */ + reserve(userId: string, key: string, amountMicro: number): Promise<{ created: boolean; reservation: Reservation }>; + /** Idempotent on `key`. `chargeMicro` is clamped to [0, reserved]; the rest is released. */ + settle(key: string, chargeMicro: number, meta?: Record): Promise; + getReservation(key: string): Promise; + /** Reservations still held after `olderThanMs` (crash recovery). */ + heldReservations(olderThanMs: number): Promise; + entries(userId: string, limit?: number): Promise; +} + +const checkAmount = (n: number, what: string) => { + if (!Number.isSafeInteger(n) || n < 0) throw new RangeError(`${what} must be a non-negative integer (micro-USD), got ${n}`); +}; + +// ------------------------------------------------------------------------------------------------ memory + +export class MemoryLedger implements Ledger { + private accounts = new Map(); + private reservations = new Map(); + private log: LedgerEntry[] = []; + private keys = new Set(); + private now: () => number; + + constructor(now: () => number = Date.now) { this.now = now; } + + private acct(userId: string) { + let a = this.accounts.get(userId); + if (!a) { a = { balance: 0, reserved: 0 }; this.accounts.set(userId, a); } + return a; + } + private add(userId: string, kind: LedgerEntry["kind"], amountMicro: number, ref: string, idempotencyKey: string, meta: Record) { + this.keys.add(idempotencyKey); + this.log.push({ id: this.log.length + 1, userId, kind, amountMicro, ref, idempotencyKey, meta, createdAt: this.now() }); + } + + async balance(userId: string): Promise { + const a = this.accounts.get(userId) ?? { balance: 0, reserved: 0 }; + return { userId, balanceMicro: a.balance, reservedMicro: a.reserved }; + } + + async topup(userId: string, amountMicro: number, eventId: string, meta: Record = {}) { + checkAmount(amountMicro, "top-up"); + const key = `topup:${eventId}`; + if (this.keys.has(key)) return { applied: false, balance: await this.balance(userId) }; + this.acct(userId).balance += amountMicro; + this.add(userId, "topup", amountMicro, eventId, key, meta); + return { applied: true, balance: await this.balance(userId) }; + } + + async reserve(userId: string, key: string, amountMicro: number) { + checkAmount(amountMicro, "reservation"); + const existing = this.reservations.get(key); + if (existing) { + if (existing.userId !== userId || existing.amountMicro !== amountMicro) throw new LedgerConflict(`reservation ${key} exists with different parameters`); + return { created: false, reservation: { ...existing } }; + } + const a = this.acct(userId); + if (a.balance < amountMicro) throw new InsufficientCredits(a.balance, amountMicro); + a.balance -= amountMicro; + a.reserved += amountMicro; + const r: Reservation = { key, userId, amountMicro, state: "held", createdAt: this.now() }; + this.reservations.set(key, r); + this.add(userId, "reserve", amountMicro, key, `reserve:${key}`, {}); + return { created: true, reservation: { ...r } }; + } + + async settle(key: string, chargeMicro: number, meta: Record = {}): Promise { + checkAmount(chargeMicro, "charge"); + const r = this.reservations.get(key); + if (!r) throw new LedgerConflict(`no such reservation ${key}`); + if (r.state === "settled") { + const charged = r.chargedMicro ?? 0; + return { settledNow: false, reservation: { ...r }, chargedMicro: charged, releasedMicro: r.amountMicro - charged }; + } + const charged = Math.min(chargeMicro, r.amountMicro); + const released = r.amountMicro - charged; + const a = this.acct(r.userId); + a.reserved -= r.amountMicro; + a.balance += released; + r.state = "settled"; + r.chargedMicro = charged; + this.add(r.userId, "settle", charged, key, `settle:${key}`, meta); + if (released > 0) this.add(r.userId, "release", released, key, `release:${key}`, {}); + return { settledNow: true, reservation: { ...r }, chargedMicro: charged, releasedMicro: released }; + } + + async getReservation(key: string) { const r = this.reservations.get(key); return r ? { ...r } : undefined; } + + async heldReservations(olderThanMs: number) { + const cutoff = this.now() - olderThanMs; + return [...this.reservations.values()].filter((r) => r.state === "held" && r.createdAt <= cutoff).map((r) => ({ ...r })); + } + + async entries(userId: string, limit = 50) { + return this.log.filter((e) => e.userId === userId).slice(-limit).reverse(); + } +} + +// ------------------------------------------------------------------------------------------------ postgres + +interface ResRow { key: string; user_id: string; amount_micro: number; state: "held" | "settled"; charged_micro: number | null; created_at: Date } +const toReservation = (r: ResRow): Reservation => ({ + key: r.key, userId: r.user_id, amountMicro: r.amount_micro, state: r.state, + chargedMicro: r.charged_micro ?? undefined, createdAt: r.created_at.getTime(), +}); + +export class PgLedger implements Ledger { + private readonly pool: Pool; + constructor(pool: Pool) { this.pool = pool; } + + async balance(userId: string): Promise { + const r = await this.pool.query("SELECT balance_micro, reserved_micro FROM credit_accounts WHERE user_id = $1", [userId]); + const row = r.rows[0]; + return { userId, balanceMicro: row?.balance_micro ?? 0, reservedMicro: row?.reserved_micro ?? 0 }; + } + + async topup(userId: string, amountMicro: number, eventId: string, meta: Record = {}) { + checkAmount(amountMicro, "top-up"); + const applied = await tx(this.pool, async (c) => { + await c.query("INSERT INTO credit_accounts(user_id) VALUES ($1) ON CONFLICT DO NOTHING", [userId]); + const ins = await c.query( + "INSERT INTO credit_entries(user_id, kind, amount_micro, ref, idempotency_key, meta) VALUES ($1,'topup',$2,$3,$4,$5) ON CONFLICT (idempotency_key) DO NOTHING RETURNING id", + [userId, amountMicro, eventId, `topup:${eventId}`, JSON.stringify(meta)], + ); + if (ins.rowCount === 0) return false; + await c.query("UPDATE credit_accounts SET balance_micro = balance_micro + $2 WHERE user_id = $1", [userId, amountMicro]); + return true; + }); + return { applied, balance: await this.balance(userId) }; + } + + async reserve(userId: string, key: string, amountMicro: number) { + checkAmount(amountMicro, "reservation"); + return tx(this.pool, async (c) => { + await c.query("INSERT INTO credit_accounts(user_id) VALUES ($1) ON CONFLICT DO NOTHING", [userId]); + const acct = (await c.query("SELECT balance_micro FROM credit_accounts WHERE user_id = $1 FOR UPDATE", [userId])).rows[0]; + const ex = (await c.query("SELECT * FROM credit_reservations WHERE key = $1", [key])).rows[0]; + if (ex) { + if (ex.user_id !== userId || ex.amount_micro !== amountMicro) throw new LedgerConflict(`reservation ${key} exists with different parameters`); + return { created: false, reservation: toReservation(ex) }; + } + if (acct.balance_micro < amountMicro) throw new InsufficientCredits(acct.balance_micro, amountMicro); + await c.query("UPDATE credit_accounts SET balance_micro = balance_micro - $2, reserved_micro = reserved_micro + $2 WHERE user_id = $1", [userId, amountMicro]); + const row = (await c.query( + "INSERT INTO credit_reservations(key, user_id, amount_micro, state) VALUES ($1,$2,$3,'held') RETURNING *", [key, userId, amountMicro], + )).rows[0]!; + await c.query( + "INSERT INTO credit_entries(user_id, kind, amount_micro, ref, idempotency_key) VALUES ($1,'reserve',$2,$3,$4)", [userId, amountMicro, key, `reserve:${key}`], + ); + return { created: true, reservation: toReservation(row) }; + }); + } + + async settle(key: string, chargeMicro: number, meta: Record = {}): Promise { + checkAmount(chargeMicro, "charge"); + return tx(this.pool, async (c) => { + // lock order everywhere: account, then reservation + const peek = (await c.query("SELECT * FROM credit_reservations WHERE key = $1", [key])).rows[0]; + if (!peek) throw new LedgerConflict(`no such reservation ${key}`); + await c.query("SELECT 1 FROM credit_accounts WHERE user_id = $1 FOR UPDATE", [peek.user_id]); + const r = (await c.query("SELECT * FROM credit_reservations WHERE key = $1 FOR UPDATE", [key])).rows[0]!; + if (r.state === "settled") { + const charged = r.charged_micro ?? 0; + return { settledNow: false, reservation: toReservation(r), chargedMicro: charged, releasedMicro: r.amount_micro - charged }; + } + const charged = Math.min(chargeMicro, r.amount_micro); + const released = r.amount_micro - charged; + await c.query("UPDATE credit_accounts SET reserved_micro = reserved_micro - $2, balance_micro = balance_micro + $3 WHERE user_id = $1", [r.user_id, r.amount_micro, released]); + const upd = (await c.query( + "UPDATE credit_reservations SET state = 'settled', charged_micro = $2, settled_at = now() WHERE key = $1 RETURNING *", [key, charged], + )).rows[0]!; + await c.query( + "INSERT INTO credit_entries(user_id, kind, amount_micro, ref, idempotency_key, meta) VALUES ($1,'settle',$2,$3,$4,$5)", + [r.user_id, charged, key, `settle:${key}`, JSON.stringify(meta)], + ); + if (released > 0) { + await c.query( + "INSERT INTO credit_entries(user_id, kind, amount_micro, ref, idempotency_key) VALUES ($1,'release',$2,$3,$4)", [r.user_id, released, key, `release:${key}`], + ); + } + return { settledNow: true, reservation: toReservation(upd), chargedMicro: charged, releasedMicro: released }; + }); + } + + async getReservation(key: string) { + const r = (await this.pool.query("SELECT * FROM credit_reservations WHERE key = $1", [key])).rows[0]; + return r ? toReservation(r) : undefined; + } + + async heldReservations(olderThanMs: number) { + const r = await this.pool.query( + "SELECT * FROM credit_reservations WHERE state = 'held' AND created_at <= now() - ($1::bigint * interval '1 millisecond') ORDER BY created_at", [olderThanMs], + ); + return r.rows.map(toReservation); + } + + async entries(userId: string, limit = 50) { + const r = await this.pool.query( + "SELECT id, user_id, kind, amount_micro, ref, idempotency_key, meta, created_at FROM credit_entries WHERE user_id = $1 ORDER BY id DESC LIMIT $2", [userId, limit], + ); + return r.rows.map((e: { id: number; user_id: string; kind: LedgerEntry["kind"]; amount_micro: number; ref: string; idempotency_key: string; meta: Record; created_at: Date }) => ({ + id: e.id, userId: e.user_id, kind: e.kind, amountMicro: e.amount_micro, ref: e.ref, idempotencyKey: e.idempotency_key, meta: e.meta, createdAt: e.created_at.getTime(), + })); + } +} diff --git a/deploy/platinum/runner/src/log.ts b/deploy/platinum/runner/src/log.ts new file mode 100644 index 00000000..b19df2ce --- /dev/null +++ b/deploy/platinum/runner/src/log.ts @@ -0,0 +1,7 @@ +// JSON-lines logger. `Logger` is injected everywhere so tests stay quiet (or capture). +export type Logger = (event: string, fields?: Record) => void; + +export const stdoutLog: Logger = (event, fields = {}) => { + console.log(JSON.stringify({ ts: new Date().toISOString(), event, ...fields })); +}; +export const noopLog: Logger = () => {}; diff --git a/deploy/platinum/runner/src/logclean.ts b/deploy/platinum/runner/src/logclean.ts new file mode 100644 index 00000000..4ebb8760 --- /dev/null +++ b/deploy/platinum/runner/src/logclean.ts @@ -0,0 +1,43 @@ +// Turn raw worker / bot output into something a person can read: one copy of every traceback (the match worker runs +// several lanes and each prints the same crash), no machine progress chatter and, when asked, no score line. +// +// A worker prints, on stderr, progress (" ladder-v1 300/600 hands (45 hands/s)") and a closing summary +// ("ladder-v1: +12.5 ± 3.2 mbb/game (aivat) over 600 hands on ladder-v1; 45 hands/s; 600 FORFEIT hands; signed"). On a +// forfeited or rejected run that summary reads like a score, so those runs drop it. + +const LANE_PREFIX = /^\s*(?:\[(?:lane\s*)?\d+\]|\(lane \d+\)|lane[ _-]?\d+\s*[:|]) ?/i; +const indented = (l: string) => /^[ \t]/.test(l); +// length-guarded: a bot's prints reach this log, and a long digit run would make the first regex crawl +const isProgress = (l: string) => (l.length <= 200 && /\d+\s*\/\s*\d+\s*hands/i.test(l)) || (l.trimStart().startsWith("{") && /"hands_(?:done|total)"|"hands_planned"/.test(l)); +export const isScoreLine = (l: string) => /mbb\/game/i.test(l) && /\bhands\b/i.test(l); + +export interface CleanOpts { maxChars?: number; dropScore?: boolean } + +/** De-duplicated excerpt (first occurrence wins, order kept), tail-limited to `maxChars` on a line boundary. */ +export function cleanLog(text: string, opts: CleanOpts = {}): string { + const maxChars = opts.maxChars ?? 800; + const lines = text.replace(/\r/g, "").split("\n").map((l) => (l.length > 2000 ? `${l.slice(0, 2000)} [...]` : l).replace(LANE_PREFIX, "").trimEnd()) + .filter((l) => l.trim() !== "" && !isProgress(l) && !(opts.dropScore && isScoreLine(l))); + const seen = new Set(); + const out: string[] = []; + for (let i = 0; i < lines.length; i++) { + let chunk = [lines[i]!]; + // a traceback / stack is a header plus its indented body; Python's ends with one unindented exception line + if (!indented(lines[i]!) && indented(lines[i + 1] ?? "")) { + let j = i + 1; + while (j < lines.length && indented(lines[j]!)) j++; + if (/^Traceback/.test(lines[i]!) && j < lines.length) j++; + chunk = lines.slice(i, j); + i = j - 1; + } + const key = chunk.join("\n"); + if (seen.has(key)) continue; + seen.add(key); + out.push(key); + } + const s = out.join("\n"); + if (s.length <= maxChars) return s; + const cut = s.slice(-maxChars); + const nl = cut.indexOf("\n"); + return nl >= 0 && nl < cut.length - 1 ? cut.slice(nl + 1) : cut; +} diff --git a/deploy/platinum/runner/src/money.ts b/deploy/platinum/runner/src/money.ts new file mode 100644 index 00000000..a8900856 --- /dev/null +++ b/deploy/platinum/runner/src/money.ts @@ -0,0 +1,9 @@ +// Money is integer micro-USD (1 USD = 1_000_000) everywhere inside the runner. Floats exist only at the env/JSON edge. + +export const MICRO = 1_000_000; +export const usdToMicro = (usd: number): number => Math.round(usd * MICRO); +export const microToUsd = (micro: number): number => micro / MICRO; +/** Stripe minor units (cents) -> micro-USD. */ +export const centsToMicro = (cents: number): number => Math.round(cents) * 10_000; +export const microToCents = (micro: number): number => Math.round(micro / 10_000); +export const fmtUsd = (micro: number): string => `$${(micro / MICRO).toFixed(micro % 10_000 === 0 ? 2 : 6)}`; diff --git a/deploy/platinum/runner/src/platinum/engine.ts b/deploy/platinum/runner/src/platinum/engine.ts new file mode 100644 index 00000000..1979c1f3 --- /dev/null +++ b/deploy/platinum/runner/src/platinum/engine.ts @@ -0,0 +1,110 @@ +// A small client for the Docker Engine API (v1.41 subset). Podman serves the same API on its compat socket +// (`podman system service`, rootless: $XDG_RUNTIME_DIR/podman/podman.sock), so one client covers both engines. +import http from "node:http"; + +export class EngineError extends Error { + status: number; + constructor(status: number, message: string) { + super(`engine ${status}: ${message}`); + this.status = status; + } +} + +export interface EngineResponse { status: number; headers: http.IncomingHttpHeaders; body: Buffer } + +export interface EngineOpts { + /** unix:///path/to.sock or tcp://host:port (http://host:port also accepted). */ + host: string; + apiVersion?: string; + requestTimeoutMs?: number; +} + +export class Engine { + private readonly target: { socketPath: string } | { host: string; port: number }; + private readonly prefix: string; + private readonly timeoutMs: number; + + constructor(opts: EngineOpts) { + this.prefix = `/v${opts.apiVersion ?? "1.41"}`; + this.timeoutMs = opts.requestTimeoutMs ?? 60_000; + const h = opts.host; + if (h.startsWith("unix://")) this.target = { socketPath: h.slice("unix://".length) }; + else { + const u = new URL(h.replace(/^tcp:/, "http:")); + this.target = { host: u.hostname, port: Number(u.port || 80) }; + } + } + + request(method: string, path: string, opts: { json?: unknown; body?: Buffer; contentType?: string; timeoutMs?: number } = {}): Promise { + return new Promise((resolve, reject) => { + const payload = opts.body ?? (opts.json !== undefined ? Buffer.from(JSON.stringify(opts.json)) : undefined); + const headers: Record = {}; + if (payload) { + headers["content-length"] = payload.length; + headers["content-type"] = opts.contentType ?? "application/json"; + } + const req = http.request({ ...this.target, method, path: this.prefix + path, headers }, (res) => { + const chunks: Buffer[] = []; + res.on("data", (c: Buffer) => chunks.push(c)); + res.on("end", () => resolve({ status: res.statusCode ?? 0, headers: res.headers, body: Buffer.concat(chunks) })); + res.on("error", reject); + }); + req.setTimeout(opts.timeoutMs ?? this.timeoutMs, () => req.destroy(new Error(`engine request timed out: ${method} ${path}`))); + req.on("error", reject); + req.end(payload); + }); + } + + /** Request that must succeed (2xx); returns parsed JSON (or undefined for an empty body). */ + async json(method: string, path: string, opts: { json?: unknown; ok?: number[]; timeoutMs?: number } = {}): Promise { + const r = await this.request(method, path, { json: opts.json, timeoutMs: opts.timeoutMs }); + const ok = opts.ok ?? [200, 201, 204]; + if (!ok.includes(r.status)) throw new EngineError(r.status, errText(r.body)); + const text = r.body.toString("utf8"); + return (text ? JSON.parse(text) : undefined) as T; + } +} + +function errText(body: Buffer): string { + const t = body.toString("utf8"); + try { const j = JSON.parse(t); return String(j.message ?? t); } catch { return t.slice(0, 300); } +} + +// ---- stream multiplexing (non-TTY exec / attach): 8-byte frame header [type,0,0,0,len(be32)] + payload ---- + +export function demux(buf: Buffer): { stdout: Buffer; stderr: Buffer } { + const out: Buffer[] = []; + const err: Buffer[] = []; + let i = 0; + while (i + 8 <= buf.length) { + const type = buf[i]!; + const len = buf.readUInt32BE(i + 4); + const end = Math.min(buf.length, i + 8 + len); + (type === 2 ? err : out).push(buf.subarray(i + 8, end)); + i = end; + } + return { stdout: Buffer.concat(out), stderr: Buffer.concat(err) }; +} + +// ---- minimal tar (ustar) writer for PUT /containers/{id}/archive ---- + +export function tarFile(name: string, data: Uint8Array, mode = 0o644, mtime = Math.floor(Date.now() / 1000)): Buffer { + if (Buffer.byteLength(name) > 99) throw new Error("tar name too long"); + const header = Buffer.alloc(512); + header.write(name, 0, "utf8"); + header.write(octal(mode, 7), 100, "ascii"); + header.write(octal(0, 7), 108, "ascii"); // uid + header.write(octal(0, 7), 116, "ascii"); // gid + header.write(octal(data.length, 11), 124, "ascii"); + header.write(octal(mtime, 11), 136, "ascii"); + header.write(" ", 148, "ascii"); // checksum placeholder (8 spaces) + header.write("0", 156, "ascii"); // regular file + header.write("ustar\0", 257, "ascii"); + header.write("00", 263, "ascii"); + let sum = 0; + for (const b of header) sum += b; + header.write(octal(sum, 6) + "\0 ", 148, "ascii"); + const pad = (512 - (data.length % 512)) % 512; + return Buffer.concat([header, Buffer.from(data), Buffer.alloc(pad), Buffer.alloc(1024)]); +} +const octal = (n: number, width: number): string => n.toString(8).padStart(width, "0"); diff --git a/deploy/platinum/runner/src/platinum/local.ts b/deploy/platinum/runner/src/platinum/local.ts new file mode 100644 index 00000000..00f5c074 --- /dev/null +++ b/deploy/platinum/runner/src/platinum/local.ts @@ -0,0 +1,238 @@ +// LOCAL PlatinumClient: each "sandbox" is a container created through the Docker Engine API (rootless podman or docker) +// on the same network as the arena. Same job flow as production, minus the microVM boundary. +// +// Egress model, the local analogue of Platinum's `allowOut:[hosts], denyOut:[0.0.0.0/0]`: +// allowOut = [] -> no network at all (worker mode: the runner talks to the arena, the sandbox never does) +// allowOut includes the arena -> `network` (compose: an `internal: true` network holding the arena and nothing that +// reaches the internet) +// allowOut includes other hosts -> `egressNetwork` (a normal network), only while `pip install` runs +// `setEgress` re-computes the set and connects / disconnects the difference, like `updateNetwork` does on Platinum. +import { Engine, EngineError, demux, tarFile } from "./engine.ts"; +import type { + CreateOpts, ExecResult, PlatinumClient, ProcessHandle, ProcessStatus, Sandbox, SandboxInfo, SandboxSpec, StartProcessOpts, +} from "./types.ts"; + +export interface LocalOpts { + engineHost: string; + network: string; + egressNetwork?: string; + binds: string[]; + pidsLimit: number; + /** AppArmor profile for the sandboxes (LOCAL_SANDBOX_APPARMOR); unset = podman's default. */ + apparmor?: string; + /** The arena's hostname: the one destination that needs no extra network. */ + arenaHost: string; + engine?: Engine; +} + +const LABEL = "sharingan.sandbox"; +const META = "sharingan.meta."; + +/** Where process pid/stdout/stderr files live inside a sandbox: on a root-only tmpfs no bot can fill or read. */ +export const PROC_DIR = "/opt/sharingan/run/proc"; + +/** tmpfs mounts of every local sandbox (see createSandbox). */ +export const LOCAL_TMPFS: Record = { + "/tmp": "rw,nosuid,nodev,size=2g,mode=1777", + "/var/tmp": "rw,nosuid,nodev,size=256m,mode=1777", + "/opt/sharingan/bot": "rw,nosuid,nodev,size=1g,mode=0755", + "/opt/sharingan/deps": "rw,nosuid,nodev,size=2g,mode=0755", + "/opt/sharingan/run": "rw,nosuid,nodev,size=64m,mode=0700", // the runner's process logs: root only +}; + +export class LocalPlatinum implements PlatinumClient { + readonly kind = "local" as const; + readonly engine: Engine; + private readonly o: LocalOpts; + + constructor(o: LocalOpts) { + this.o = o; + this.engine = o.engine ?? new Engine({ host: o.engineHost }); + } + + async createSandbox(spec: SandboxSpec, opts: CreateOpts = {}): Promise { + if (opts.signal?.aborted) throw new Error("aborted"); + const labels: Record = { [LABEL]: "1" }; + for (const [k, v] of Object.entries(spec.metadata)) labels[META + k] = v; + const want = this.desiredNetworks(spec.allowOut); + const first = want[0]; + const body = { + Image: spec.template, + Cmd: ["sleep", "infinity"], + Labels: labels, + StopTimeout: 1, + HostConfig: { + Memory: spec.ramMb * 1024 * 1024, + NanoCpus: Math.round(spec.cpu * 1e9), + PidsLimit: this.o.pidsLimit, + NetworkMode: first ?? "none", + Binds: this.o.binds.length ? this.o.binds : undefined, + // apparmor: deploy/production/apparmor/sharingan-sandbox (podman's default denies every signal inside the container under crun) + SecurityOpt: ["no-new-privileges", ...(this.o.apparmor ? [`apparmor=${this.o.apparmor}`] : [])], + // Everything a bot (or its install) can write is a size-capped tmpfs, charged to the container's memory limit: + // nothing reaches the host disk. The image itself has no other writable path for the bot users. + Tmpfs: LOCAL_TMPFS, + Init: true, // reaps orphans, so a killed bot leaves no zombie behind + // NET_ADMIN in the sandbox's own network namespace only: the worker (root) takes the loopback interface down before + // a bot runs (no TCP state a bot could leave for the next rotation). Bot users have no capabilities. + CapAdd: ["NET_ADMIN"], + Ulimits: [{ Name: "core", Soft: 0, Hard: 0 }], // no core dumps (they would land on the host's handler) + }, + NetworkingConfig: first ? { EndpointsConfig: { [first]: {} } } : undefined, + }; + let id: string; + try { + const r = await this.engine.json<{ Id: string }>("POST", `/containers/create?name=${encodeURIComponent(spec.name)}`, { json: body, ok: [201] }); + id = r.Id; + } catch (e) { + if (e instanceof EngineError && e.status === 404) throw new Error(`local sandbox image not found: ${spec.template} (${e.message})`); + throw e; + } + const sbx = new LocalSandbox(this, id, new Set(first ? [first] : [])); + try { + await this.engine.json("POST", `/containers/${id}/start`, { ok: [204, 304] }); + const info = await this.engine.json<{ State?: { Running?: boolean } }>("GET", `/containers/${id}/json`); + if (!info.State?.Running) throw new Error(`container ${spec.name} is not running after start`); + await sbx.setEgress(spec.allowOut); + } catch (e) { + await this.deleteSandbox(id).catch(() => {}); + throw e; + } + return sbx; + } + + async *listSandboxes(): AsyncIterable { + const filters = encodeURIComponent(JSON.stringify({ label: [`${LABEL}=1`], status: ["running"] })); + const rows = await this.engine.json }>>("GET", `/containers/json?filters=${filters}`); + for (const r of rows ?? []) { + const metadata: Record = {}; + for (const [k, v] of Object.entries(r.Labels ?? {})) if (k.startsWith(META)) metadata[k.slice(META.length)] = v; + yield { id: r.Id, metadata, createdAtMs: r.Created * 1000 }; + } + } + + async deleteSandbox(id: string): Promise { + try { + await this.engine.json("DELETE", `/containers/${id}?force=true&v=true`, { ok: [200, 204] }); + } catch (e) { + if (e instanceof EngineError && e.status === 404) return; + throw e; + } + } + + /** Networks a sandbox with this allowlist should be on (see the egress model above). */ + desiredNetworks(allowOut: string[]): string[] { + const nets: string[] = []; + if (allowOut.includes(this.o.arenaHost)) nets.push(this.o.network); + if (allowOut.some((h) => h !== this.o.arenaHost) && this.o.egressNetwork) nets.push(this.o.egressNetwork); + return nets; + } + + async networkOp(op: "connect" | "disconnect", net: string, id: string): Promise { + const r = await this.engine.request("POST", `/networks/${encodeURIComponent(net)}/${op}`, { + json: op === "connect" ? { Container: id } : { Container: id, Force: true }, + }); + const text = r.body.toString("utf8"); + // already attached / not attached are the idempotent no-ops + if (r.status >= 300 && !/already|not connected|not attached|no such|not found|exists/i.test(text)) throw new EngineError(r.status, text.slice(0, 200)); + } +} + +let procSeq = 0; + +class LocalSandbox implements Sandbox { + readonly id: string; + private readonly c: LocalPlatinum; + private networks: Set; + + constructor(c: LocalPlatinum, id: string, networks: Set) { this.c = c; this.id = id; this.networks = networks; } + + private async execCreate(cmd: string[], o: { env?: Record; cwd?: string; user?: string }): Promise { + const env = o.env ? Object.entries(o.env).map(([k, v]) => `${k}=${v}`) : undefined; + const r = await this.c.engine.json<{ Id: string }>("POST", `/containers/${this.id}/exec`, { + json: { AttachStdout: true, AttachStderr: true, Tty: false, Cmd: cmd, Env: env, WorkingDir: o.cwd, User: o.user }, + ok: [201], + }); + return r.Id; + } + + /** Run to completion and collect output (the engine streams the multiplexed frames until the process exits). */ + private async execRun(cmd: string[], o: { env?: Record; cwd?: string; timeoutMs?: number } = {}): Promise<{ exitCode: number; stdout: Buffer; stderr: Buffer }> { + const execId = await this.execCreate(cmd, o); + const r = await this.c.engine.request("POST", `/exec/${execId}/start`, { json: { Detach: false, Tty: false }, timeoutMs: (o.timeoutMs ?? 120_000) + 5_000 }); + if (r.status !== 200) throw new EngineError(r.status, r.body.toString("utf8").slice(0, 300)); + const { stdout, stderr } = demux(r.body); + const info = await this.c.engine.json<{ ExitCode: number; Running: boolean }>("GET", `/exec/${execId}/json`); + return { exitCode: info.ExitCode, stdout, stderr }; + } + + async sh(script: string, opts: { timeoutMs?: number } = {}): Promise { + const cmd = opts.timeoutMs + ? ["timeout", "-s", "KILL", String(Math.max(1, Math.ceil(opts.timeoutMs / 1000))), "sh", "-c", script] + : ["sh", "-c", script]; + const r = await this.execRun(cmd, { timeoutMs: opts.timeoutMs }); + return { exitCode: r.exitCode, stdout: r.stdout.toString("utf8"), stderr: r.stderr.toString("utf8") }; + } + + async writeFile(path: string, data: Uint8Array, opts: { mode?: number } = {}): Promise { + const i = path.lastIndexOf("/"); + const dir = i <= 0 ? "/" : path.slice(0, i); + const name = path.slice(i + 1); + const r = await this.c.engine.request("PUT", `/containers/${this.id}/archive?path=${encodeURIComponent(dir)}`, { + body: tarFile(name, data, opts.mode ?? 0o644), contentType: "application/x-tar", + }); + if (r.status !== 200) throw new EngineError(r.status, `write ${path}: ${r.body.toString("utf8").slice(0, 200)}`); + } + + async readFile(path: string): Promise { + const r = await this.execRun(["cat", path]); + if (r.exitCode !== 0) throw new Error(`read ${path}: ${r.stderr.toString("utf8").trim() || `exit ${r.exitCode}`}`); + return new Uint8Array(r.stdout); + } + + async startProcess(o: StartProcessOpts): Promise { + const n = ++procSeq; + const base = `${PROC_DIR}/proc-${n}`; + const lim = o.timeoutMs ? `timeout -s KILL ${Math.max(1, Math.ceil(o.timeoutMs / 1000))} ` : ""; + // pid file first, then exec so the pid stays the command's; stdout/stderr go to files `logs()` reads back. The + // directory is root-only (0700): the worker's log carries the bot's prints, and no later bot process may read them. + const script = `umask 077; mkdir -p -m 0700 ${PROC_DIR} && echo $$ > ${base}.pid && exec ${lim}"$@" > ${base}.out 2> ${base}.err`; // PROC_DIR: root-only tmpfs + const execId = await this.execCreate(["sh", "-c", script, "sh", ...o.cmd], { env: o.env, cwd: o.cwd }); + const r = await this.c.engine.request("POST", `/exec/${execId}/start`, { json: { Detach: true, Tty: false } }); + if (r.status >= 300) throw new EngineError(r.status, r.body.toString("utf8").slice(0, 300)); + return new LocalProcess(this.c, this, execId, base); + } + + async setEgress(allowOut: string[]): Promise { + const want = new Set(this.c.desiredNetworks(allowOut)); + for (const n of want) if (!this.networks.has(n)) { await this.c.networkOp("connect", n, this.id); this.networks.add(n); } + for (const n of [...this.networks]) if (!want.has(n)) { await this.c.networkOp("disconnect", n, this.id); this.networks.delete(n); } + } + async usage(): Promise | undefined> { return undefined; } + async delete(): Promise { await this.c.deleteSandbox(this.id); } +} + +class LocalProcess implements ProcessHandle { + private readonly c: LocalPlatinum; + private readonly sbx: LocalSandbox; + private readonly execId: string; + private readonly base: string; + constructor(c: LocalPlatinum, sbx: LocalSandbox, execId: string, base: string) { + this.c = c; this.sbx = sbx; this.execId = execId; this.base = base; + } + + async status(): Promise { + const i = await this.c.engine.json<{ Running: boolean; ExitCode: number }>("GET", `/exec/${this.execId}/json`); + return i.Running ? { running: true } : { running: false, exitCode: i.ExitCode }; + } + + async logs(): Promise<{ stdout: string; stderr: string }> { + const r = await this.sbx.sh(`tail -c 65536 ${this.base}.out 2>/dev/null; echo '@@SPLIT@@'; tail -c 65536 ${this.base}.err 2>/dev/null`); + const [stdout = "", stderr = ""] = r.stdout.split("@@SPLIT@@\n"); + return { stdout, stderr }; + } + + async kill(): Promise { + await this.sbx.sh(`kill -KILL "$(cat ${this.base}.pid 2>/dev/null)" 2>/dev/null; true`); + } +} diff --git a/deploy/platinum/runner/src/platinum/real.ts b/deploy/platinum/runner/src/platinum/real.ts new file mode 100644 index 00000000..ff18e434 --- /dev/null +++ b/deploy/platinum/runner/src/platinum/real.ts @@ -0,0 +1,114 @@ +// REAL PlatinumClient on @platinum-dev/sdk (0.9.0). One ephemeral microVM per run. +// Not exercised against a live control plane (no credentials); request shapes are covered by test/real.test.ts with a mock fetch. +import { Platinum, type Sandbox as PtSandbox, type ProcessHandle as PtProcess } from "@platinum-dev/sdk"; +import type { + CreateOpts, ExecResult, PlatinumClient, ProcessHandle, ProcessStatus, Sandbox, SandboxInfo, SandboxSpec, StartProcessOpts, +} from "./types.ts"; + +export interface RealOpts { + apiUrl: string; + token: string; + /** Transport override (tests). */ + fetch?: typeof fetch; +} + +/** The API clamps one-shot exec calls to MAX_EXEC_TIMEOUT_MS (85 s); longer scripts must be managed processes. */ +const EXEC_LIMIT_MS = 80_000; + +export class RealPlatinum implements PlatinumClient { + readonly kind = "platinum" as const; + readonly pt: Platinum; + + constructor(o: RealOpts) { + this.pt = new Platinum({ url: o.apiUrl, token: o.token, fetch: o.fetch }); + } + + async createSandbox(spec: SandboxSpec, opts: CreateOpts = {}): Promise { + const sbx = await this.pt.sandboxes.create( + { + name: spec.name, + template: spec.template, + type: "ephemeral", + auto_stop_minutes: spec.autoStopMinutes, // belt and braces; the runner deletes explicitly + cpu: spec.cpu, + ram_mb: spec.ramMb, + disk_gb: spec.diskGb, + region: spec.region, + metadata: spec.metadata, + // allow wins over deny: hostnames in allowOut stay reachable, everything else is dropped (G14: DNS unverified) + network: { allowOut: spec.allowOut, denyOut: ({ allTraffic }) => [allTraffic] }, + }, + { waitForRunning: true, waitTimeoutMs: opts.timeoutMs ?? 120_000, signal: opts.signal }, + ); + return new RealSandbox(sbx); + } + + async *listSandboxes(): AsyncIterable { + for await (const s of this.pt.sandboxes.iterate({ state: "running" })) { + const row = s as unknown as { id: string; metadata?: Record; createdAt?: string; created_at?: string }; + const metadata: Record = {}; + for (const [k, v] of Object.entries(row.metadata ?? {})) metadata[k] = String(v); + yield { id: row.id, metadata, createdAtMs: new Date(row.createdAt ?? row.created_at ?? 0).getTime() }; + } + } + + async deleteSandbox(id: string): Promise { + try { + await this.pt.sandboxes.delete(id); + } catch (e) { + if ((e as { status?: number }).status === 404) return; + throw e; + } + } +} + +class RealSandbox implements Sandbox { + private readonly sbx: PtSandbox; + readonly id: string; + constructor(sbx: PtSandbox) { this.sbx = sbx; this.id = sbx.id; } + + async sh(script: string, opts: { timeoutMs?: number } = {}): Promise { + const t = opts.timeoutMs; + if (t !== undefined && t > EXEC_LIMIT_MS) { + const p = await this.sbx.process.start({ cmd: ["sh", "-c", script], timeoutMs: t }); + const rec = await p.wait({ timeoutMs: t + 10_000 }); + const l = await p.logs(); + return { exitCode: rec.exit_code, stdout: l.stdout_text, stderr: l.stderr_text }; + } + const r = await this.sbx.sh(script, { timeoutMs: t }); + return { exitCode: r.exit_code, stdout: r.stdout, stderr: r.stderr }; + } + + async writeFile(path: string, data: Uint8Array, opts: { mode?: number } = {}): Promise { + await this.sbx.files.write(path, data); + if (opts.mode !== undefined) (await this.sbx.exec(["chmod", opts.mode.toString(8), path])).check(); + } + + readFile(path: string): Promise { return this.sbx.files.read(path); } + + async startProcess(o: StartProcessOpts): Promise { + const p = await this.sbx.process.start({ cmd: o.cmd, cwd: o.cwd, env: o.env, timeoutMs: o.timeoutMs }); + return new RealProcess(p); + } + + async setEgress(allowOut: string[]): Promise { + await this.sbx.updateNetwork({ allowOut, denyOut: ({ allTraffic }) => [allTraffic] }); + } + + usage(): Promise | undefined> { return this.sbx.usage(); } + async delete(): Promise { await this.sbx.delete(); } +} + +class RealProcess implements ProcessHandle { + private readonly p: PtProcess; + constructor(p: PtProcess) { this.p = p; } + async status(): Promise { + const i = await this.p.info(); + return i.running ? { running: true } : { running: false, exitCode: i.exit_code }; + } + async logs(): Promise<{ stdout: string; stderr: string }> { + const l = await this.p.logs(); + return { stdout: l.stdout_text, stderr: l.stderr_text }; + } + async kill(): Promise { await this.p.kill(); } +} diff --git a/deploy/platinum/runner/src/platinum/types.ts b/deploy/platinum/runner/src/platinum/types.ts new file mode 100644 index 00000000..9353bcfd --- /dev/null +++ b/deploy/platinum/runner/src/platinum/types.ts @@ -0,0 +1,71 @@ +// The sandbox backend the runner needs, nothing more. Two implementations: +// real.ts @platinum-dev/sdk against a Platinum control plane (one microVM per run) +// local.ts a Docker-Engine-API container per run (podman or docker) on the arena's network, for dev / CI / the e2e +// Everything above this seam (job.ts, service.ts) is identical in both. + +export interface SandboxSpec { + /** Unique, human readable (used as the container / sandbox name). */ + name: string; + /** Platinum template name, or (local) an image reference. */ + template: string; + cpu: number; + ramMb: number; + diskGb: number; + region?: string; + autoStopMinutes: number; + /** String metadata; `sharingan_job` is what the orphan reaper keys on. */ + metadata: Record; + /** Hostnames the sandbox may reach; everything else is denied. */ + allowOut: string[]; +} + +export interface ExecResult { exitCode: number; stdout: string; stderr: string } + +export interface ProcessStatus { running: boolean; exitCode?: number } + +export interface ProcessHandle { + status(): Promise; + logs(): Promise<{ stdout: string; stderr: string }>; + kill(): Promise; +} + +export interface StartProcessOpts { + cmd: string[]; + cwd?: string; + env?: Record; + /** Guest-side hard stop for the process. */ + timeoutMs?: number; +} + +export interface Sandbox { + readonly id: string; + /** Run a shell script to completion (as root). Throws on transport errors, returns non-zero exit codes. */ + sh(script: string, opts?: { timeoutMs?: number }): Promise; + writeFile(path: string, data: Uint8Array, opts?: { mode?: number }): Promise; + readFile(path: string): Promise; + startProcess(opts: StartProcessOpts): Promise; + /** Replace the egress allowlist (hostnames). Used to drop PyPI after `pip install`. */ + setEgress(allowOut: string[]): Promise; + /** Backend's own bill for this sandbox so far, if it can say (Platinum: GET .../usage). */ + usage(): Promise | undefined>; + delete(): Promise; +} + +export interface SandboxInfo { id: string; metadata: Record; createdAtMs: number } + +export interface CreateOpts { signal?: AbortSignal; timeoutMs?: number } + +export interface PlatinumClient { + readonly kind: "platinum" | "local"; + createSandbox(spec: SandboxSpec, opts?: CreateOpts): Promise; + /** Running sandboxes this client can see (for the orphan reaper). */ + listSandboxes(): AsyncIterable; + /** Delete by id without a handle (reaper). Already-gone is not an error. */ + deleteSandbox(id: string): Promise; +} + +export const sleep = (ms: number, signal?: AbortSignal): Promise => + new Promise((resolve, reject) => { + const t = setTimeout(resolve, ms); + signal?.addEventListener("abort", () => { clearTimeout(t); reject(new Error("aborted")); }, { once: true }); + }); diff --git a/deploy/platinum/runner/src/provision.ts b/deploy/platinum/runner/src/provision.ts new file mode 100644 index 00000000..c5a7734a --- /dev/null +++ b/deploy/platinum/runner/src/provision.ts @@ -0,0 +1,19 @@ +// One-off: build the Platinum templates from the pushed images. Run by hand, never from the request path. +// PT_TOKEN=... PT_API_URL=... node --experimental-strip-types src/provision.ts sharingan-bot [sharingan-arena] +// Needs a key with templates:write. Images must already be pushed to a registry Platinum can pull anonymously (DESIGN.md G7). +// (Local mode has no templates: the "template" is the image built by deploy/local/e2e.sh.) +import { readFileSync } from "node:fs"; +import { Platinum, Template } from "@platinum-dev/sdk"; + +const pt = new Platinum({ url: process.env.PT_API_URL ?? "https://api.platinum.dev", token: process.env.PT_TOKEN }); +const names = process.argv.slice(2); +if (!names.length) { console.error("usage: provision.ts