diff --git a/services/flysim/crates/fly-session/fixtures/legacy-toy/circuit-roles.json b/services/flysim/crates/fly-session/fixtures/legacy-toy/circuit-roles.json new file mode 100644 index 0000000..8bac168 --- /dev/null +++ b/services/flysim/crates/fly-session/fixtures/legacy-toy/circuit-roles.json @@ -0,0 +1 @@ +{"neurons":4096,"roles":{"kenyon":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,381,382,383,384,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,462,463,464,465,466,467,468,469,470,471,472,473,474,475,476,477,478,479,480,481,482,483,484,485,486,487,488,489,490,491,492,493,494,495,496,497,498,499,500,501,502,503,504,505,506,507,508,509,510,511,512,513,514,515,516,517,518,519,520,521,522,523,524,525,526,527,528,529,530,531,532,533,534,535,536,537,538,539,540,541,542,543,544,545,546,547,548,549,550,551,552,553,554,555,556,557,558,559,560,561,562,563,564,565,566,567,568,569,570,571,572,573,574,575,576,577,578,579,580,581,582,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,611,612,613,614,615,616,617,618,619,620,621,622,623,624,625,626,627,628,629,630,631,632,633,634,635,636,637,638,639,640,641,642,643,644,645,646,647,648,649,650,651,652,653,654,655,656,657,658,659,660,661,662,663,664,665,666,667,668,669,670,671,672,673,674,675,676,677,678,679,680,681,682,683,684,685,686,687,688,689,690,691,692,693,694,695,696,697,698,699,700,701,702,703,704,705,706,707,708,709,710,711,712,713,714,715,716,717,718,719,720,721,722,723,724,725,726,727,728,729,730,731,732,733,734,735,736,737,738,739,740,741,742,743,744,745,746,747,748,749,750,751,752,753,754,755,756,757,758,759,760,761,762,763,764,765,766,767,768,769,770,771,772,773,774,775,776,777,778,779,780,781,782,783,784,785,786,787,788,789,790,791,792,793,794,795,796,797,798,799,800,801,802,803,804,805,806,807,808,809,810,811,812,813,814,815,816,817,818,819,820,821,822,823,824,825,826,827,828,829,830,831,832,833,834,835,836,837,838,839,840,841,842,843,844,845,846,847,848,849,850,851,852,853,854,855,856,857,858,859,860,861,862,863,864,865,866,867,868,869,870,871,872,873,874,875,876,877,878,879,880,881,882,883,884,885,886,887,888,889,890,891,892,893,894,895,896,897,898,899,900,901,902,903,904,905,906,907,908,909,910,911,912,913,914,915,916,917,918,919,920,921,922,923,924,925,926,927,928,929,930,931,932,933,934,935,936,937,938,939,940,941,942,943,944,945,946,947,948,949,950,951,952,953,954,955,956,957,958,959,960,961,962,963,964,965,966,967,968,969,970,971,972,973,974,975,976,977,978,979,980,981,982,983,984,985,986,987,988,989,990,991,992,993,994,995,996,997,998,999,1000,1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1011,1012,1013,1014,1015,1016,1017,1018,1019,1020,1021,1022,1023],"mbon":[1024,1025,1026,1027,1028,1029,1030,1031,1032,1033,1034,1035,1036,1037,1038,1039,1040,1041,1042,1043,1044,1045,1046,1047,1048,1049,1050,1051,1052,1053,1054,1055,1056,1057,1058,1059,1060,1061,1062,1063,1064,1065,1066,1067,1068,1069,1070,1071,1072,1073,1074,1075,1076,1077,1078,1079,1080,1081,1082,1083,1084,1085,1086,1087,1088,1089,1090,1091,1092,1093,1094,1095,1096,1097,1098,1099,1100,1101,1102,1103,1104,1105,1106,1107,1108,1109,1110,1111,1112,1113,1114,1115,1116,1117,1118,1119,1120,1121,1122,1123,1124,1125,1126,1127,1128,1129,1130,1131,1132,1133,1134,1135,1136,1137,1138,1139,1140,1141,1142,1143,1144,1145,1146,1147,1148,1149,1150,1151,1152,1153,1154,1155,1156,1157,1158,1159,1160,1161,1162,1163,1164,1165,1166,1167,1168,1169,1170,1171,1172,1173,1174,1175,1176,1177,1178,1179,1180,1181,1182,1183,1184,1185,1186,1187,1188,1189,1190,1191,1192,1193,1194,1195,1196,1197,1198,1199,1200,1201,1202,1203,1204,1205,1206,1207,1208,1209,1210,1211,1212,1213,1214,1215,1216,1217,1218,1219,1220,1221,1222,1223,1224,1225,1226,1227,1228,1229,1230,1231,1232,1233,1234,1235,1236,1237,1238,1239,1240,1241,1242,1243,1244,1245,1246,1247,1248,1249,1250,1251,1252,1253,1254,1255,1256,1257,1258,1259,1260,1261,1262,1263,1264,1265,1266,1267,1268,1269,1270,1271,1272,1273,1274,1275,1276,1277,1278,1279],"macro_go_out":[1100,1101,1102,1103,1104,1105,1106,1107,1108,1109,1110,1111,1112,1113,1114,1115],"macro_talk":[1116,1117,1118,1119,1120,1121,1122,1123,1124,1125,1126,1127,1128,1129,1130,1131],"macro_menu":[1132,1133,1134,1135,1136,1137,1138,1139,1140,1141,1142,1143,1144,1145,1146,1147],"macro_next":[1148,1149,1150,1151,1152,1153,1154,1155,1156,1157,1158,1159,1160,1161,1162,1163]}} diff --git a/services/flysim/crates/fly-session/fixtures/legacy-toy/indptr.binz b/services/flysim/crates/fly-session/fixtures/legacy-toy/indptr.binz new file mode 100644 index 0000000..41935a3 Binary files /dev/null and b/services/flysim/crates/fly-session/fixtures/legacy-toy/indptr.binz differ diff --git a/services/flysim/crates/fly-session/fixtures/legacy-toy/meta.json b/services/flysim/crates/fly-session/fixtures/legacy-toy/meta.json new file mode 100644 index 0000000..ce8f896 --- /dev/null +++ b/services/flysim/crates/fly-session/fixtures/legacy-toy/meta.json @@ -0,0 +1 @@ +{"schemaVersion":1,"dataset":"legacy-toy","neurons":4096,"edges":40960,"roles":{"command_0":[1344,1345,1346,1347,1348,1349,1350,1351,1352,1353,1354,1355,1356,1357,1358,1359,1360,1361,1362,1363,1364,1365,1366,1367,1368,1369,1370,1371,1372,1373,1374,1375],"command_1":[1376,1377,1378,1379,1380,1381,1382,1383,1384,1385,1386,1387,1388,1389,1390,1391,1392,1393,1394,1395,1396,1397,1398,1399,1400,1401,1402,1403,1404,1405,1406,1407],"command_2":[1408,1409,1410,1411,1412,1413,1414,1415,1416,1417,1418,1419,1420,1421,1422,1423,1424,1425,1426,1427,1428,1429,1430,1431,1432,1433,1434,1435,1436,1437,1438,1439],"command_3":[1440,1441,1442,1443,1444,1445,1446,1447,1448,1449,1450,1451,1452,1453,1454,1455,1456,1457,1458,1459,1460,1461,1462,1463,1464,1465,1466,1467,1468,1469,1470,1471],"command_4":[1472,1473,1474,1475,1476,1477,1478,1479,1480,1481,1482,1483,1484,1485,1486,1487,1488,1489,1490,1491,1492,1493,1494,1495,1496,1497,1498,1499,1500,1501,1502,1503],"command_5":[1504,1505,1506,1507,1508,1509,1510,1511,1512,1513,1514,1515,1516,1517,1518,1519,1520,1521,1522,1523,1524,1525,1526,1527,1528,1529,1530,1531,1532,1533,1534,1535],"command_6":[1536,1537,1538,1539,1540,1541,1542,1543,1544,1545,1546,1547,1548,1549,1550,1551,1552,1553,1554,1555,1556,1557,1558,1559,1560,1561,1562,1563,1564,1565,1566,1567],"command_7":[1568,1569,1570,1571,1572,1573,1574,1575,1576,1577,1578,1579,1580,1581,1582,1583,1584,1585,1586,1587,1588,1589,1590,1591,1592,1593,1594,1595,1596,1597,1598,1599],"reward_pam":[1280,1281,1282,1283,1284,1285,1286,1287,1288,1289,1290,1291,1292,1293,1294,1295,1296,1297,1298,1299,1300,1301,1302,1303,1304,1305,1306,1307,1308,1309,1310,1311,1312,1313,1314,1315,1316,1317,1318,1319,1320,1321,1322,1323,1324,1325,1326,1327,1328,1329,1330,1331,1332,1333,1334,1335,1336,1337,1338,1339,1340,1341,1342,1343],"steer_left":[2400,2401,2402,2403,2404,2405,2406,2407,2408,2409,2410,2411,2412,2413,2414,2415,2416,2417,2418,2419,2420,2421,2422,2423,2424,2425,2426,2427,2428,2429,2430,2431],"steer_right":[2432,2433,2434,2435,2436,2437,2438,2439,2440,2441,2442,2443,2444,2445,2446,2447,2448,2449,2450,2451,2452,2453,2454,2455,2456,2457,2458,2459,2460,2461,2462,2463],"visual_l1":[1600,1601,1602,1603,1604,1605,1606,1607,1608,1609,1610,1611,1612,1613,1614,1615,1616,1617,1618,1619,1620,1621,1622,1623,1624,1625,1626,1627,1628,1629,1630,1631,1632,1633,1634,1635,1636,1637,1638,1639,1640,1641,1642,1643,1644,1645,1646,1647,1648,1649,1650,1651,1652,1653,1654,1655,1656,1657,1658,1659,1660,1661,1662,1663,1664,1665,1666,1667,1668,1669,1670,1671,1672,1673,1674,1675,1676,1677,1678,1679,1680,1681,1682,1683,1684,1685,1686,1687,1688,1689,1690,1691,1692,1693,1694,1695,1696,1697,1698,1699,1700,1701,1702,1703,1704,1705,1706,1707,1708,1709,1710,1711,1712,1713,1714,1715,1716,1717,1718,1719,1720,1721,1722,1723,1724,1725,1726,1727,1728,1729,1730,1731,1732,1733,1734,1735,1736,1737,1738,1739,1740,1741,1742,1743,1744,1745,1746,1747,1748,1749,1750,1751,1752,1753,1754,1755,1756,1757,1758,1759,1760,1761,1762,1763,1764,1765,1766,1767,1768,1769,1770,1771,1772,1773,1774,1775,1776,1777,1778,1779,1780,1781,1782,1783,1784,1785,1786,1787,1788,1789,1790,1791,1792,1793,1794,1795,1796,1797,1798,1799,1800,1801,1802,1803,1804,1805,1806,1807,1808,1809,1810,1811,1812,1813,1814,1815,1816,1817,1818,1819,1820,1821,1822,1823,1824,1825,1826,1827,1828,1829,1830,1831,1832,1833,1834,1835,1836,1837,1838,1839,1840,1841,1842,1843,1844,1845,1846,1847,1848,1849,1850,1851,1852,1853,1854,1855,1856,1857,1858,1859,1860,1861,1862,1863,1864,1865,1866,1867,1868,1869,1870,1871,1872,1873,1874,1875,1876,1877,1878,1879,1880,1881,1882,1883,1884,1885,1886,1887,1888,1889,1890,1891,1892,1893,1894,1895,1896,1897,1898,1899,1900,1901,1902,1903,1904,1905,1906,1907,1908,1909,1910,1911,1912,1913,1914,1915,1916,1917,1918,1919,1920,1921,1922,1923,1924,1925,1926,1927,1928,1929,1930,1931,1932,1933,1934,1935,1936,1937,1938,1939,1940,1941,1942,1943,1944,1945,1946,1947,1948,1949,1950,1951,1952,1953,1954,1955,1956,1957,1958,1959,1960,1961,1962,1963,1964,1965,1966,1967,1968,1969,1970,1971,1972,1973,1974,1975,1976,1977,1978,1979,1980,1981,1982,1983,1984,1985,1986,1987,1988,1989,1990,1991,1992,1993,1994,1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019,2020,2021,2022,2023,2024,2025,2026,2027,2028,2029,2030,2031,2032,2033,2034,2035,2036,2037,2038,2039,2040,2041,2042,2043,2044,2045,2046,2047,2048,2049,2050,2051,2052,2053,2054,2055,2056,2057,2058,2059,2060,2061,2062,2063,2064,2065,2066,2067,2068,2069,2070,2071,2072,2073,2074,2075,2076,2077,2078,2079,2080,2081,2082,2083,2084,2085,2086,2087,2088,2089,2090,2091,2092,2093,2094,2095,2096,2097,2098,2099,2100,2101,2102,2103,2104,2105,2106,2107,2108,2109,2110,2111,2112,2113,2114,2115,2116,2117,2118,2119,2120,2121,2122,2123,2124,2125,2126,2127,2128,2129,2130,2131,2132,2133,2134,2135,2136,2137,2138,2139,2140,2141,2142,2143,2144,2145,2146,2147,2148,2149,2150,2151,2152,2153,2154,2155,2156,2157,2158,2159,2160,2161,2162,2163,2164,2165,2166,2167,2168,2169,2170,2171,2172,2173,2174,2175,2176,2177,2178,2179,2180,2181,2182,2183,2184,2185,2186,2187,2188,2189,2190,2191,2192,2193,2194,2195,2196,2197,2198,2199,2200,2201,2202,2203,2204,2205,2206,2207,2208,2209,2210,2211,2212,2213,2214,2215,2216,2217,2218,2219,2220,2221,2222,2223,2224,2225,2226,2227,2228,2229,2230,2231,2232,2233,2234,2235,2236,2237,2238,2239,2240,2241,2242,2243,2244,2245,2246,2247,2248,2249,2250,2251,2252,2253,2254,2255,2256,2257,2258,2259,2260,2261,2262,2263,2264,2265,2266,2267,2268,2269,2270,2271,2272,2273,2274,2275,2276,2277,2278,2279,2280,2281,2282,2283,2284,2285,2286,2287,2288,2289,2290,2291,2292,2293,2294,2295,2296,2297,2298,2299,2300,2301,2302,2303,2304,2305,2306,2307,2308,2309,2310,2311,2312,2313,2314,2315,2316,2317,2318,2319,2320,2321,2322,2323,2324,2325,2326,2327,2328,2329,2330,2331,2332,2333,2334,2335,2336,2337,2338,2339,2340,2341,2342,2343,2344,2345,2346,2347,2348,2349,2350,2351,2352,2353,2354,2355,2356,2357,2358,2359,2360,2361,2362,2363,2364,2365,2366,2367,2368,2369,2370,2371,2372,2373,2374,2375,2376,2377,2378,2379,2380,2381,2382,2383,2384,2385,2386,2387,2388,2389,2390,2391,2392,2393,2394,2395,2396,2397,2398,2399]},"visual":{"population":"toy-retina","count":800}} diff --git a/services/flysim/crates/fly-session/fixtures/legacy-toy/targets.binz b/services/flysim/crates/fly-session/fixtures/legacy-toy/targets.binz new file mode 100644 index 0000000..84d574d Binary files /dev/null and b/services/flysim/crates/fly-session/fixtures/legacy-toy/targets.binz differ diff --git a/services/flysim/crates/fly-session/fixtures/legacy-toy/visual-hemisphere.binz b/services/flysim/crates/fly-session/fixtures/legacy-toy/visual-hemisphere.binz new file mode 100644 index 0000000..4203e09 Binary files /dev/null and b/services/flysim/crates/fly-session/fixtures/legacy-toy/visual-hemisphere.binz differ diff --git a/services/flysim/crates/fly-session/fixtures/legacy-toy/visual-indices.binz b/services/flysim/crates/fly-session/fixtures/legacy-toy/visual-indices.binz new file mode 100644 index 0000000..1c50f0e Binary files /dev/null and b/services/flysim/crates/fly-session/fixtures/legacy-toy/visual-indices.binz differ diff --git a/services/flysim/crates/fly-session/fixtures/legacy-toy/visual-xy.binz b/services/flysim/crates/fly-session/fixtures/legacy-toy/visual-xy.binz new file mode 100644 index 0000000..feb31e6 Binary files /dev/null and b/services/flysim/crates/fly-session/fixtures/legacy-toy/visual-xy.binz differ diff --git a/services/flysim/crates/fly-session/fixtures/legacy-toy/weights.binz b/services/flysim/crates/fly-session/fixtures/legacy-toy/weights.binz new file mode 100644 index 0000000..c148f83 Binary files /dev/null and b/services/flysim/crates/fly-session/fixtures/legacy-toy/weights.binz differ diff --git a/services/flysim/crates/fly-session/src/legacy_parity.rs b/services/flysim/crates/fly-session/src/legacy_parity.rs new file mode 100644 index 0000000..557e9d2 --- /dev/null +++ b/services/flysim/crates/fly-session/src/legacy_parity.rs @@ -0,0 +1,1510 @@ +//! AGENT-01's parity harness: recorded inputs, a reference that drives [`NeuralAgent`] directly +//! in the legacy frame order, the same inputs driven through a launched [`LegacyAgentWorker`] +//! over the bus, and a record-by-record comparison. +//! +//! ```text +//! LegacyScript ──> DirectReference (NeuralAgent in Sim::step_frame order) ──> Vec +//! ──> AgentDriver (Agent.* RPCs to a launched worker) ──> Vec +//! └─ compare() ─┘ +//! ``` +//! +//! A [`ParityRecord`] carries only what both sides can observe of the agent: the ticks, the +//! brain clock and its exact remainder, the decision, the whole telemetry, the digest of the +//! transition's spike bitset and, at declared checkpoints, the digest of the full agent state +//! (`agent_to_chunks`). A state digest is exact equality of every membrane, trace, gain, rate, +//! RNG and decoder field. +//! +//! [`ReferenceSource`] is the seam for FND-01: a reader of `LegacyFrame`'s `FLY_TRACE` is a +//! second reference beside [`DirectReference`], producing the same records from the running +//! loop instead of from a transcription of it. Nothing here depends on it. +//! +//! [`toy`] is the committed toy connectome the goldens run on; the real dataset is optional. + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use fly_session_types::extensions::{ + AgentRollbackParams, AgentRollbackResult, METHOD_AGENT_ROLLBACK, ROLLBACK_POLICY, +}; +use fly_session_types::gameboy::{self, ChannelsDecision, Location, ReadoutContext}; +use flybrain_core::agent::{AgentConfig as CoreAgentConfig, NeuralAgent}; +use flybrain_core::dataset::BrainDataset; +use flybrain_core::decoder::gameboy::{gameboy_decoder_config_with_macros, to_button_mask}; +use flybrain_core::envelope::{agent_from_chunks, agent_to_chunks, decode_envelope}; +use flybrain_core::rng::Xorshift32; +use flybus::{Client, Grants, Pattern, Policy, Router, RouterConfig}; +use serde_json::{Value, json}; + +use crate::launcher::{ + ExecutionMode, Launcher, LegacyAgentLaunch, SUPERVISOR_CLIENT, ThreadBudget, Via, +}; +use crate::legacy_agent::{ + LegacyAgentProfile, LegacyProfileKind, PAYLOAD_MAGIC, SPIKES_ATTACHMENT, channels_decision, + legacy_remainder_to_rational, spike_bitset, telemetry_of, +}; +use crate::rpc::{Serials, WorkerRef, call}; +use crate::types::*; + +/// The frame size: 160 x 144 RGBA8. +pub const FRAME_BYTES: usize = (gameboy::VIEW_WIDTH * gameboy::VIEW_HEIGHT * 4) as usize; +/// The legacy default seed. The profile's kernel version pins it (`lif-1ms-f64-v2` hashes the +/// seed into any other value), so it is the only seed this profile accepts. +pub const LEGACY_SEED: i32 = 22_222; + +// ------------------------------------------------------------------------------------------- +// The toy connectome + +pub mod toy { + //! The committed toy connectome, `fixtures/legacy-toy`: 4,096 neurons, sized as the + //! oracle's synthetic connectome is (`packages/brain/tools/golden.ts`) so that 300 noise + //! kicks leave the network sub-threshold and the connectome drives it, with the roles the + //! legacy readout and plasticity read -- `command_0..7`, `kenyon`, `mbon`, `reward_pam` -- + //! and four `macro_*` populations merged after the fingerprint, as FAFB's are. + + use std::io::Write as _; + use std::path::{Path, PathBuf}; + + use flate2::Compression; + use flate2::write::GzEncoder; + use flybrain_core::rng::Xorshift32; + use serde_json::{Map, Value, json}; + + /// The macro channels of the toy composition, in composition order. + pub const MACRO_CHANNELS: [&str; 4] = + ["macro_go_out", "macro_talk", "macro_menu", "macro_next"]; + pub const NEURONS: u32 = 4_096; + const EDGES_PER_NEURON: u32 = 10; + const SEED: i32 = 20_260_923; + + /// `services/flysim/crates/fly-session/fixtures/legacy-toy`. + pub fn dir() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/legacy-toy") + } + + fn range(from: u32, to: u32) -> Vec { + (from..to).collect() + } + + fn gz(bytes: &[u8]) -> Vec { + // flate2's default header has no name and a zero mtime, so the bytes are reproducible. + let mut encoder = GzEncoder::new(Vec::new(), Compression::best()); + encoder.write_all(bytes).expect("in memory"); + encoder.finish().expect("in memory") + } + + /// Every file of the toy dataset, by name, as it is committed. + pub fn files() -> Vec<(String, Vec)> { + let mut random = Xorshift32::new(SEED); + let kenyon = (0u32, 1_024u32); + let mbon = (1_024u32, 1_280u32); + let visual = range(1_600, 2_400); + + let mut roles = Map::new(); + for command in 0..8u32 { + roles.insert( + format!("command_{command}"), + json!(range(1_344 + command * 32, 1_376 + command * 32)), + ); + } + roles.insert("reward_pam".to_owned(), json!(range(1_280, 1_344))); + roles.insert("steer_left".to_owned(), json!(range(2_400, 2_432))); + roles.insert("steer_right".to_owned(), json!(range(2_432, 2_464))); + roles.insert("visual_l1".to_owned(), json!(visual)); + + let mut indptr = Vec::with_capacity(NEURONS as usize + 1); + let mut targets: Vec = Vec::new(); + let mut weights: Vec = Vec::new(); + for source in 0..NEURONS { + indptr.push(targets.len() as u32); + let is_kenyon = source >= kenyon.0 && source < kenyon.1; + for edge in 0..EDGES_PER_NEURON { + let forced = is_kenyon && edge < 4; + let target = if forced { + mbon.0 + (random.next_f64() * f64::from(mbon.1 - mbon.0)).floor() as u32 + } else { + (random.next_f64() * f64::from(NEURONS)).floor() as u32 + }; + let magnitude = 1 + (random.next_f64() * 40.0).floor() as i16; + targets.push(target); + weights.push(if !forced && random.next_f64() < 0.2 { + -magnitude + } else { + magnitude + }); + } + } + indptr.push(targets.len() as u32); + + let mut visual_xy = Vec::with_capacity(visual.len() * 2); + for column in 0..visual.len() { + visual_xy.push((column % 40) as f32 * 7.5); + visual_xy.push((column / 40) as f32 * 5.25); + } + let hemisphere: Vec = (0..visual.len()).map(|c| (c % 2) as u8).collect(); + + let meta = json!({ + "schemaVersion": 1, + "dataset": "legacy-toy", + "neurons": NEURONS, + "edges": targets.len(), + "roles": Value::Object(roles), + "visual": {"population": "toy-retina", "count": visual.len()}, + }); + let circuits = json!({ + "neurons": NEURONS, + "roles": { + "kenyon": range(kenyon.0, kenyon.1), + "mbon": range(mbon.0, mbon.1), + // Relabelled MBONs, outside the fingerprint, as the FAFB macro populations are. + "macro_go_out": range(1_100, 1_116), + "macro_talk": range(1_116, 1_132), + "macro_menu": range(1_132, 1_148), + "macro_next": range(1_148, 1_164), + }, + }); + let le32 = |values: &[u32]| { + values + .iter() + .flat_map(|v| v.to_le_bytes()) + .collect::>() + }; + let text = |value: &Value| { + let mut s = serde_json::to_string(value).expect("json"); + s.push('\n'); + s.into_bytes() + }; + vec![ + ("meta.json".to_owned(), text(&meta)), + ("circuit-roles.json".to_owned(), text(&circuits)), + ("indptr.binz".to_owned(), gz(&le32(&indptr))), + ("targets.binz".to_owned(), gz(&le32(&targets))), + ( + "weights.binz".to_owned(), + gz(&weights + .iter() + .flat_map(|v| v.to_le_bytes()) + .collect::>()), + ), + ("visual-indices.binz".to_owned(), gz(&le32(&visual))), + ("visual-hemisphere.binz".to_owned(), gz(&hemisphere)), + ( + "visual-xy.binz".to_owned(), + gz(&visual_xy + .iter() + .flat_map(|v| v.to_le_bytes()) + .collect::>()), + ), + ] + } + + /// Writes the dataset into `dir`. + pub fn write(dir: &Path) -> std::io::Result<()> { + std::fs::create_dir_all(dir)?; + for (name, bytes) in files() { + std::fs::write(dir.join(name), bytes)?; + } + Ok(()) + } +} + +/// `/data/fafb-v783`, or `None` where the dataset is not checked out. +pub fn fafb_dir() -> Option { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../../data/fafb-v783"); + dir.join("meta.json").is_file().then_some(dir) +} + +// ------------------------------------------------------------------------------------------- +// Recorded inputs + +/// One reward event of the legacy adapter: a value for `reinforce` and a pulse for +/// `stimulate`. The task turns it into one `Reward` and one `reward-pulse` `Stimulus`. +#[derive(Clone, Debug, PartialEq)] +pub struct RewardEvent { + pub value: f64, + pub stimulation_ms: f64, +} + +/// One step of a recorded run. +#[derive(Clone, Debug, PartialEq)] +pub enum ScriptStep { + /// One transition: sugar admitted before it, the frame the environment produced, the + /// adapter's reward events, and the next decision context. + Frame { + sugar: Vec, + frame: usize, + rewards: Vec, + next_context: ReadoutContext, + }, + /// `legacy-ratchet-rollback-v1` at the boundary just reached: the slot's archived frame and + /// the context the executor's observation of the restored world produced. + Rollback { + frame: usize, + context: ReadoutContext, + }, + /// A group restore at the boundary just reached into a fresh agent + /// (`legacy-transient-reset`): a FLYSIM01-style load into a new process. + Restore, +} + +/// A recorded run: the macro channels, the frame pool, the first frame and context, and the +/// steps. The frames are the environment's output, so they are inputs here. +#[derive(Clone, Debug)] +pub struct LegacyScript { + pub name: String, + pub macro_channels: Vec, + pub frames: Arc>>, + pub initial_frame: usize, + pub initial_context: ReadoutContext, + pub steps: Vec, + /// Step indices after which the full agent state is compared. + pub checkpoints: BTreeSet, +} + +/// A deterministic pool of frames with distinct overall brightness, so the retina drive differs +/// from frame to frame and the connectome has something to respond to. +pub fn frame_pool(count: usize, seed: i32) -> Vec> { + let mut random = Xorshift32::new(seed); + (0..count) + .map(|index| { + let scale = (index + 1) as f64 / count as f64; + (0..FRAME_BYTES) + .map(|byte| { + if byte % 4 == 3 { + 255 + } else { + (random.next_f64() * 256.0 * scale).floor() as u8 + } + }) + .collect() + }) + .collect() +} + +fn context(boot: bool, bound: &[&str], location: Option<(u32, u32, u32)>) -> ReadoutContext { + ReadoutContext { + boot, + bound: bound.iter().map(|b| (*b).to_owned()).collect(), + location: location.map(|(area, x, y)| Location { area, x, y }), + } +} + +/// The macros-mode toy scenario: boot and play, a still location long enough for the blocked +/// rule, a battle (no location), sugar overlapping a pulse, reward events on a schedule with a +/// zero-value one, a rollback, a restore into a fresh worker and play after both. +pub fn toy_macros_script(frames: usize) -> LegacyScript { + let channels: Vec = toy::MACRO_CHANNELS + .iter() + .map(|c| (*c).to_owned()) + .collect(); + let bound_at = |k: usize| -> Vec<&'static str> { + match k { + 0..60 => vec![], + 60..130 => vec!["macro_go_out", "macro_talk"], + 130..200 => vec!["macro_talk", "macro_menu", "macro_next"], + _ => vec!["macro_go_out", "macro_menu"], + } + }; + let location_at = |k: usize| -> Option<(u32, u32, u32)> { + match k { + 0..20 => None, + 20..90 => Some((1, 5, 5)), + 90..96 => None, + _ => Some((1, 5 + (k / 30) as u32, 5)), + } + }; + let mut steps = Vec::new(); + for k in 1..=frames { + let sugar = match k { + 25 => vec![300.0], + 26 => vec![100.0], + 170 => vec![500.0, 40.0], + _ => vec![], + }; + let mut rewards = Vec::new(); + if k % 17 == 0 { + rewards.push(RewardEvent { + value: 0.4, + stimulation_ms: 120.0, + }); + } + if k == 50 { + rewards.push(RewardEvent { + value: 0.25, + stimulation_ms: 80.0, + }); + rewards.push(RewardEvent { + value: 0.5, + stimulation_ms: 200.0, + }); + } + if k == 77 { + rewards.push(RewardEvent { + value: 0.0, + stimulation_ms: 60.0, + }); + } + steps.push(ScriptStep::Frame { + sugar, + frame: (k * 3) % 8, + rewards, + next_context: context(k < 40, &bound_at(k), location_at(k)), + }); + if k == 120 { + steps.push(ScriptStep::Rollback { + frame: 5, + context: context(false, &bound_at(k), Some((2, 3, 4))), + }); + } + if k == 190 { + steps.push(ScriptStep::Restore); + } + } + let checkpoints: BTreeSet = steps + .iter() + .enumerate() + .filter(|(i, _)| i % 40 == 39) + .map(|(i, _)| i) + .chain([steps.len() - 1]) + .collect(); + LegacyScript { + name: "toy-macros".to_owned(), + macro_channels: channels, + frames: Arc::new(frame_pool(8, 4_242)), + initial_frame: 0, + initial_context: context(true, &[], None), + steps, + checkpoints, + } +} + +/// The raw-mode toy scenario: no macro group, a still location, rewards, a rollback. +pub fn toy_raw_script(frames: usize) -> LegacyScript { + let mut steps = Vec::new(); + for k in 1..=frames { + steps.push(ScriptStep::Frame { + sugar: if k == 10 { vec![250.0] } else { vec![] }, + frame: (k * 5) % 8, + rewards: if k % 13 == 0 { + vec![RewardEvent { + value: 0.3, + stimulation_ms: 120.0, + }] + } else { + vec![] + }, + next_context: context(k < 30, &[], if k > 5 { Some((7, 1, 1)) } else { None }), + }); + if k == 60 { + steps.push(ScriptStep::Rollback { + frame: 2, + context: context(false, &[], None), + }); + } + } + let last = steps.len() - 1; + LegacyScript { + name: "toy-raw".to_owned(), + macro_channels: Vec::new(), + frames: Arc::new(frame_pool(8, 99)), + initial_frame: 1, + initial_context: context(true, &[], None), + steps, + checkpoints: [29, last].into_iter().collect(), + } +} + +// ------------------------------------------------------------------------------------------- +// Records + +/// What both sides can observe of one step. +#[derive(Clone, Debug, PartialEq)] +pub struct ParityRecord { + /// 0 is Initialize; step `i` of the script is record `i + 1`. + pub index: usize, + pub kind: &'static str, + /// The committed boundary after the step. + pub boundary: u64, + pub ticks: u64, + pub brain_ticks: u64, + pub remainder: RationalNs, + pub decision: Option, + pub telemetry: Option, + /// SHA-256 of the transition's spike bitset. + pub spikes: Option, + /// SHA-256 of the full agent state, at a checkpoint. + pub state: Option, +} + +impl ParityRecord { + pub fn to_json(&self) -> Value { + json!({ + "index": self.index, + "kind": self.kind, + "boundary": self.boundary.to_string(), + "ticks": self.ticks.to_string(), + "brainTicks": self.brain_ticks.to_string(), + "remainder": self.remainder.to_json(), + "decision": self.decision.as_ref().map_or(Value::Null, DomainType::to_json), + "telemetry": self.telemetry.as_ref().map_or(Value::Null, |t| t.to_json()), + "spikes": self.spikes, + "state": self.state, + }) + } + + pub fn digest(&self) -> Digest { + digest_of(&self.to_json()).expect("a record canonicalizes") + } + + /// One readable line for a golden file: the fields a reviewer reads, then the digest of + /// the whole record. + pub fn row(&self) -> String { + let (mask, macro_channel) = match &self.decision { + Some(d) => ( + format!("{:02x}", d.mask()), + d.macro_channel.clone().unwrap_or_else(|| "-".to_owned()), + ), + None => ("--".to_owned(), "-".to_owned()), + }; + let pulse = self + .telemetry + .as_ref() + .and_then(|t| t.stimulus_remaining_ms) + .map_or("-".to_owned(), |ms| format!("{ms}")); + format!( + "{} {} b{} t{} bt{} m{} {} p{} {}{}", + self.index, + self.kind, + self.boundary, + self.ticks, + self.brain_ticks, + mask, + macro_channel, + pulse, + &self.digest()[..16], + if self.state.is_some() { " state" } else { "" } + ) + } +} + +/// The digest of a full agent state: every chunk and the manifest `agent_to_chunks` writes. +pub fn state_digest(state: &flybrain_core::agent::AgentState) -> Digest { + let chunks = agent_to_chunks(state); + let mut bytes = chunks.manifest.stringify().into_bytes(); + for (name, chunk) in &chunks.chunks { + bytes.extend_from_slice(name.as_bytes()); + bytes.extend_from_slice(&(chunk.len() as u64).to_le_bytes()); + bytes.extend_from_slice(chunk); + } + digest_of_bytes(&bytes) +} + +/// The state digest of a worker's capture payload. +pub fn payload_state_digest(payload: &[u8]) -> Result { + let parts = decode_envelope(payload, PAYLOAD_MAGIC).map_err(|e| e.to_string())?; + let state = agent_from_chunks(&parts.manifest, &parts).map_err(|e| e.to_string())?; + Ok(state_digest(&state)) +} + +/// The first record at which two runs differ, described. +pub fn compare(left: &[ParityRecord], right: &[ParityRecord]) -> Result<(), String> { + for (a, b) in left.iter().zip(right) { + if a != b { + let mut fields = Vec::new(); + let (ja, jb) = (a.to_json(), b.to_json()); + for key in [ + "kind", + "boundary", + "ticks", + "brainTicks", + "remainder", + "decision", + "telemetry", + "spikes", + "state", + ] { + if ja[key] != jb[key] { + fields.push(format!("{key}: {} != {}", ja[key], jb[key])); + } + } + return Err(format!( + "record {} ({}) differs: {}", + a.index, + a.kind, + fields.join("; ") + )); + } + } + if left.len() != right.len() { + return Err(format!("{} records against {}", left.len(), right.len())); + } + Ok(()) +} + +/// A source of reference records for a script. +/// +/// [`DirectReference`] is one. FND-01's `LegacyFrame` trace (`FLY_TRACE`) is meant to be the +/// other: it would produce the same records from the running legacy loop, and at that point the +/// transcription in [`DirectReference`] is itself checked against the service. +pub trait ReferenceSource { + fn records(&mut self, script: &LegacyScript) -> Result, String>; +} + +// ------------------------------------------------------------------------------------------- +// The direct reference: NeuralAgent in `Sim::step_frame` order + +/// `NeuralAgent` driven the way `flysim::simloop::Sim` drives it, transcribed line by line from +/// `fresh_start`, `step_frame`, `recover` and `try_restore`, with the emulator, adapter and +/// macro layer replaced by the script's recorded outputs. +pub struct DirectReference { + dataset: Arc, + agent: NeuralAgent, + macro_channels: Vec, + // `Sim`'s own fields. + remainder: f64, + location: Option, + held_channel: Option, + blocked_since_ms: f64, + frame_buffer: Vec, + /// What the adapter and the macro layer would report after the last frame. + boot: bool, + bound: Vec, + /// Reinforcement calls, for `learning.updates`. + reinforcements: u64, +} + +impl DirectReference { + fn build(dataset: Arc, macro_channels: &[String]) -> Result { + let channels: Vec<&str> = macro_channels.iter().map(String::as_str).collect(); + let mut config = + CoreAgentConfig::with_decoder(gameboy_decoder_config_with_macros(&channels)); + config.warmup_ms = gameboy::WARMUP_MS; + NeuralAgent::new(dataset, config).map_err(|e| e.to_string()) + } + + /// `Sim::boot` with no checkpoint: `fresh_start` warms up on the setup frame. + pub fn fresh( + dataset: Arc, + script: &LegacyScript, + ) -> Result<(DirectReference, ParityRecord), String> { + let mut agent = DirectReference::build(dataset.clone(), &script.macro_channels)?; + let frame = script.frames[script.initial_frame].clone(); + agent.warmup(Some(&frame)).map_err(|e| e.to_string())?; + let reference = DirectReference { + dataset, + agent, + macro_channels: script.macro_channels.clone(), + remainder: 0.0, + location: None, + held_channel: None, + blocked_since_ms: 0.0, + frame_buffer: frame, + boot: script.initial_context.boot, + bound: script.initial_context.bound.clone(), + reinforcements: 0, + }; + let record = reference.record(0, "initialize", 0, gameboy::WARMUP_MS, None, None); + Ok((reference, record)) + } + + fn record( + &self, + index: usize, + kind: &'static str, + boundary: u64, + ticks: u64, + decision: Option, + spikes: Option, + ) -> ParityRecord { + ParityRecord { + index, + kind, + boundary, + ticks, + brain_ticks: self.agent.network.ms as u64, + remainder: legacy_remainder_to_rational(self.remainder).expect("a legacy remainder"), + decision, + telemetry: Some(telemetry_of( + &self.agent, + self.agent.network.ms as u64, + self.reinforcements, + )), + spikes, + state: None, + } + } + + /// The full state as `Sim::checkpoint` exports it: the loop owns the remainder. + pub fn state_digest(&self) -> Digest { + let mut state = self.agent.export_state(); + state.remainder = self.remainder; + state_digest(&state) + } + + /// `drain_commands` (sugar) and then `Sim::step_frame`'s agent half. + fn frame( + &mut self, + sugar: &[f64], + frame: &[u8], + rewards: &[RewardEvent], + next: &ReadoutContext, + ) -> (u64, ChannelsDecision, Digest) { + // Commands: `self.agent.network.stimulate(duration)`. + for duration in sugar { + self.agent.network.stimulate(*duration); + } + // 2. Step the brain. + self.remainder += self.agent.ms_per_frame; + let steps = self.remainder.floor(); + self.remainder -= steps; + let since = self.agent.network.ms; + self.agent.network.step(steps as u64); + // 3. Decode. + let boot = self.boot; + let ms = self.agent.network.ms; + let rates = self.agent.network.rates.clone(); + let blocked_ms = self.agent.decoder.blocked_ms(); + let blocked = (blocked_ms > 0.0 && ms - self.blocked_since_ms >= blocked_ms) + .then(|| self.agent.decoder.current()) + .flatten() + .map(str::to_string); + let bound = (!self.macro_channels.is_empty()).then(|| self.bound.clone()); + let active = + self.agent + .decoder + .decode_bound(&rates, ms, boot, blocked.as_deref(), bound.as_deref()); + let held = self.agent.decoder.current().map(str::to_string); + if held != self.held_channel { + self.held_channel = held; + self.blocked_since_ms = ms; + } + let mask = to_button_mask(&active); + let decision = channels_decision(&active, &self.bound); + debug_assert_eq!(u32::from(decision.mask()), mask); + // 5. Run a frame (recorded), 6. set the visual frame from it. + self.frame_buffer.copy_from_slice(frame); + let (width, height) = (self.agent.frame.width, self.agent.frame.height); + self.agent + .network + .set_visual_frame(&self.frame_buffer, width, height); + // 7. Sample rewards (recorded), 8. stimulate once per event, 9. reinforce with the sum. + let ms = self.agent.network.ms; + let mut total = 0.0; + for event in rewards { + self.agent.network.stimulate(event.stimulation_ms); + total += event.value; + } + if self.agent.network.plasticity.enabled { + self.agent.network.plasticity.reinforce(total, ms); + self.reinforcements += 1; + } + // `observe` (recorded as the next context's bound) and the cooldown's other reset. + self.boot = next.boot; + self.bound = next.bound.clone(); + let location = next.location; + if location.is_some() && location != self.location { + self.location = location; + self.blocked_since_ms = ms; + } + let spikes = digest_of_bytes(&spike_bitset(&self.agent.network.last_spike_ms, since, ms)); + (steps as u64, decision, spikes) + } + + /// `Sim::recover`: `recover_game`'s neural half, then the loop's own transients. + fn rollback(&mut self, frame: &[u8], context: &ReadoutContext) { + let ms = self.agent.network.ms; + self.agent.decoder.clear_holds(ms); + let ms = self.agent.network.ms; + self.agent.network.plasticity.clear_eligibility(ms); + let (width, height) = (self.agent.frame.width, self.agent.frame.height); + self.agent.network.set_visual_frame(frame, width, height); + self.frame_buffer.copy_from_slice(frame); + self.location = context.location; + self.held_channel = None; + self.blocked_since_ms = self.agent.network.ms; + self.boot = context.boot; + self.bound = context.bound.clone(); + } + + /// A service restart onto the last checkpoint: `Sim::boot`'s fresh fields, then + /// `try_restore`'s agent half. The executor observes the restored world before the first + /// frame, which is the context this reference already holds. + fn restore(&mut self) -> Result<(), String> { + let mut state = self.agent.export_state(); + state.remainder = self.remainder; + let mut agent = DirectReference::build(self.dataset.clone(), &self.macro_channels)?; + agent.import_state(&state).map_err(|e| e.to_string())?; + self.agent = agent; + self.remainder = state.remainder; + let (width, height) = (self.agent.frame.width, self.agent.frame.height); + self.agent + .network + .set_visual_frame(&self.frame_buffer, width, height); + self.location = None; + self.held_channel = None; + self.blocked_since_ms = 0.0; + Ok(()) + } +} + +/// [`ReferenceSource`] over a dataset directory. +pub struct DirectSource { + pub dataset: Arc, +} + +impl ReferenceSource for DirectSource { + fn records(&mut self, script: &LegacyScript) -> Result, String> { + let (mut reference, first) = DirectReference::fresh(self.dataset.clone(), script)?; + let mut records = vec![first]; + let mut boundary = 0u64; + for (index, step) in script.steps.iter().enumerate() { + let mut record = match step { + ScriptStep::Frame { + sugar, + frame, + rewards, + next_context, + } => { + let (ticks, decision, spikes) = + reference.frame(sugar, &script.frames[*frame], rewards, next_context); + boundary += 1; + reference.record( + index + 1, + "frame", + boundary, + ticks, + Some(decision), + Some(spikes), + ) + } + ScriptStep::Rollback { frame, context } => { + reference.rollback(&script.frames[*frame], context); + reference.record(index + 1, "rollback", boundary, 0, None, None) + } + ScriptStep::Restore => { + reference.restore()?; + let mut record = + reference.record(index + 1, "restore", boundary, 0, None, None); + // An ActivateRestore reply carries no telemetry; the record says so. + record.telemetry = None; + record.state = Some(reference.state_digest()); + record + } + }; + if script.checkpoints.contains(&index) { + record.state = Some(reference.state_digest()); + } + records.push(record); + } + Ok(records) + } +} + +// ------------------------------------------------------------------------------------------- +// The worker side: a launched LegacyAgentWorker driven over the bus + +const DRIVER_CLIENT: &str = "coordinator"; +const MAX_GENERATIONS: u32 = 8; + +fn agent_service(agent_id: &Id) -> String { + format!("agent.{agent_id}") +} + +fn agent_client(agent_id: &Id, generation: u32) -> String { + if generation <= 1 { + format!("worker-{agent_id}") + } else { + format!("worker-{agent_id}-r{generation}") + } +} + +fn grants(f: impl FnOnce(&mut Grants)) -> Grants { + let mut g = Grants::default(); + f(&mut g); + g +} + +/// One legacy agent the rig launches. +#[derive(Clone, Debug)] +pub struct RigAgent { + pub agent_id: Id, + pub port_id: Id, + pub dataset_dir: PathBuf, + pub profile: LegacyProfileKind, + pub macro_channels: Vec, + pub worker_threads: usize, +} + +/// A router, a launcher in one execution mode and the legacy agents it started: the smallest +/// composition that runs `LegacyAgentWorker` under `fly-session`'s own supervisor. The +/// coordinator's part is played by [`AgentDriver`]s on one bus client. +pub struct LegacyRig { + pub launcher: Launcher, + pub client: Client, + pub session_id: Id, + pub mode: ExecutionMode, + agents: BTreeMap, +} + +impl LegacyRig { + pub async fn start( + root: &Path, + mode: ExecutionMode, + agents: &[RigAgent], + ) -> Result { + let session_id = id("legacy"); + let store_root = root.join("store"); + let sockets = root.join("sockets"); + std::fs::create_dir_all(&sockets).map_err(|e| format!("sockets: {e}"))?; + let mut policy = Policy::closed() + .client( + DRIVER_CLIENT, + grants(|g| g.call = vec![Pattern::prefix("agent.")]), + ) + .client( + SUPERVISOR_CLIENT, + grants(|g| g.call = vec![Pattern::prefix("agent.")]), + ); + for agent in agents { + let service = agent_service(&agent.agent_id); + for generation in 1..=MAX_GENERATIONS { + policy = policy.client( + &agent_client(&agent.agent_id, generation), + grants(|g| g.register = vec![Pattern::exact(&service)]), + ); + } + } + let mut config = RouterConfig::new(&store_root); + config.policy = policy; + let router = Router::new(config).map_err(|e| format!("router: {e}"))?; + let total = 1 + agents.iter().map(|a| a.worker_threads).sum::(); + let budget = ThreadBudget::new(total, 1).map_err(|e| e.message)?; + let launcher = Launcher::start(router, mode, Via::Unix, &store_root, &sockets, budget) + .await + .map_err(|e| format!("launcher: {}", e.message))?; + let client = launcher + .connect(DRIVER_CLIENT) + .await + .map_err(|e| format!("connect: {}", e.message))?; + let mut rig = LegacyRig { + launcher, + client, + session_id, + mode, + agents: BTreeMap::new(), + }; + for agent in agents { + rig.agents + .insert(agent.agent_id.clone(), (agent.clone(), 0)); + rig.launch(&agent.agent_id).await?; + } + Ok(rig) + } + + async fn launch(&mut self, agent_id: &Id) -> Result { + let (agent, generation) = self.agents.get_mut(agent_id).ok_or("unknown agent")?; + *generation += 1; + let spec = LegacyAgentLaunch { + session_id: self.session_id.clone(), + agent_id: agent.agent_id.clone(), + port_id: agent.port_id.clone(), + incarnation_id: parse_id(&format!("{}-inc-{generation}", agent.agent_id))?, + worker_threads: agent.worker_threads, + dataset_dir: agent.dataset_dir.clone(), + profile: agent.profile, + macro_channels: agent.macro_channels.clone(), + client_id: agent_client(&agent.agent_id, *generation), + service: agent_service(&agent.agent_id), + }; + self.launcher + .launch_legacy_agent(spec) + .await + .map_err(|e| e.message)?; + Ok(self.worker_ref(agent_id)) + } + + pub fn worker_ref(&self, agent_id: &Id) -> WorkerRef { + self.launcher + .worker(agent_id) + .expect("launched") + .worker_ref() + } + + /// Stops an agent's worker and starts its replacement: a new process in process mode, with + /// a new incarnation and a new client identity, uninitialized. + pub async fn replace(&mut self, agent_id: &Id) -> Result { + self.launcher.reap(agent_id, &id("replaced")).await; + self.launch(agent_id).await + } + + pub async fn stop(mut self) { + self.launcher.reap_all(&id("done")).await; + } + + /// A driver for one agent, playing the coordinator's part. + pub fn driver(&self, agent_id: &Id, script: &LegacyScript) -> AgentDriver { + let (agent, _) = &self.agents[agent_id]; + AgentDriver { + client: self.client.clone(), + target: self.worker_ref(agent_id), + session_id: self.session_id.clone(), + agent_id: agent_id.clone(), + profile: agent.profile.profile(), + epoch_serial: 1, + boundary: 0, + serials: Serials::default(), + context: script.initial_context.to_typed(), + frames: script.frames.clone(), + captures: 0, + remainder: RationalNs::ZERO, + } + } +} + +fn domain(e: DomainError) -> String { + format!("{:?}: {}", e.code, e.message) +} + +/// The coordinator's side of one agent: scopes, request serials, frame artifacts and the +/// context it last sent. +pub struct AgentDriver { + client: Client, + target: WorkerRef, + session_id: Id, + agent_id: Id, + profile: LegacyAgentProfile, + epoch_serial: u32, + boundary: u64, + serials: Serials, + context: TypedValue, + frames: Arc>>, + captures: u64, + /// The remainder the last Prepare reported: a rollback keeps it. + remainder: RationalNs, +} + +/// A captured payload, held for a restore. +pub struct Captured { + pub result: CaptureResult, + pub artifact: flybus::Artifact, + pub bytes: Vec, + pub scope: Scope, +} + +impl AgentDriver { + fn epoch(&self) -> Id { + id(&format!("e{}", self.epoch_serial)) + } + + fn scope(&self) -> Scope { + scope_at(&self.session_id, &self.epoch(), self.boundary) + } + + async fn frame_input( + &self, + frame: usize, + boundary: u64, + ) -> Result<(SensoryInput, flybus::Artifact), String> { + let artifact = crate::media::seal_copy( + &self.client, + crate::media::FRAME_CONTENT_TYPE.to_owned(), + &self.frames[frame], + ) + .await + .map_err(domain)?; + let input = SensoryInput { + boundary, + views: vec![ViewRef { + view_id: gameboy::VIEW_ID.to_owned(), + produced_step: boundary, + pixels: artifact.reference().clone(), + }], + structured: None, + }; + Ok((input, artifact)) + } + + async fn call( + &mut self, + method: &str, + scope: Option, + params: Value, + attachments: &[(&str, &flybus::Artifact)], + want: &[&str], + ) -> Result { + let request_id = self.serials.next(&self.target.service); + let want: Vec = want.iter().map(|w| (*w).to_owned()).collect(); + let reply = call( + &self.client, + &self.target, + method, + scope, + object(params), + attachments, + request_id, + &want, + ) + .await + .map_err(|e| format!("{method}: {}", domain(e)))?; + reply + .result() + .map_err(|e| format!("{method}: {}", domain(e)))?; + Ok(reply) + } + + /// One call with any params, its domain outcome returned as it stands: for tests that + /// need the worker to refuse something. + pub async fn call_raw( + &mut self, + method: &str, + scope: Option, + params: Value, + attachments: &[(&str, &flybus::Artifact)], + ) -> Result { + let request_id = self.serials.next(&self.target.service); + call( + &self.client, + &self.target, + method, + scope, + object(params), + attachments, + request_id, + &[], + ) + .await + } + + /// The same request again, same id and body: a domain retry. + pub async fn retry_raw( + &mut self, + request_id: DomainRequestId, + method: &str, + scope: Option, + params: Value, + ) -> Result { + call( + &self.client, + &self.target, + method, + scope, + object(params), + &[], + request_id, + &[], + ) + .await + } + + /// A sealed frame from the script's pool, as a sensory input observing `boundary`. + pub async fn input( + &self, + frame: usize, + boundary: u64, + ) -> Result<(SensoryInput, flybus::Artifact), String> { + self.frame_input(frame, boundary).await + } + + /// The scope of the committed boundary this driver is at. + pub fn current_scope(&self) -> Scope { + self.scope() + } + + /// Moves the driver to the next epoch without telling the worker, to address it wrongly. + pub fn bump_epoch(&mut self) { + self.epoch_serial += 1; + } + + pub fn context(&self) -> &TypedValue { + &self.context + } + + pub fn profile(&self) -> &AssetRef { + &self.profile.asset + } + + async fn acknowledge(&mut self, request_id: DomainRequestId) -> Result<(), String> { + let params = AcknowledgeParams { + request_ids: vec![request_id], + }; + self.call("Worker.Acknowledge", None, params.to_json(), &[], &[]) + .await + .map(|_| ()) + } + + pub async fn initialize(&mut self, initial_frame: usize) -> Result { + let (input, artifact) = self.frame_input(initial_frame, 0).await?; + let params = AgentInitializeParams { + agent_id: self.agent_id.clone(), + profile: self.profile.asset.clone(), + seed: LEGACY_SEED, + initial_input: input, + initial_decision_context: self.context.clone(), + worker_threads: 1, + }; + let reply = self + .call( + "Agent.Initialize", + Some(self.scope()), + params.to_json(), + &[("view.lcd", &artifact)], + &[], + ) + .await?; + let result: AgentInitializeResult = reply.parse().map_err(domain)?; + if result + .telemetry + .rates + .iter() + .map(|r| r.role_id.as_str()) + .ne(result.graph.rate_roles.iter().map(String::as_str)) + { + return Err("telemetry rates are not in AgentGraph.rateRoles order".to_owned()); + } + self.acknowledge(reply.request_id).await?; + Ok(ParityRecord { + index: 0, + kind: "initialize", + boundary: 0, + ticks: result.warmup_ticks, + brain_ticks: result.telemetry.brain_ticks, + remainder: RationalNs::ZERO, + decision: None, + telemetry: Some(result.telemetry), + spikes: None, + state: None, + }) + } + + /// Prepare then Commit: one transition. + pub async fn frame( + &mut self, + index: usize, + sugar: &[f64], + frame: usize, + rewards: &[RewardEvent], + next_context: &ReadoutContext, + ) -> Result { + let k = self.boundary; + let prepare = PrepareParams { + agent_id: self.agent_id.clone(), + profile_digest: self.profile.asset.digest.clone(), + interval: gameboy::step_duration(), + decision_context_digest: self.context.digest(), + pre_step_stimulations: sugar + .iter() + .enumerate() + .map(|(n, ms)| Stimulus { + id: id(&format!("sugar-{k}-{n}")), + kind_id: gameboy::STIMULUS_REWARD_PULSE.to_owned(), + duration_ms: *ms, + }) + .collect(), + }; + let reply = self + .call( + "Agent.Prepare", + Some(self.scope()), + prepare.to_json(), + &[], + &[], + ) + .await?; + let prepared: PreparedDecision = reply.parse().map_err(domain)?; + let decision = ChannelsDecision::from_typed(&prepared.decision).map_err(|e| e.0)?; + + let (input, artifact) = self.frame_input(frame, k + 1).await?; + let next = next_context.to_typed(); + let commit = CommitParams { + agent_id: self.agent_id.clone(), + prepared_request_id: reply.request_id.clone(), + next_input: input, + next_decision_context: next.clone(), + rewards: rewards + .iter() + .enumerate() + .map(|(n, e)| Reward { + event_id: id(&format!("ev-{k}-{n}")), + rule_id: id("toy"), + value: e.value, + }) + .collect(), + task_stimulations: rewards + .iter() + .enumerate() + .map(|(n, e)| Stimulus { + id: id(&format!("ev-{k}-{n}")), + kind_id: gameboy::STIMULUS_REWARD_PULSE.to_owned(), + duration_ms: e.stimulation_ms, + }) + .collect(), + }; + let reply = self + .call( + "Agent.Commit", + Some(self.scope()), + commit.to_json(), + &[("view.lcd", &artifact)], + &[SPIKES_ATTACHMENT], + ) + .await?; + let result: AgentCommitResult = reply.parse().map_err(domain)?; + if result.committed_step != k + 1 || result.decision_context_digest != next.digest() { + return Err(format!( + "Agent.Commit acknowledged {} with another context", + result.committed_step + )); + } + let spikes = match reply.artifacts.get(SPIKES_ATTACHMENT) { + Some(artifact) => digest_of_bytes(&artifact.read_all().await.map_err(|e| e.message)?), + None => return Err("Agent.Commit carried no spike bitset".to_owned()), + }; + self.context = next; + self.boundary = k + 1; + self.remainder = prepared.remainder; + Ok(ParityRecord { + index, + kind: "frame", + boundary: k + 1, + ticks: prepared.ticks_advanced, + brain_ticks: prepared.brain_ticks, + remainder: prepared.remainder, + decision: Some(decision), + telemetry: Some(result.telemetry), + spikes: Some(spikes), + state: None, + }) + } + + /// `legacy-ratchet-rollback-v1`'s agent half, under a new epoch at the same boundary. + pub async fn rollback( + &mut self, + index: usize, + frame: usize, + context: &ReadoutContext, + ) -> Result { + let prior = self.epoch(); + self.epoch_serial += 1; + let (input, artifact) = self.frame_input(frame, self.boundary).await?; + let typed = context.to_typed(); + let params = AgentRollbackParams { + agent_id: self.agent_id.clone(), + prior_epoch: prior, + policy: ROLLBACK_POLICY.to_owned(), + input, + decision_context: typed.clone(), + }; + let reply = self + .call( + METHOD_AGENT_ROLLBACK, + Some(self.scope()), + params.to_json(), + &[("view.lcd", &artifact)], + &[], + ) + .await?; + let result: AgentRollbackResult = reply.parse().map_err(domain)?; + result + .validate_against_scope(&self.scope()) + .map_err(|e| e.0)?; + self.context = typed; + Ok(ParityRecord { + index, + kind: "rollback", + boundary: self.boundary, + ticks: 0, + brain_ticks: result.telemetry.brain_ticks, + remainder: self.remainder, + decision: None, + telemetry: Some(result.telemetry), + spikes: None, + state: None, + }) + } + + /// `State.Capture` at the committed boundary. + pub async fn capture(&mut self) -> Result { + self.captures += 1; + let scope = self.scope(); + let params = CaptureParams { + checkpoint_id: id(&format!("cp-{}", self.captures)), + }; + let reply = self + .call( + "State.Capture", + Some(scope.clone()), + params.to_json(), + &[], + &[crate::state::PAYLOAD_ATTACHMENT], + ) + .await?; + let result: CaptureResult = reply.parse().map_err(domain)?; + let artifact = reply + .artifacts + .get(crate::state::PAYLOAD_ATTACHMENT) + .cloned() + .ok_or("State.Capture carried no payload")?; + let bytes = artifact.read_all().await.map_err(|e| e.message)?; + self.acknowledge(reply.request_id).await?; + Ok(Captured { + result, + artifact, + bytes, + scope, + }) + } + + /// A group restore into `target`, a fresh replacement worker, under a new epoch. + pub async fn restore_into( + &mut self, + target: WorkerRef, + captured: &Captured, + ) -> Result<(), String> { + self.target = target; + self.epoch_serial += 1; + let params = StageRestoreParams { + checkpoint_id: captured.result.checkpoint_id.clone(), + source_scope: captured.scope.clone(), + compatibility_digest: captured.result.compatibility_digest.clone(), + payload: captured.artifact.reference().clone(), + }; + let reply = self + .call( + "State.StageRestore", + Some(self.scope()), + params.to_json(), + &[(crate::state::PAYLOAD_ATTACHMENT, &captured.artifact)], + &[], + ) + .await?; + let staged: StageRestoreResult = reply.parse().map_err(domain)?; + self.acknowledge(reply.request_id).await?; + let params = ActivateRestoreParams { + restore_token: staged.restore_token, + }; + let reply = self + .call("State.ActivateRestore", None, params.to_json(), &[], &[]) + .await?; + let activated: ActivateRestoreResult = reply.parse().map_err(domain)?; + if activated.committed_step != self.boundary { + return Err("State.ActivateRestore landed on another boundary".to_owned()); + } + self.acknowledge(reply.request_id).await + } +} + +/// Runs a script against the rig's agent, recording what the coordinator observes. +pub async fn run_on_worker( + rig: &mut LegacyRig, + agent_id: &Id, + script: &LegacyScript, +) -> Result, String> { + let mut driver = rig.driver(agent_id, script); + let mut records = vec![driver.initialize(script.initial_frame).await?]; + for (index, step) in script.steps.iter().enumerate() { + let mut record = match step { + ScriptStep::Frame { + sugar, + frame, + rewards, + next_context, + } => { + driver + .frame(index + 1, sugar, *frame, rewards, next_context) + .await? + } + ScriptStep::Rollback { frame, context } => { + driver.rollback(index + 1, *frame, context).await? + } + ScriptStep::Restore => { + let captured = driver.capture().await?; + let target = rig.replace(agent_id).await?; + driver.restore_into(target, &captured).await?; + // The replacement's own capture: a restore is exact for everything captured. + let after = driver.capture().await?; + ParityRecord { + index: index + 1, + kind: "restore", + boundary: driver.boundary, + ticks: 0, + brain_ticks: captured_brain_ticks(&after.bytes)?, + remainder: captured_remainder(&after.bytes)?, + decision: None, + telemetry: None, + spikes: None, + state: Some(payload_state_digest(&after.bytes)?), + } + } + }; + if script.checkpoints.contains(&index) { + let captured = driver.capture().await?; + record.state = Some(payload_state_digest(&captured.bytes)?); + } + records.push(record); + } + Ok(records) +} + +fn captured_session(payload: &[u8]) -> Result { + let parts = decode_envelope(payload, PAYLOAD_MAGIC).map_err(|e| e.to_string())?; + let session = parts.manifest.get("session").ok_or("no session member")?; + serde_json::from_str(&session.stringify()).map_err(|e| e.to_string()) +} + +fn captured_brain_ticks(payload: &[u8]) -> Result { + captured_session(payload)?["accumulator"]["executedTicks"] + .as_str() + .and_then(|s| s.parse().ok()) + .ok_or_else(|| "no executedTicks".to_owned()) +} + +fn captured_remainder(payload: &[u8]) -> Result { + RationalNs::from_json(&captured_session(payload)?["accumulator"]["remainder"]).map_err(|e| e.0) +} + +/// The rows and the overall digest of a record sequence, as a golden file holds them. +pub fn golden_json(script: &LegacyScript, records: &[ParityRecord]) -> Value { + let all: Vec = records.iter().map(ParityRecord::to_json).collect(); + json!({ + "scenario": script.name, + "macroChannels": script.macro_channels, + "records": records.len(), + "digest": digest_of(&Value::Array(all)).expect("records canonicalize"), + "rows": records.iter().map(ParityRecord::row).collect::>(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_frame_pool_and_scripts_are_deterministic() { + assert_eq!(frame_pool(3, 7), frame_pool(3, 7)); + assert_ne!(frame_pool(3, 7)[0], frame_pool(3, 7)[1]); + let script = toy_macros_script(260); + assert_eq!( + script + .steps + .iter() + .filter(|s| matches!(s, ScriptStep::Rollback { .. })) + .count(), + 1 + ); + assert_eq!( + script + .steps + .iter() + .filter(|s| matches!(s, ScriptStep::Restore)) + .count(), + 1 + ); + for step in &script.steps { + if let ScriptStep::Frame { next_context, .. } = step { + next_context + .validate_against(&script.macro_channels) + .expect("a valid context"); + } + } + } +} diff --git a/services/flysim/crates/fly-session/src/lib.rs b/services/flysim/crates/fly-session/src/lib.rs index 74a21c9..fcb005e 100644 --- a/services/flysim/crates/fly-session/src/lib.rs +++ b/services/flysim/crates/fly-session/src/lib.rs @@ -30,6 +30,7 @@ pub mod environment; pub mod harness; pub mod launcher; pub mod legacy_agent; +pub mod legacy_parity; pub mod measure; pub mod media; pub mod metrics;