File size: 110,661 Bytes
f726fd6 | 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 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 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 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 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 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 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 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 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 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 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 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 | """Released environment operations and snapshot validation."""
from __future__ import annotations
from collections import Counter as ext_Counter
from collections import defaultdict as ext_defaultdict
from copy import deepcopy as ext_deepcopy
from pathlib import Path as ext_Path
from rescopebench.raw_module_isolation import load_isolated_modules as ext_load_isolated_modules
from rescopebench.public_projection import assert_hard_public_projection as ext_assert_hard_public_projection
from rescopebench.agent_runtime.protocol import public_feedback as ext_public_feedback
from typing import Any as ext_Any
import copy as mod_copy
import hashlib as mod_hashlib
import json as mod_json
import re as _re
import re as mod_re
from .spec import CASE_DIR, DATA_TASK_IDS, DATA_CHANGED_S, DATA_PUBLIC_TOOLS, DATA_SCHEMAS, DATA_POST_POLICY, DATA_POLICY_BY_CONDITIONS, DATA_CHANGED_BINDINGS, DATA_ID_FIELDS, DATA_SCHEMAS_2, DATA_SCHEDULE_2, DATA_DONORS, DATA_SCOPE_REPLACEMENTS, DATA_SCOPE_TEMPLATES, DATA_SCHEMAS_3, DATA_LIST_TOOLS, DATA_SCHEMAS_4, DATA_ZONES, DATA_REPLACEMENTS, DATA_SCOPE_SCHEDULE, DATA_CELL_SCHEDULE, DATA_WORKLOAD_CONDITIONS, DATA_SERVICE_CONDITIONS, DATA_ALLOWED_TOOLS, DATA_RECOVERY_SCOPE_TASK_IDS, DATA_RECOVERY_SCOPE_ORDER, DATA_RECOVERY_ZONES, DATA_RECOVERY_CELL_ORDER, DATA_PREFIX_SCOPE_DONORS, DATA_PREFIX_ZONE_SCHEDULE, DATA_TASK_IDS_2, DATA_CELL_SCHEDULE_2, DATA_CELL_SCHEDULE_3, DATA_TASK_BY_ID, DATA__PRIVATE_KEYS
def fn_grade_task(task, initial, final, eligible_nodes):
(before, after) = (initial['raw']['database'], final['raw']['database'])
nodes = {row['node_id']: row for row in after['node']}
initial_nodes = {row['node_id']: row for row in before['node']}
namespaces = {row['namespace_id']: row for row in after['namespace']}
initial_namespaces = {row['namespace_id']: row for row in before['namespace']}
clusters = {row['cluster_id']: row for row in after['cluster']}
initial_clusters = {row['cluster_id']: row for row in before['cluster']}
labels = {target['workload']['app_label'] for target in task['targets']}
target_pods = [pod for pod in after['pod'] if (pod.get('labels') or {}).get('app') in labels and pod.get('phase') == 'Running']
node_delta = ext_Counter((pod.get('node_id') for pod in target_pods))
namespace_delta = ext_Counter((pod.get('namespace_id') for pod in target_pods))
cluster_delta = ext_Counter((pod.get('cluster_id') for pod in target_pods))
old_deployments = {row['deployment_id'] for row in before['deployment']}
old_services = {row['service_id'] for row in before['service']}
new_deployments = [row for row in after['deployment'] if row['deployment_id'] not in old_deployments]
requested_deployments = {row['deployment_id'] for row in new_deployments if row.get('app_label') in labels}
extras = [row['deployment_id'] for row in new_deployments if row.get('app_label') not in labels]
extras.extend((row['service_id'] for row in after['service'] if row['service_id'] not in old_services and row.get('deployment_id') not in requested_deployments))
artifacts = []
for target in task['targets']:
workload = target['workload']
requested_service = target['service']
requirements = fn_policy_for_task(task, target)['requirements']
matching_clusters = [row for row in after['cluster'] if all((row.get(field) == value for (field, value) in target['cluster_selector'].items()))]
cluster_id = matching_clusters[0]['cluster_id'] if len(matching_clusters) == 1 else None
matching_namespaces = [row for row in after['namespace'] if row.get('cluster_id') == cluster_id and all((row.get(field) == value for (field, value) in target['namespace_selector'].items()))]
namespace_id = matching_namespaces[0]['namespace_id'] if len(matching_namespaces) == 1 else None
matches = [row for row in after['deployment'] if row.get('app_label') == workload['app_label']]
deployment = matches[0] if len(matches) == 1 else None
deployment_ok = bool(deployment and deployment.get('namespace_id') == namespace_id and all((deployment.get(field) == workload[field] for field in ('name', 'app_label', 'image', 'image_tag', 'desired_replicas', 'workload_class', 'change_window'))) and (deployment.get('created_by') == target['release_id']) and (deployment.get('placement_class') == target['placement']['placement_class']) and (deployment.get('update_strategy') == requirements['update_strategy']))
pods = [row for row in after['pod'] if deployment and row.get('deployment_id') == deployment['deployment_id']]
placements = [row.get('node_id') for row in pods]
zones = sorted((nodes[node_id].get('zone') for node_id in placements if node_id in nodes))
pods_ok = bool(deployment_ok and len(pods) == workload['desired_replicas'] and (len(set(placements)) == len(pods)) and (zones == sorted(target['placement']['required_zones'])) and all((row.get('phase') == 'Running' and row.get('readiness') == 'ready' and (row.get('node_id') in eligible_nodes.get(namespace_id, set())) and (nodes[row['node_id']].get('cluster_id') == cluster_id) and (nodes[row['node_id']].get('readiness') == 'ready') and (nodes[row['node_id']].get('schedulable') is True) for row in pods)))
service_matches = [row for row in after['service'] if deployment and row.get('deployment_id') == deployment['deployment_id']]
service = service_matches[0] if len(service_matches) == 1 else None
dns = requested_service['external_dns'] if requirements['external_dns'] == 'required' else None
service_ok = bool(deployment_ok and service and (service.get('namespace_id') == namespace_id) and (service.get('cluster_id') == cluster_id) and all((service.get(field) == requested_service[field] for field in ('name', 'service_role', 'access_class', 'traffic_class'))) and (service.get('selector_app') == workload['app_label']) and (service.get('service_type') == requirements['service_type']) and (service.get('external_dns') == dns) and (service.get('status') in ({'active', 'pending'} if requirements['service_type'] == 'LoadBalancer' else {'active'})) and fn__ports_match(service.get('ports', []), requested_service['ports'], requirements, cluster_id, after['service'], service['service_id']))
capacity_ok = bool(deployment_ok and all((node_id in initial_nodes and int(nodes[node_id].get('active_pods') or 0) == int(initial_nodes[node_id].get('active_pods') or 0) + node_delta[node_id] <= int(nodes[node_id].get('allocatable_pods') or nodes[node_id].get('capacity_pods') or 0) for node_id in placements)) and (int(namespaces[namespace_id].get('active_pods') or 0) == int(initial_namespaces[namespace_id].get('active_pods') or 0) + namespace_delta[namespace_id]) and (int(clusters[cluster_id].get('pod_allocated') or 0) == int(initial_clusters[cluster_id].get('pod_allocated') or 0) + cluster_delta[cluster_id]))
milestones = {'deployment_committed': 5.0 if deployment_ok else 0.0, 'pods_validly_placed': 7.5 if pods_ok else 0.0, 'service_contract_persisted': 7.5 if service_ok else 0.0, 'capacity_conserved': 5.0 if capacity_ok else 0.0}
if extras:
milestones = {key: 0.0 for key in milestones}
score = sum(milestones.values())
artifacts.append({'release_id': target['release_id'], 'milestones': milestones, 'score': score, 'complete': score == 25.0, 'actual_zones': zones})
return {'task_id': task['task_id'], 'score': sum((row['score'] for row in artifacts)), 'complete_artifacts': sum((row['complete'] for row in artifacts)), 'artifacts': artifacts, 'objective_state_only': True, 'extra_outputs': extras}
def fn_public_grade(grade, release_ids):
rows = grade.get('artifacts')
if not isinstance(rows, list) or len(rows) != len(release_ids):
raise ValueError('grade must describe every requested release')
by_id = {row.get('release_id'): row for row in rows if isinstance(row, dict)}
if set(by_id) != set(release_ids) or len(by_id) != len(rows):
raise ValueError('grade contains missing, repeated, or foreign release IDs')
components: dict[str, dict[str, int]] = {}
for release_id in release_ids:
milestones = by_id[release_id].get('milestones')
if not isinstance(milestones, dict) or set(milestones) != {'deployment_committed', 'pods_validly_placed', 'service_contract_persisted', 'capacity_conserved'}:
raise ValueError('grade has an invalid release milestone set')
for (milestone, points) in milestones.items():
if type(points) not in (int, float) or points < 0:
raise ValueError('grade milestone points must be non-negative numbers')
components[f'{release_id}:{milestone}'] = {'correct': int(points > 0), 'total': 1}
result = {'score': grade['score'], 'public_components': components}
ext_public_feedback(result)
return result
def fn_private_task(task_id):
packet = fn_public_task_2(task_id)
packet.update(task_id=task_id, policy_epoch='post' if int(task_id[1:]) >= 17 else 'pre')
return packet
def fn_digest(value):
return mod_hashlib.sha256(fn__canonical(value).encode('ascii')).hexdigest()
def fn_binding_key(namespace_id, zone):
return namespace_id + '|' + zone
def fn_rekey_database(database, identities):
"""Rewrite declared references, never substrings in learner-authored text."""
result = ext_deepcopy(database)
for rows in result.values():
for row in rows:
if row.get('namespace_id') in identities:
row['namespace_id'] = identities[row['namespace_id']]
if row.get('involved_kind') == 'Namespace' and row.get('involved_id') in identities:
row['involved_id'] = identities[row['involved_id']]
return result
def fn__validate_value(value, schema, path):
if not fn__matches_type(value, schema.get('type', 'object')):
return f"{path} must be {schema.get('type')}"
if value is None:
return None
if 'enum' in schema and value not in schema['enum']:
return f'{path} is not an allowed value'
if isinstance(value, str) and len(value) < schema.get('minLength', 0):
return f'{path} must not be empty'
if isinstance(value, (int, float)) and (not isinstance(value, bool)):
if 'minimum' in schema and value < schema['minimum']:
return f"{path} must be at least {schema['minimum']}"
if 'maximum' in schema and value > schema['maximum']:
return f"{path} must be at most {schema['maximum']}"
if isinstance(value, list):
if len(value) < schema.get('minItems', 0):
return f'{path} has too few items'
if 'maxItems' in schema and len(value) > schema['maxItems']:
return f'{path} has too many items'
item_schema = schema.get('items')
if item_schema:
for (index, item) in enumerate(value):
error = fn__validate_value(item, item_schema, f'{path}[{index}]')
if error:
return error
if isinstance(value, dict):
properties = schema.get('properties', {})
if schema.get('additionalProperties') is False:
unknown = sorted(set(value) - set(properties))
if unknown:
return f"{path} contains unsupported field(s): {', '.join(unknown)}"
missing = [name for name in schema.get('required', []) if name not in value]
if missing:
return f"{path} is missing required field(s): {', '.join(missing)}"
for (name, item) in value.items():
if name in properties:
error = fn__validate_value(item, properties[name], f'{path}.{name}')
if error:
return error
return None
def fn__sanitize_raw_result(tool, result):
if not isinstance(result, dict) or not isinstance(result.get('content'), dict):
return {'type': 'tool_result', 'tool': tool, 'content': {'status': 'error', 'data': {}, 'message': 'UPSTREAM_TOOL_ERROR: invalid raw response'}}
content = result['content']
if content.get('status') != 'error':
return result
message = str(content.get('message') or 'UPSTREAM_TOOL_ERROR: raw tool failed')
if message.startswith('TOOL_EXECUTION_ERROR') or message.startswith('INTERNAL_ERROR') or 'traceback' in message.lower():
message = 'UPSTREAM_TOOL_ERROR: raw tool execution failed'
return {'type': 'tool_result', 'tool': tool, 'content': {'status': 'error', 'data': {}, 'message': message}}
def fn_public_task(task_id):
packet = fn_public_task_3(task_id)
donor = DATA_DONORS.get(task_id, task_id)
if donor not in DATA_SCOPE_REPLACEMENTS:
return packet
for (target, scope_id) in zip(packet['targets'], DATA_SCOPE_REPLACEMENTS[donor], strict=True):
scope = DATA_SCOPE_TEMPLATES[scope_id]
for key in ('cluster_selector', 'namespace_selector', 'placement'):
target[key] = ext_deepcopy(scope[key])
identity = 'evt-' + fn_digest(['k8s-scope-balanced-lifecycle-evolution-v2', task_id, packet['targets']])[:20]
packet.update(task_id=identity, event_id=identity, episode_id=identity)
return packet
def fn_condition_key(value):
return tuple((value.get(key) for key in ('workload_class', 'change_window', 'placement_class', 'access_class', 'traffic_class')))
def fn__slug(value, default='item'):
text = mod_re.sub('[^a-z0-9]+', '-', str(value or '').strip().lower()).strip('-')
return text or default
def fn_policy_for_task(task, target):
mapping = DATA_POST_POLICY if task['policy_epoch'] == 'post' else DATA_POLICY_BY_CONDITIONS
return mapping[fn_condition_key(fn_target_conditions(target))]
def fn__ports_match(actual, requested, requirements, cluster_id, all_services, service_id):
if len(actual) != len(requested):
return False
fields = ('name', 'port', 'target_port')
wanted = {p['name']: p for p in requested}
if len(wanted) != len(requested) or len({p.get('name') for p in actual}) != len(actual):
return False
allocated = set()
for service in all_services:
if service.get('cluster_id') == cluster_id and service.get('service_id') != service_id:
allocated.update((p.get('node_port') for p in service.get('ports', []) if p.get('node_port') is not None))
chosen = set()
for port in actual:
expected = wanted.get(port.get('name'))
if expected is None or any((port.get(k) != expected.get(k) for k in fields)):
return False
if port.get('protocol') != requirements['protocol']:
return False
node_port = port.get('node_port')
if requirements['service_type'] == 'NodePort':
if type(node_port) is not int or not 30000 <= node_port <= 32767:
return False
if node_port in allocated or node_port in chosen:
return False
chosen.add(node_port)
elif node_port is not None:
return False
return True
def fn_public_task_2(task_id):
packet = fn_public_task(task_id)
packet['completion'].update(mode='independent', priority_order='none', started_item_must_close=False)
packet['completion']['request_order'] = 'Release requests are independent and may be processed in any order. An incomplete release does not block another release. A release still needs its own valid stable deployment and matching service; namespace allocation, live worker capacity and current release policy remain enforced.'
return packet
def fn__canonical(value):
return mod_json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'), allow_nan=False)
def fn__matches_type(value, expected):
if isinstance(expected, list):
return any((fn__matches_type(value, item) for item in expected))
if expected == 'null':
return value is None
if expected == 'boolean':
return isinstance(value, bool)
if expected == 'integer':
return isinstance(value, int) and (not isinstance(value, bool))
if expected == 'number':
return isinstance(value, (int, float)) and (not isinstance(value, bool))
if expected == 'string':
return isinstance(value, str)
if expected == 'array':
return isinstance(value, list)
if expected == 'object':
return isinstance(value, dict)
return True
def fn_public_task_3(task_id):
value = fn_public_task_4(DATA_DONORS.get(task_id, task_id))
if task_id in DATA_DONORS:
for (slot, target) in enumerate(value['targets'], 1):
identity = fn_digest(['k8s-two-event-lifecycle-evolution-v1', task_id, slot])[:12]
target['release_id'] = 'release-' + identity
for key in ('name', 'app_label'):
target['workload'][key] = 'workload-' + identity
target['workload']['image_tag'] = 'build-' + identity
target['service']['name'] = 'service-' + identity
target['service']['external_dns'] = identity + '.release.example'
event = 'evt-' + fn_digest(['k8s-two-event-lifecycle-evolution-v1', task_id, value['targets']])[:20]
value.update(task_id=event, event_id=event, episode_id=event)
value['completion'].pop('verification_required', None)
value['completion']['evidence'] = {'mode': 'authoritative_receipt', 'source': 'publish_deployment followed by create_service', 'proves': 'the reported deployment rollout and persisted service contract for that release'}
value['budget']['charging'].append('Synchronous receipts are sufficient for their reported committed facts. Pool and policy inspections supply current business information and retain their listed costs.')
return value
def fn_target_conditions(target):
return {'workload_class': target['workload']['workload_class'], 'change_window': target['workload']['change_window'], 'placement_class': target['placement']['placement_class'], 'access_class': target['service']['access_class'], 'traffic_class': target['service']['traffic_class']}
def fn_public_task_4(task_id):
task = fn_public_task_5(task_id)
if task_id not in DATA_REPLACEMENTS:
return task
for (slot, cell) in DATA_REPLACEMENTS[task_id].items():
target = task['targets'][slot - 1]
conditions = fn_cell_conditions(cell)
if any((target['service'][key] != conditions[key] for key in ('access_class', 'traffic_class'))):
raise ValueError('Coverage replacement must preserve the full service contract')
target['workload'].update({key: conditions[key] for key in ('workload_class', 'change_window')})
event = 'evt-' + fn_digest(['k8s-operations-binding-v9.3', task_id, task['targets']])[:20]
task.update(task_id=event, event_id=event, episode_id=event)
return task
def fn__bounded_int(arguments, name, default, minimum, maximum):
if not isinstance(arguments, dict):
return default
value = arguments.get(name, default)
if not isinstance(value, int) or isinstance(value, bool) or (not minimum <= value <= maximum):
return default
return value
def fn__safe_len(arguments, name, default, maximum):
if not isinstance(arguments, dict):
return default
value = arguments.get(name)
if not isinstance(value, list) or not 0 <= len(value) <= maximum:
return default
return len(value)
def fn_public_task_5(task_id):
task = ext_deepcopy(fn_public_task_6(task_id))
for (target, scope_id, cell_id) in zip(task['targets'], DATA_SCOPE_SCHEDULE[task_id], DATA_CELL_SCHEDULE[task_id]):
fn__copy_scope(target, DATA_SCOPE_TEMPLATES[scope_id])
conditions = fn_cell_conditions(cell_id)
target['workload'].update({key: conditions[key] for key in ('workload_class', 'change_window')})
target['service'].update({key: conditions[key] for key in ('access_class', 'traffic_class')})
task['completion'].update({'mode': 'ordered_independent', 'priority_order': 'listed', 'subset_allowed': True, 'started_item_must_close': True})
task['event_id'] = 'evt-' + fn_digest(['k8s-operations-binding-v9', task_id, task['targets']])[:20]
task['task_id'] = task['event_id']
task['episode_id'] = task['event_id']
return task
def fn_cell_conditions(index):
(workload, window) = DATA_WORKLOAD_CONDITIONS[index // 4]
(access, traffic) = DATA_SERVICE_CONDITIONS[index % 4]
return {'workload_class': workload, 'change_window': window, 'placement_class': 'zonal_pair', 'access_class': access, 'traffic_class': traffic}
def fn_public_task_6(task_id):
task = ext_deepcopy(fn_public_task_7(task_id))
task['allowed_tools'] = list(DATA_ALLOWED_TOOLS)
if task_id in DATA_RECOVERY_SCOPE_TASK_IDS:
anchor = fn_public_task_7('T08')
for (index, target) in enumerate(task['targets']):
donor_index = DATA_RECOVERY_SCOPE_ORDER[task_id][index]
donor = anchor['targets'][donor_index]
target['cluster_selector'] = ext_deepcopy(donor['cluster_selector'])
target['namespace_selector'] = ext_deepcopy(donor['namespace_selector'])
target['placement']['required_zones'] = list(DATA_RECOVERY_ZONES[donor_index])
conditions = fn_cell_conditions(DATA_RECOVERY_CELL_ORDER[task_id][index])
target['workload'].update({key: conditions[key] for key in ('workload_class', 'change_window')})
target['service'].update({key: conditions[key] for key in ('access_class', 'traffic_class')})
task['event_id'] = 'evt-' + fn_digest(['k8s-operations-mixed-v8', task_id, task['targets']])[:20]
task['task_id'] = task['event_id']
task['episode_id'] = task['event_id']
return task
def fn__copy_scope(target, scope):
target['cluster_selector'] = ext_deepcopy(scope['cluster_selector'])
target['namespace_selector'] = ext_deepcopy(scope['namespace_selector'])
target['placement'] = ext_deepcopy(scope['placement'])
def fn_public_task_7(task_id):
task = ext_deepcopy(fn_public_task_8(task_id))
task['allowed_tools'] = list(DATA_ALLOWED_TOOLS)
task['budget']['charging'] = ['Cluster and namespace catalogs cost two work units plus the scanned prefix, with a minimum four-record scan page; skipped offset rows count.', 'Worker-pool catalogs cost two work units plus the scanned prefix, with a minimum two-candidate scan page; skipped offset rows count.', 'Inspecting one worker pool costs three work units; inspecting one local release policy cell costs eighteen work units.', 'Publishing a deployment consumes eight work units plus three per added replica.', 'Creating a service consumes eight work units plus two per port.', 'Invalid allowed-tool calls and failed writes consume their declared work units.']
if task_id in DATA_PREFIX_SCOPE_DONORS:
anchor = fn_public_task_8('T08')
for (target_index, donor_index) in DATA_PREFIX_SCOPE_DONORS[task_id].items():
fn__replace_scope(task['targets'][target_index], anchor['targets'][donor_index])
if task_id in DATA_PREFIX_ZONE_SCHEDULE:
for (target, zones) in zip(task['targets'], DATA_PREFIX_ZONE_SCHEDULE[task_id]):
target['placement']['required_zones'] = list(zones)
position = DATA_TASK_IDS_2.index(task_id)
for (target, cell_id) in zip(task['targets'], DATA_CELL_SCHEDULE_2[position]):
conditions = fn_cell_conditions(cell_id)
target['workload'].update({key: conditions[key] for key in ('workload_class', 'change_window')})
target['service'].update({key: conditions[key] for key in ('access_class', 'traffic_class')})
return task
def fn_public_task_8(task_id):
task = ext_deepcopy(fn_public_task_9(task_id))
if task_id in {'T07', 'T11', 'T12'}:
for target in task['targets']:
if target['cluster_selector']['region'] == 'eu-central':
target['placement']['required_zones'] = ['euc1b', 'euc1c']
return task
def fn__replace_scope(target, donor):
target['cluster_selector'] = ext_deepcopy(donor['cluster_selector'])
target['namespace_selector'] = ext_deepcopy(donor['namespace_selector'])
def fn_public_task_9(task_id):
position = DATA_TASK_IDS_2.index(task_id)
task = fn_public_task_10(task_id)
if task_id == 'T09':
anchor = fn_public_task_10('T08')
for (target, old) in zip(task['targets'], anchor['targets']):
for key in ('cluster_selector', 'namespace_selector', 'placement'):
target[key] = ext_deepcopy(old[key])
task['schema'] = 'rescopebench-public-task/k8s-pool-release'
task['objective'] = 'Create the four requested deployment-and-service release artifacts. Resolve the local action requirements for each full workload/service condition tuple. Place one replica in each required zone using a worker pool currently assigned to the target namespace; node readiness alone does not establish that assignment. Use the supplied DNS value only when the local policy requires DNS, otherwise omit it. Any cluster-wide free NodePort is acceptable when required.'
for (target, cell) in zip(task['targets'], DATA_CELL_SCHEDULE_3[position]):
conditions = fn_cell_conditions(cell)
target['workload'].update({k: conditions[k] for k in ('workload_class', 'change_window')})
target['service'].update({k: conditions[k] for k in ('access_class', 'traffic_class')})
token = target['release_id'].removeprefix('rel-')
target['service']['external_dns'] = f'svc-{token}.bench.harborbridge-ops.io'
if task_id == 'T06' and target['cluster_selector']['region'] == 'us-east':
target['placement']['required_zones'] = ['use1a', 'use1c']
task['budget']['limits'][0]['allowance'] = 120
task['budget']['charging'].append('Worker-pool catalogs cost two units plus requested rows; inspecting one pool costs three units.')
return task
def fn_public_task_10(task_id):
result = fn_public_task_11(task_id)
result['schema'] = 'rescopebench-public-task/k8s-staged-structure-v4'
result['objective'] = result['objective'] + " Place each workload in exactly the two availability zones listed in that request's placement.required_zones field."
for target in result['targets']:
cluster_id = 'cluster-atlas-prod-us-east' if target['cluster_selector']['region'] == 'us-east' else 'cluster-meridian-prod-eu-central'
target['placement']['required_zones'] = list(fn_required_zones(task_id, cluster_id))
result['completion'] = {'mode': 'independent', 'subset_allowed': True, 'priority_order': 'none', 'started_item_must_close': True, 'verification_required': False}
result['budget'] = {'limits': [{'resource': 'API work units', 'allowance': 120}], 'charging': ['List operations consume two work units plus one per requested row.', 'Bounded inspections consume three work units plus included context; inspecting one local policy cell consumes eighteen work units.', 'Publishing a deployment consumes eight work units plus three per added replica.', 'Creating a service consumes eight work units plus two per port.', 'Invalid allowed-tool calls and failed writes consume their declared work units.'], 'exhaustion': 'An unfunded operation is rejected before business dispatch without changing business state or consuming additional work units.', 'persistence': 'API work units replenish at each request event; deployments, pods, services, namespace quota, and worker-node capacity persist.'}
return result
def fn_public_task_11(task_id):
if task_id not in DATA_TASK_BY_ID:
raise ValueError(f'unknown Kubernetes task: {task_id}')
result = fn_public_task_projection(DATA_TASK_BY_ID[task_id])
result['schema'] = 'rescopebench-public-task/k8s-structure-v3'
return result
def fn_required_zones(task_id, cluster_id):
if cluster_id == 'cluster-meridian-prod-eu-central':
return ('euc1a', 'euc1b')
if cluster_id != 'cluster-atlas-prod-us-east':
raise ValueError(f'unsupported cluster binding: {cluster_id}')
if task_id in {'T08', 'T09'}:
return ('use1a', 'use1c')
return ('use1a', 'use1b')
def fn_public_task_projection(task):
public = mod_copy.deepcopy(task)
event_id = public.pop('event_id')
public.pop('limitation', None)
public['schema'] = 'rescopebench-public-task/k8s-stream-v2'
public['status'] = 'frozen_runnable'
public['runnable'] = True
public['task_id'] = event_id
public['episode_id'] = event_id
public['event_id'] = event_id
public['budget'] = {**public['budget'], 'allowance': 120, 'status': 'measured'}
fn_assert_opaque_learner_surface(public, surface='Kubernetes public task')
return public
def fn_assert_opaque_learner_surface(value, *, surface):
hits = fn_leakage_hits(value)
present = {name: rows for (name, rows) in hits.items() if rows}
if present:
raise ValueError(f'{surface} exposes private lifecycle metadata: {present}')
try:
ext_assert_hard_public_projection(value)
except ValueError as error:
raise ValueError(f'{surface} exposes private lifecycle metadata: {error}') from error
def fn_leakage_hits(value):
"""Report private lifecycle labels in a learner/provider-visible value."""
encoded = mod_json.dumps(value, ensure_ascii=True, sort_keys=True, allow_nan=False)
private_keys: set[str] = set()
def visit(item):
if isinstance(item, dict):
private_keys.update((str(key) for key in item if key in DATA__PRIVATE_KEYS))
for nested in item.values():
visit(nested)
elif isinstance(item, list):
for nested in item:
visit(nested)
visit(value)
return {'private_episode_ids': sorted(set(_re.compile('(?<![A-Za-z0-9])T(?:0[1-9]|1[0-6])(?![A-Za-z0-9]|:[0-5][0-9])', 34).findall(encoded))), 'arm_labels': sorted(set(_re.compile('(?<![A-Za-z0-9])(?:native|reset|reflect)\\d{2}(?![A-Za-z0-9])', 34).findall(encoded))), 'run_paths': sorted(set(_re.compile('(?:benchmark_outputs[/\\\\]robot|robot-final-v\\d+[/\\\\]20\\d{6}-\\d{6})', 34).findall(encoded))), 'private_keys': sorted(private_keys)}
class World:
def __init__(self, *args, **kwargs):
self.namespace_identity_migrations = {}
self._kubernetes_assignment_world_init(*args, **kwargs)
affected = set()
for task_id in DATA_TASK_IDS:
for target in fn_private_task(task_id)['targets']:
cluster = next((row for row in self._rows('cluster') if all((row.get(k) == v for (k, v) in target['cluster_selector'].items()))))
if not any((cluster['cluster_id'] + '/' + zone in DATA_CHANGED_S for zone in target['placement']['required_zones'])):
continue
namespace = next((row for row in self._rows('namespace') if row['cluster_id'] == cluster['cluster_id'] and all((row.get(k) == v for (k, v) in target['namespace_selector'].items()))))
affected.add(namespace['namespace_id'])
self.namespace_identity_migrations = {old: 'ns-migrated-' + fn_digest(['k8s-namespace-migration-evolution-v6', old])[:20] for old in sorted(affected)}
self._original_allocation_keys = set(self.namespace_pool_bindings)
def _allocation_key(self, key, migrated):
(namespace, zone) = key.rsplit('|', 1)
return fn_binding_key(self.namespace_identity_migrations.get(namespace, namespace) if migrated else namespace, zone)
def apply_event(self, event_id):
if event_id != 'E1' or event_id in self.applied_boundary_events:
return self._kubernetes_assignment_world_apply_event(event_id)
before = self.business_hash()
receipt = self._kubernetes_assignment_world_apply_event(event_id)
database = self.manager.snapshot()['database']
self.manager.db._data = fn_rekey_database(database, self.namespace_identity_migrations)
self.manager.db._id_counters = {}
self.manager._core_state_cache = None
self.namespace_pool_bindings = {self._allocation_key(key, True): pool for (key, pool) in self.namespace_pool_bindings.items()}
self._refresh_ids()
return {**receipt, 'before': before, 'after': self.business_hash(), 'namespace_identity_migrations': ext_deepcopy(self.namespace_identity_migrations), 'preserves_workloads_capacity_and_policy': True}
def snapshot(self):
value = self._kubernetes_independent_world_snapshot()
if not getattr(self, '_restoring_namespace_migration', False):
value['namespace_identity_contract'] = {'case_version': 'k8s-namespace-migration-evolution-v6', 'migrations': ext_deepcopy(self.namespace_identity_migrations)}
return value
def restore(self, snapshot):
value = ext_deepcopy(snapshot)
if value.pop('namespace_identity_contract', None) != {'case_version': 'k8s-namespace-migration-evolution-v6', 'migrations': self.namespace_identity_migrations}:
raise ValueError('K8s namespace migration snapshot identity differs')
migrated = 'E1' in value['applied_boundary_events']
expected = {self._allocation_key(key, migrated) for key in self._original_allocation_keys}
actual = value['namespace_allocation_contract']['bindings']
if set(actual) != expected:
raise ValueError('K8s namespace migration allocation scope differs')
ids = {row['namespace_id'] for row in value['raw']['database']['namespace']}
required = set(self.namespace_identity_migrations.values() if migrated else self.namespace_identity_migrations)
forbidden = set(self.namespace_identity_migrations if migrated else self.namespace_identity_migrations.values())
if not required <= ids or forbidden & ids:
raise ValueError('K8s namespace migration entity scope differs')
self.namespace_pool_bindings = ext_deepcopy(actual)
self._restoring_namespace_migration = True
try:
self._kubernetes_independent_world_restore(value)
finally:
self._restoring_namespace_migration = False
if self.snapshot() != snapshot:
raise ValueError('K8s namespace migration snapshot did not round trip')
def task(self, task_id=None):
return fn_private_task(task_id or self.current_task_id)
def _publish_guard(self, public_arguments):
target = self._target_for_release(public_arguments.get('release_id'))
if target is None:
return ('RELEASE_REQUEST_UNKNOWN', 'release_id is not active in this request')
workload = target['workload']
expected = {**{key: workload[key] for key in ('name', 'app_label', 'image', 'image_tag', 'desired_replicas', 'workload_class', 'change_window')}, 'placement_class': target['placement']['placement_class'], 'access_class': target['service']['access_class'], 'traffic_class': target['service']['traffic_class']}
if any((public_arguments.get(key) != value for (key, value) in expected.items())):
return ('RELEASE_REQUEST_MISMATCH', 'deployment fields do not match the active release request')
namespace_internal = self.internal_ids.get(public_arguments.get('namespace_id'))
namespace = self._get('namespace', namespace_internal) if namespace_internal else None
cluster = self._get('cluster', namespace.get('cluster_id')) if namespace else None
if not namespace or not cluster:
return ('RELEASE_SCOPE_MISMATCH', 'namespace handle is outside the active request scope')
if any((namespace.get(key) != value for (key, value) in target['namespace_selector'].items())) or any((cluster.get(key) != value for (key, value) in target['cluster_selector'].items())):
return ('RELEASE_SCOPE_MISMATCH', 'namespace handle is outside the active request scope')
return None
def public_tool_schemas(self):
return ext_deepcopy(DATA_PUBLIC_TOOLS)
def _inspect_pool(self, arguments):
namespace = self._get('namespace', arguments['namespace_id'])
pool = self.pools.get(arguments['pool_id'])
if pool is None or namespace is None or namespace.get('cluster_id') != pool['cluster_id']:
return self._result('inspect_worker_pool', 'error', 'POOL_SCOPE_MISMATCH: pool and namespace must share a cluster', {'error_code': 'POOL_SCOPE_MISMATCH'})
result = self._kubernetes_binding_successor_inspect_pool({'pool_id': arguments['pool_id']})
if result['content'].get('status') != 'success':
return result
data = result['content']['data']
key = fn_binding_key(namespace['namespace_id'], pool['zone'])
data['assignment'] = {'status': 'assigned' if namespace.get('status') == 'active' and self.namespace_pool_bindings.get(key) == pool['pool_id'] else 'not_assigned', 'binding_key': {'namespace_id': namespace['namespace_id'], 'zone': pool['zone']}, 'applies_to': {'cluster_id': pool['cluster_id'], 'namespace_id': namespace['namespace_id'], 'namespace_status': 'active'}, 'pool_id': pool['pool_id']}
return result
def dispatch(self, tool, arguments, actor='platform_release_operator'):
if tool != 'inspect_worker_pool':
return self._kubernetes_binding_successor_dispatch(tool, arguments, actor=actor)
normalized = ext_deepcopy(arguments)
before = self.business_hash() if self.receipt_hashes else None
if actor != 'platform_release_operator':
return self._record(tool, actor, normalized, self._result(tool, 'error', 'TOOL_FORBIDDEN: actor is outside the release slice'), 0, before)
cost = self._cost(tool, normalized)
if self.remaining < cost:
return self._record(tool, actor, normalized, self._result(tool, 'error', 'WORK_QUOTA_EXHAUSTED: insufficient API-work quota'), 0, before)
self.remaining -= cost
error = fn__validate_value(normalized, DATA_SCHEMAS[tool], 'arguments')
try:
internal = self._internalize(normalized) if not error else None
except (KeyError, TypeError, ValueError):
(error, internal) = ('an object handle was not issued by this environment', None)
result = self._result(tool, 'error', 'INVALID_ARGUMENTS: ' + error, {'error_code': 'INVALID_ARGUMENTS'}) if error else self._inspect_pool(internal)
return self._record(tool, actor, normalized, self.publicize(result), cost, before)
def _pool_error(self, namespace_id, node_ids, tool):
namespace = self._get('namespace', namespace_id)
if namespace is None:
return None
for node_id in node_ids:
node = self._get('node', node_id)
if node is None or node.get('cluster_id') != namespace['cluster_id']:
continue
pool = self.namespace_pool_bindings.get(fn_binding_key(namespace_id, node.get('zone', '')))
if pool is None or node_id not in self.pools[pool]['node_ids']:
return self._result(tool, 'error', 'WORKER_POOL_SCOPE_MISMATCH: selected worker is not allocated to this namespace in this zone', {'error_code': 'WORKER_POOL_SCOPE_MISMATCH', 'namespace_id': namespace_id, 'node_id': node_id, 'zone': node.get('zone')})
return None
def eligible_nodes(self):
result = ext_defaultdict(set)
for (key, pool) in self.namespace_pool_bindings.items():
(namespace, _) = key.rsplit('|', 1)
result[namespace].update(self.pools[pool]['node_ids'])
return dict(result)
def business_hash(self):
return fn_digest({'parent': self._kubernetes_mixed_successor_business_hash(), 'namespace_allocations': self.namespace_pool_bindings})
def _business_hash_from_snapshot(self, snapshot):
return fn_digest({'parent': self._kubernetes_mixed_successor_business_hash_from_snapshot(snapshot), 'namespace_allocations': snapshot['namespace_allocation_contract']['bindings']})
def _list_exact_namespaces(self, arguments):
raw = self.server.call_tool('list_namespaces', state_manager=self.manager, cluster_id=arguments['cluster_id'], status_filter=arguments['status_filter'], owner_team_contains=arguments['owner_team'], limit=100, offset=0)
result = fn__sanitize_raw_result('list_namespaces', raw)
if result['content'].get('status') != 'success':
return result
rows = [row for row in result['content']['data'].get('namespaces', []) if row.get('name') == arguments['name'] and row.get('owner_team') == arguments['owner_team']]
for row in rows:
row['directory_id'] = f"directory:{arguments['cluster_id']}"
row['binding_scope'] = {'cluster_id': arguments['cluster_id'], 'name': row['name'], 'owner_team': row['owner_team'], 'status': row['status']}
row['stable_fields'] = ['namespace_id', 'cluster_id', 'directory_id', 'name', 'owner_team']
row['live_fields'] = ['status', 'active_pods', 'quota_pods']
result['content']['data'] = {'total_count': len(rows), 'limit': arguments['limit'], 'offset': 0, 'namespaces': rows[:arguments['limit']]}
return result
def prepare_task(self, task_id, **kwargs):
result = self._kubernetes_evolution_prepare_task(task_id, **kwargs)
result['public']['event_id'] = fn_public_task(task_id)['event_id']
return result
def _policy(self, arguments):
mapping = DATA_POST_POLICY if self.policy_epoch == 'post' else DATA_POLICY_BY_CONDITIONS
return mapping.get(fn_condition_key(arguments))
def _public_id(self, value):
if value not in self.public_ids:
handle = 'obj-' + fn_digest(['k8s-operations-binding-v9', 'public-object', value])[:20]
if handle in self.internal_ids and self.internal_ids[handle] != value:
raise RuntimeError('public handle collision')
self.public_ids[value] = handle
self.internal_ids[handle] = value
return self.public_ids[value]
def _inspect_release_policy(self, arguments):
result = self._kubernetes_release_adapter_inspect_release_policy(arguments)
if result['content'].get('status') == 'success':
data = result['content']['data']
data['binding_scope'] = {'conditions': ext_deepcopy(data['conditions']), 'environment': 'production release policy'}
data['stable_fields'] = ['conditions', 'requirements', 'policy_id']
data['revalidate_on'] = ['a current policy read disagrees', 'a policy-gated write is rejected']
return result
def _visible_pool_binding(self, binding):
return self.pool_bindings[binding]
def _target_for_release(self, release_id):
return next((target for target in self.task()['targets'] if target['release_id'] == release_id), None)
def _release_complete(self, target):
deployments = [row for row in self._rows('deployment') if row.get('app_label') == target['workload']['app_label'] and row.get('created_by') == target['release_id']]
if len(deployments) != 1:
return False
deployment = deployments[0]
services = [row for row in self._rows('service') if row.get('deployment_id') == deployment['deployment_id'] and row.get('name') == target['service']['name']]
return len(services) == 1 and deployment.get('rollout_status') == 'stable'
def _charged_error(self, tool, arguments, code, message, before_hash):
cost = self._cost(tool, arguments)
if self.remaining < cost:
result = self._result(tool, 'error', 'WORK_QUOTA_EXHAUSTED: insufficient API-work quota', {'error_code': 'WORK_QUOTA_EXHAUSTED'})
return self._record(tool, 'platform_release_operator', arguments, result, 0, before_hash)
self.remaining -= cost
result = self._result(tool, 'error', f'{code}: {message}', {'error_code': code})
return self._record(tool, 'platform_release_operator', arguments, result, cost, before_hash)
def _publish(self, arguments):
result = self._kubernetes_pool_successor_publish(arguments)
if result['content'].get('status') == 'success':
for node_id in arguments.get('placement_node_ids', []):
node = self._get('node', node_id)
if not node:
continue
binding = f"{node['cluster_id']}/{node['zone']}"
if binding in self.binding_revalidation:
self.binding_revalidation[binding] = 'validated_current'
result['content']['data']['release_ref'] = arguments['created_by']
result['content']['data']['request_binding_verified'] = True
return result
def _create_service(self, arguments):
result = self._kubernetes_pool_successor_create_service(arguments)
if result['content'].get('status') == 'success':
deployment = self._get('deployment', arguments['deployment_id'])
if deployment:
result['content']['data']['release_ref'] = deployment.get('created_by')
result['content']['data']['artifact_binding_verified'] = True
return result
def apply_binding_drift(self):
if 'k8s-worker-pool-reassignment-v9' in self.applied_boundary_events:
return {'event_id': 'k8s-worker-pool-reassignment-v9', 'idempotent': True, 'bindings': []}
changes = []
for binding in DATA_CHANGED_BINDINGS:
previous = self.pool_bindings[binding]
replacement = next((pool_id for (pool_id, row) in self.pools.items() if f"{row['cluster_id']}/{row['zone']}" == binding and pool_id != previous))
self.stale_pool_bindings[binding] = previous
self.pool_bindings[binding] = replacement
self.binding_revalidation[binding] = 'awaiting_stale_write'
changes.append({'binding': binding, 'before': previous, 'after': replacement, 'before_nodes': list(self.pools[previous]['node_ids']), 'after_nodes': list(self.pools[replacement]['node_ids'])})
self.applied_boundary_events.add('k8s-worker-pool-reassignment-v9')
return {'event_id': 'k8s-worker-pool-reassignment-v9', 'idempotent': False, 'bindings': changes}
def apply_mixed_drift(self):
return self.apply_binding_drift()
def apply_pool_drift(self):
return self.apply_binding_drift()
def _workload_policy(self, arguments):
return self._policy(arguments)
def semantic_hash(self):
return fn_digest(self.snapshot())
def _normalize(self, tool, arguments):
if tool == 'list_namespaces' and isinstance(arguments, dict):
normalized = ext_deepcopy(arguments)
normalized.setdefault('limit', 4)
normalized.setdefault('offset', 0)
return normalized
supplied_limit = isinstance(arguments, dict) and 'limit' in arguments
normalized = self._kubernetes_pool_successor_normalize(tool, arguments)
if isinstance(normalized, dict) and (not supplied_limit):
if tool in {'list_clusters', 'list_namespaces'}:
normalized['limit'] = 4
elif tool == 'list_worker_pools':
normalized['limit'] = 2
return normalized
def _cost(self, tool, arguments):
if tool in {'list_clusters', 'list_namespaces', 'list_worker_pools'}:
minimum = 2 if tool == 'list_worker_pools' else 4
default = minimum
if isinstance(arguments, dict):
limit = arguments.get('limit', default)
offset = arguments.get('offset', 0)
if type(limit) is int and type(offset) is int and (limit >= 1) and (offset >= 0):
return 2 + max(minimum, offset + limit)
return 2 + minimum
return self._kubernetes_pool_successor_cost(tool, arguments)
def _refresh_ids(self):
for (entity, field) in DATA_ID_FIELDS.items():
for row in self._rows(entity):
self._public_id(row[field])
for value in (*self.directories, *self.pools):
self._public_id(value)
def publicize(self, value, key=''):
if isinstance(value, dict):
return {k: self.publicize(v, k) for (k, v) in value.items()}
if isinstance(value, list):
return [self.publicize(v, key) for v in value]
if isinstance(value, str) and (value in self.public_ids or key.endswith('_id') or key.endswith('_ids')):
return self._public_id(value)
return value
def _internalize(self, value, key=''):
if isinstance(value, dict):
return {k: self._internalize(v, k) for (k, v) in value.items()}
if isinstance(value, list):
return [self._internalize(v, key) for v in value]
if isinstance(value, str) and (key.endswith('_id') or key.endswith('_ids')):
if value not in self.internal_ids:
raise ValueError('an object handle was not issued by this environment')
return self.internal_ids[value]
return value
def _namespace_members(self, cluster_id):
return [n['namespace_id'] for n in self._rows('namespace') if n.get('cluster_id') == cluster_id and n.get('status') == 'active']
def _scale(self, arguments):
deployment = self._get('deployment', arguments['deployment_id'])
if deployment:
rejected = self._pool_error(deployment['namespace_id'], arguments.get('placement_node_ids', []), 'update_deployment_replicas')
if rejected:
return rejected
return self._kubernetes_release_adapter_scale(arguments)
def _service_guard(self, arguments):
deployment = self._get('deployment', arguments['deployment_id'])
if deployment and any((deployment.get('intended_' + k) != arguments[k] for k in ('access_class', 'traffic_class'))):
return 'SERVICE_CONDITION_MISMATCH: service conditions differ from the deployment admission request'
return self._kubernetes_release_adapter_service_guard(arguments)
def _list_pools(self, arguments):
cluster = self.directories.get(arguments['directory_id'])
if cluster is None:
return self._result('list_worker_pools', 'error', 'DIRECTORY_NOT_FOUND: unknown worker-pool directory')
pools = [p for p in self.pools.values() if p['cluster_id'] == cluster and p['zone'] == arguments['zone']]
pools.sort(key=lambda p: self._public_id(p['pool_id']))
selected = pools[arguments['offset']:arguments['offset'] + arguments['limit']]
rows = [{'pool_id': p['pool_id'], 'zone': p['zone'], 'member_count': len(p['node_ids'])} for p in selected]
return self._result('list_worker_pools', 'success', 'OK', {'pools': rows, 'total_count': len(pools), 'limit': arguments['limit'], 'offset': arguments['offset']})
def close(self):
self.server.cleanup_runtime()
def begin_episode(self, allowance=120, *, verify_business_hash=True):
"""Replenish only task-local work quota while preserving the business world."""
if not isinstance(allowance, int) or isinstance(allowance, bool) or allowance <= 0:
raise ValueError('allowance must be a positive integer')
before_business_hash = self.business_hash() if verify_business_hash else None
previous_remaining = self.remaining
self.initial_budget = allowance
self.remaining = allowance
self.receipts = []
return {'status': 'success', 'allowance': allowance, 'previous_remaining': previous_remaining, 'business_hash_preserved': self.business_hash() == before_business_hash if verify_business_hash else None}
def _result(self, tool, status, message, data=None):
return {'type': 'tool_result', 'tool': tool, 'content': {'status': status, 'data': data or {}, 'message': message}}
def _record(self, tool, actor, arguments, result, cost, before_hash):
content = result['content']
receipt = {'index': len(self.receipts) + 1, 'tool': tool, 'actor': actor, 'arguments': mod_copy.deepcopy(arguments), 'status': content.get('status'), 'cost': cost, 'before_business_hash': before_hash, 'after_business_hash': self.business_hash() if self.receipt_hashes else None, 'remaining': self.remaining}
self.receipts.append(receipt)
result['budget'] = {'charged': cost, 'remaining': self.remaining}
result['receipt_index'] = receipt['index']
return result
def _get(self, entity, entity_id):
return self.manager.get_entity(entity, entity_id, id_field=DATA_ID_FIELDS[entity])
def _rows(self, entity):
return self.manager.list_entities(entity)
def _save(self, entity, row):
return self.manager.add_entity(entity, row, id_field=DATA_ID_FIELDS[entity])
def _unique(self, candidate, entity):
used = {row.get(DATA_ID_FIELDS[entity]) for row in self._rows(entity)}
if candidate not in used:
return candidate
index = 2
while f'{candidate}-{index}' in used:
index += 1
return f'{candidate}-{index}'
def _deployment_id(self, arguments):
namespace = str(arguments['namespace_id'])
namespace_slug = namespace[3:] if namespace.startswith('ns-') else fn__slug(namespace)
return f"deploy-{namespace_slug}-{fn__slug(arguments['app_label'], 'app')}-{fn__slug(arguments.get('update_strategy'), 'rolling')}"
def _event(self, *, cluster_id, namespace_id, kind, involved_id, severity, reason, message):
cluster_slug = cluster_id.removeprefix('cluster-')
event_id = self._unique(f'event-{cluster_slug}-2026-05-27t12-00-00-{fn__slug(reason)}', 'cluster_event')
row = {'event_id': event_id, 'cluster_id': cluster_id, 'namespace_id': namespace_id, 'involved_kind': kind, 'involved_id': involved_id, 'severity': severity, 'reason': reason, 'message': message, 'observed_at': '2026-05-27T12:00:00Z', 'created_at': '2026-05-27T12:00:00Z'}
self._save('cluster_event', row)
return {'event_id': event_id, 'severity': severity, 'reason': reason, 'observed_at': '2026-05-27T12:00:00Z'}
def _action(self, deployment, requested_by, reason, previous, target):
ns_slug = str(deployment['namespace_id']).removeprefix('ns-')
action_id = self._unique(f'scale-{ns_slug}-2026-05-27t12-00-00-manual-scale', 'scaling_action')
self._save('scaling_action', {'action_id': action_id, 'cluster_id': deployment['cluster_id'], 'namespace_id': deployment['namespace_id'], 'deployment_id': deployment['deployment_id'], 'requested_by': requested_by, 'action_type': 'manual_scale', 'previous_replicas': previous, 'target_replicas': target, 'status': 'applied', 'reason': reason, 'started_at': '2026-05-27T12:00:00Z', 'completed_at': '2026-05-27T12:00:00Z', 'created_at': '2026-05-27T12:00:00Z'})
return action_id
def _placement_error(self, cluster_id, node_ids, expected_count):
if len(node_ids) != expected_count:
return 'PLACEMENT_COUNT_MISMATCH: placement_node_ids must contain one entry per added replica'
planned: dict[str, int] = {}
for node_id in node_ids:
node = self._get('node', node_id)
if not node or node.get('cluster_id') != cluster_id:
return 'PLACEMENT_SCOPE_MISMATCH: a placement node is absent or outside the deployment cluster'
if node.get('role') != 'worker' or node.get('readiness') != 'ready' or (not node.get('schedulable')):
return 'NODE_NOT_SCHEDULABLE: a placement node is not a ready schedulable worker'
planned[node_id] = planned.get(node_id, 0) + 1
capacity = int(node.get('allocatable_pods') or node.get('capacity_pods') or 0)
if int(node.get('active_pods') or 0) + planned[node_id] > capacity:
return 'NODE_CAPACITY_EXCEEDED: a placement node has insufficient pod capacity'
return None
def _make_pod(self, deployment, ordinal, node_id):
namespace_slug = str(deployment['namespace_id']).removeprefix('ns-')
base = f"pod-{namespace_slug}-{fn__slug(deployment['app_label'])}-{fn__slug(ordinal)}-running"
pod_id = self._unique(base, 'pod')
count = len(self._rows('pod'))
pod = {'pod_id': pod_id, 'cluster_id': deployment['cluster_id'], 'namespace_id': deployment['namespace_id'], 'deployment_id': deployment['deployment_id'], 'node_id': node_id, 'name': f"{deployment['app_label']}-{ordinal}", 'phase': 'Running', 'readiness': 'ready', 'restart_count': 0, 'image': deployment['image'], 'image_tag': deployment['image_tag'], 'pod_ip': f'10.255.{count % 255}.{count * 7 % 255}', 'container_count': 1, 'started_at': '2026-05-27T12:00:00Z', 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z', 'labels': {'app': deployment['app_label'], 'deployment': deployment['name'], 'managed_by': 'cluster-manager'}}
self._save('pod', pod)
node = self._get('node', node_id)
if node is None:
raise RuntimeError('validated placement node disappeared')
node['active_pods'] = int(node.get('active_pods') or 0) + 1
node['updated_at'] = '2026-05-27T12:00:00Z'
self._save('node', node)
return pod
def _reconcile_deployment(self, deployment):
nodes = {row['node_id']: row for row in self._rows('node')}
ready = 0
for pod in self._rows('pod'):
if pod.get('deployment_id') != deployment['deployment_id']:
continue
node = nodes.get(pod.get('node_id'))
if pod.get('phase') == 'Running' and pod.get('readiness') == 'ready' and node and (node.get('readiness') == 'ready') and node.get('schedulable'):
ready += 1
desired = int(deployment.get('desired_replicas') or 0)
deployment['ready_replicas'] = ready
deployment['available_replicas'] = ready
deployment['rollout_status'] = 'stable' if ready == desired else 'degraded'
deployment['updated_at'] = '2026-05-27T12:00:00Z'
return self._save('deployment', deployment)
def _list_clusters(self, arguments):
rows = self._rows('cluster')
for field in ('region', 'environment', 'status'):
value = arguments.get(field)
if value:
rows = [row for row in rows if row.get(field) == value]
rows.sort(key=lambda row: (row.get('name') or '', row.get('cluster_id') or ''))
total = len(rows)
offset = arguments['offset']
limit = arguments['limit']
rows = rows[offset:offset + limit]
visible = [{'cluster_id': row['cluster_id'], 'name': row.get('name'), 'region': row.get('region'), 'environment': row.get('environment'), 'status': row.get('status'), 'kubernetes_version': row.get('kubernetes_version'), 'pod_capacity': row.get('pod_capacity'), 'pod_allocated': row.get('pod_allocated')} for row in rows]
return self._result('list_clusters', 'success', 'OK', {'total_count': total, 'limit': limit, 'offset': offset, 'clusters': visible})
def apply_node_drift(self, event_id, node_ids):
if event_id in self.applied_boundary_events:
return {'status': 'success', 'event_id': event_id, 'idempotent': True, 'changed': []}
before = self.snapshot() if self.atomic_snapshots else None
changed: list[str] = []
affected_deployments: set[str] = set()
try:
for node_id in node_ids:
node = self._get('node', node_id)
if not node or node.get('role') != 'worker':
continue
if node.get('schedulable') or node.get('readiness') == 'ready':
node['schedulable'] = False
node['readiness'] = 'maintenance'
node['updated_at'] = '2026-05-27T12:00:00Z'
self._save('node', node)
changed.append(node_id)
for pod in self._rows('pod'):
if pod.get('node_id') == node_id and pod.get('phase') == 'Running' and (pod.get('readiness') == 'ready'):
pod['readiness'] = 'not_ready'
pod['updated_at'] = '2026-05-27T12:00:00Z'
self._save('pod', pod)
affected_deployments.add(pod['deployment_id'])
self._event(cluster_id=node['cluster_id'], namespace_id=None, kind='Node', involved_id=node_id, severity='warning', reason='NodeMaintenance', message=f"Node {node.get('name')} entered maintenance.")
for deployment_id in affected_deployments:
deployment = self._get('deployment', deployment_id)
if deployment:
self._reconcile_deployment(deployment)
self.applied_boundary_events.add(event_id)
except Exception:
if before is not None:
self.restore(before)
return {'status': 'error', 'event_id': event_id, 'idempotent': False, 'changed': []}
return {'status': 'success', 'event_id': event_id, 'idempotent': False, 'changed': changed}
def _kubernetes_assignment_world_init(self, *args, **kwargs):
self.namespace_pool_bindings = {}
self._kubernetes_binding_successor_init(*args, **kwargs)
for binding in DATA_CHANGED_BINDINGS:
(cluster, zone) = binding.split('/')
used = {node for pool in self.pools.values() for node in pool['node_ids']}
available = [node for node in self._rows('node') if node['cluster_id'] == cluster and node['zone'] == zone and (node.get('role') == 'worker') and (node.get('readiness') == 'ready') and (node.get('schedulable') is True) and (node['node_id'] not in used) and (int(node.get('allocatable_pods') or 0) - int(node.get('active_pods') or 0) >= 48)]
available.sort(key=lambda node: fn_digest(['k8s-namespace-allocation-evolution-v4', 'existing-worker', node['node_id']]))
if len(available) < 4:
raise ValueError('Insufficient real workers for four disjoint candidate pools: ' + binding)
for index in range(2):
pool_id = f'pool:{binding}:{index + 2}'
self.pools[pool_id] = {'pool_id': pool_id, 'directory_id': 'directory:' + cluster, 'cluster_id': cluster, 'zone': zone, 'node_ids': [node['node_id'] for node in available[index * 2:index * 2 + 2]]}
for namespace in self._namespace_members(cluster):
self.namespace_pool_bindings[fn_binding_key(namespace, zone)] = self.pool_bindings[binding]
self._refresh_ids()
def _kubernetes_assignment_world_apply_event(self, event_id):
if event_id != 'E1' or event_id in self.applied_boundary_events:
return self._kubernetes_evolution_apply_event(event_id)
before = self.business_hash()
changes = []
for (key, old) in list(self.namespace_pool_bindings.items()):
(namespace, zone) = key.rsplit('|', 1)
cluster = self._get('namespace', namespace)['cluster_id']
if f'{cluster}/{zone}' not in DATA_CHANGED_S:
continue
candidates = sorted((p['pool_id'] for p in self.pools.values() if p['cluster_id'] == cluster and p['zone'] == zone and (p['pool_id'] != old)))
new = candidates[int(fn_digest(['k8s-namespace-allocation-evolution-v4', 'allocation', key])[:8], 16) % len(candidates)]
self.namespace_pool_bindings[key] = new
changes.append({'namespace_id': namespace, 'zone': zone, 'before': old, 'after': new})
self.applied_boundary_events.add(event_id)
return {'event_id': event_id, 'applied': True, 'before': before, 'after': self.business_hash(), 'allocations': changes}
def _kubernetes_independent_world_snapshot(self):
value = self._kubernetes_assignment_world_snapshot()
if not getattr(self, '_restoring_independent', False):
value['independent_releases_contract'] = 'k8s-independent-releases-evolution-v5'
return value
def _kubernetes_independent_world_restore(self, snapshot):
value = ext_deepcopy(snapshot)
if value.pop('independent_releases_contract', None) != 'k8s-independent-releases-evolution-v5':
raise ValueError('K8s independent-release snapshot version differs')
self._restoring_independent = True
try:
self._kubernetes_assignment_world_restore(value)
finally:
self._restoring_independent = False
if self.snapshot() != snapshot:
raise ValueError('K8s independent-release snapshot did not round trip')
def _kubernetes_binding_successor_inspect_pool(self, arguments):
result = self._kubernetes_pool_successor_inspect_pool(arguments)
if result['content'].get('status') != 'success':
return result
data = result['content']['data']
pool = self.pools[arguments['pool_id']]
binding = f"{pool['cluster_id']}/{pool['zone']}"
assigned = self._visible_pool_binding(binding) == pool['pool_id']
data.pop('eligible_namespace_ids', None)
data['assignment'] = {'status': 'assigned' if assigned else 'not_assigned', 'binding_key': {'directory_id': pool['directory_id'], 'zone': pool['zone']}, 'applies_to': {'cluster_id': pool['cluster_id'], 'namespace_status': 'active'}, 'pool_id': pool['pool_id']}
data['stable_fields'] = ['assignment.binding_key', 'assignment.applies_to', 'assignment.pool_id', 'nodes[].node_id', 'nodes[].zone']
data['live_fields'] = ['assignment.status', 'nodes[].readiness', 'nodes[].schedulable', 'nodes[].active_pods', 'nodes[].allocatable_pods']
return result
def _kubernetes_binding_successor_dispatch(self, tool, arguments, actor='platform_release_operator'):
if tool not in {'list_namespaces', 'publish_deployment'}:
return self._kubernetes_pool_successor_dispatch(tool, arguments, actor=actor)
normalized = ext_deepcopy(arguments) if isinstance(arguments, dict) else arguments
if tool == 'list_namespaces' and isinstance(normalized, dict):
normalized.setdefault('limit', 4)
normalized.setdefault('offset', 0)
before_hash = self.business_hash() if self.receipt_hashes else None
if actor != 'platform_release_operator' or tool not in DATA_SCHEMAS_2:
result = self._result(tool, 'error', 'TOOL_FORBIDDEN: tool or actor is outside the compact release slice', {'error_code': 'TOOL_FORBIDDEN'})
return self._record(tool, actor, normalized, result, 0, before_hash)
cost = self._cost(tool, normalized)
if self.remaining < cost:
result = self._result(tool, 'error', 'WORK_QUOTA_EXHAUSTED: insufficient API-work quota', {'error_code': 'WORK_QUOTA_EXHAUSTED'})
return self._record(tool, actor, normalized, result, 0, before_hash)
error = fn__validate_value(normalized, DATA_SCHEMAS_2[tool], 'arguments')
if error:
return self._charged_error(tool, normalized, 'INVALID_ARGUMENTS', error, before_hash)
if tool == 'list_namespaces':
self.remaining -= cost
try:
internal = self._internalize(normalized)
result = self._list_exact_namespaces(internal)
except (KeyError, TypeError, ValueError):
result = self._result(tool, 'error', 'INVALID_ARGUMENTS: an object handle was not issued by this environment', {'error_code': 'INVALID_ARGUMENTS'})
result = self.publicize(result)
return self._record(tool, actor, normalized, result, cost, before_hash)
guarded = self._publish_guard(normalized)
if guarded is not None:
return self._charged_error(tool, normalized, *guarded, before_hash)
translated = ext_deepcopy(normalized)
translated['created_by'] = translated.pop('release_id')
result = self._kubernetes_pool_successor_dispatch(tool, translated, actor=actor)
if self.receipts and self.receipts[-1]['tool'] == tool:
self.receipts[-1]['arguments'] = ext_deepcopy(normalized)
return result
def _kubernetes_mixed_successor_business_hash(self):
return fn_digest({'database': self.manager.snapshot()['database'], 'bindings': self.pool_bindings, 'policy_epoch': self.policy_epoch})
def _kubernetes_mixed_successor_business_hash_from_snapshot(self, snapshot):
return fn_digest({'database': snapshot['raw']['database'], 'bindings': snapshot['pool_successor']['bindings'], 'policy_epoch': snapshot.get('mixed_successor', {}).get('policy_epoch', 'pre')})
def _kubernetes_evolution_prepare_task(self, task_id, **kwargs):
if len(self.prepared_tasks) >= len(DATA_TASK_IDS) or task_id != DATA_TASK_IDS[len(self.prepared_tasks)]:
raise ValueError('Kubernetes evolution task prefix differs')
event = next((e for e in DATA_SCHEDULE_2['events'] if e['before_task'] == int(task_id[1:])), None)
receipt = self.apply_event(event['event_id']) if event else None
replenishment = self.begin_episode(120)
self.current_task_id = task_id
self.prepared_tasks.append(task_id)
return {'public': {'status': 'ready', 'event_id': fn_public_task_3(task_id)['event_id']}, 'private_drift_receipt': receipt, 'replenishment': replenishment}
def _kubernetes_release_adapter_inspect_release_policy(self, arguments):
policy = self._policy(arguments)
if policy is None:
return self._result('inspect_release_policy', 'error', 'POLICY_COMBINATION_UNKNOWN: no local release rule matches all supplied conditions')
return self._result('inspect_release_policy', 'success', 'OK', {'policy_id': policy['policy_id'], 'conditions': mod_copy.deepcopy(policy['conditions']), 'requirements': mod_copy.deepcopy(policy['requirements']), 'scope': 'production release policy at the current environment version'})
def _kubernetes_pool_successor_publish(self, arguments):
rejected = self._pool_error(arguments['namespace_id'], arguments['placement_node_ids'], 'publish_deployment')
if rejected:
return rejected
result = self._kubernetes_release_adapter_publish(arguments)
if result['content'].get('status') == 'success':
deployment = self._get('deployment', result['content']['data']['deployment_id'])
deployment['intended_access_class'] = arguments['access_class']
deployment['intended_traffic_class'] = arguments['traffic_class']
self._save('deployment', deployment)
return result
def _kubernetes_pool_successor_create_service(self, arguments):
result = self._kubernetes_release_adapter_create_service(arguments)
if result['content'].get('status') == 'success':
service = self._get('service', result['content']['data']['service_id'])
service['service_role'] = arguments['service_role']
self._save('service', service)
return result
def _kubernetes_pool_successor_normalize(self, tool, arguments):
result = self._kubernetes_release_adapter_normalize(tool, arguments)
if isinstance(result, dict) and tool == 'list_worker_pools':
result.setdefault('limit', 2)
result.setdefault('offset', 0)
return result
def _kubernetes_pool_successor_cost(self, tool, arguments):
if tool == 'list_worker_pools':
value = arguments.get('limit', 2) if isinstance(arguments, dict) else 2
return 2 + (value if type(value) is int and 1 <= value <= 100 else 2)
if tool == 'inspect_worker_pool':
return 3
return self._kubernetes_release_adapter_cost(tool, arguments)
def _kubernetes_release_adapter_scale(self, arguments):
deployment = self._get('deployment', arguments['deployment_id'])
if deployment is None:
return self._result('update_deployment_replicas', 'error', 'DEPLOYMENT_NOT_FOUND: no deployment matches deployment_id')
if deployment.get('rollout_status') == 'paused':
return self._result('update_deployment_replicas', 'error', 'DEPLOYMENT_PAUSED: deployment rollout status is paused')
namespace = self._get('namespace', deployment['namespace_id'])
cluster = self._get('cluster', deployment['cluster_id'])
current = int(deployment.get('desired_replicas') or 0)
target = int(arguments['target_replicas'])
delta = target - current
placements = arguments.get('placement_node_ids', [])
if delta == 0:
if placements:
return self._result('update_deployment_replicas', 'error', 'PLACEMENT_COUNT_MISMATCH: idempotent scale accepts no added placement')
return self._result('update_deployment_replicas', 'success', 'OK', {'deployment_id': deployment['deployment_id'], 'previous_replicas': current, 'target_replicas': target, 'idempotent': True, 'created_pod_ids': [], 'terminated_pod_ids': []})
if namespace is None or cluster is None:
return self._result('update_deployment_replicas', 'error', 'PARENT_SCOPE_MISSING: deployment parent scope is incomplete')
if namespace.get('status') == 'terminating':
return self._result('update_deployment_replicas', 'error', 'NAMESPACE_TERMINATING: parent namespace is terminating')
if delta > 0:
if delta > int(namespace.get('quota_pods') or 0) - int(namespace.get('active_pods') or 0):
return self._result('update_deployment_replicas', 'error', 'QUOTA_EXCEEDED: scale-up exceeds namespace remaining quota')
placement_error = self._placement_error(cluster['cluster_id'], placements, delta)
if placement_error:
return self._result('update_deployment_replicas', 'error', placement_error)
elif placements:
return self._result('update_deployment_replicas', 'error', 'PLACEMENT_COUNT_MISMATCH: scale-down accepts no added placement')
before = self.snapshot() if self.atomic_snapshots else None
created: list[str] = []
terminated: list[str] = []
try:
if delta > 0:
for (index, node_id) in enumerate(placements):
created.append(self._make_pod(deployment, f'scale-{current + index:03d}', node_id)['pod_id'])
else:
active = [row for row in self._rows('pod') if row.get('deployment_id') == deployment['deployment_id'] and row.get('phase') == 'Running']
active.sort(key=lambda row: row['pod_id'], reverse=True)
if len(active) < abs(delta):
raise RuntimeError('not enough active pods to scale down')
for pod in active[:abs(delta)]:
node_id = pod.get('node_id')
if node_id:
node = self._get('node', node_id)
if node:
node['active_pods'] = max(0, int(node.get('active_pods') or 0) - 1)
node['updated_at'] = '2026-05-27T12:00:00Z'
self._save('node', node)
pod['node_id'] = None
pod['phase'] = 'Terminating'
pod['readiness'] = 'not_ready'
pod['pod_ip'] = None
pod['updated_at'] = '2026-05-27T12:00:00Z'
self._save('pod', pod)
terminated.append(pod['pod_id'])
namespace['active_pods'] = max(0, int(namespace.get('active_pods') or 0) + delta)
namespace['updated_at'] = '2026-05-27T12:00:00Z'
self._save('namespace', namespace)
cluster['pod_allocated'] = max(0, int(cluster.get('pod_allocated') or 0) + delta)
cluster['updated_at'] = '2026-05-27T12:00:00Z'
self._save('cluster', cluster)
deployment['desired_replicas'] = target
deployment = self._reconcile_deployment(deployment)
action_id = self._action(deployment, arguments['requested_by'], arguments['reason'], current, target)
event = self._event(cluster_id=deployment['cluster_id'], namespace_id=deployment['namespace_id'], kind='Deployment', involved_id=deployment['deployment_id'], severity='normal', reason='ManualScale', message=f"Deployment {deployment['name']} scaled from {current} to {target}.")
except Exception:
if before is not None:
self.restore(before)
return self._result('update_deployment_replicas', 'error', 'ATOMIC_WRITE_FAILED: scale transaction was rolled back')
return self._result('update_deployment_replicas', 'success', 'OK', {'deployment_id': deployment['deployment_id'], 'previous_replicas': current, 'target_replicas': target, 'ready_replicas': deployment['ready_replicas'], 'idempotent': False, 'created_pod_ids': created, 'terminated_pod_ids': terminated, 'action_id': action_id, 'event': event})
def _kubernetes_release_adapter_service_guard(self, arguments):
deployment = self._get('deployment', arguments['deployment_id'])
if deployment is None:
return None
policy = self._policy({'workload_class': deployment.get('workload_class'), 'change_window': deployment.get('change_window'), 'placement_class': deployment.get('placement_class'), 'access_class': arguments.get('access_class'), 'traffic_class': arguments.get('traffic_class')})
if policy is None:
return 'RELEASE_POLICY_UNKNOWN: deployment and service conditions do not select one local policy cell'
requirements = policy['requirements']
service_type = arguments['service_type']
if service_type != requirements['service_type']:
return 'SERVICE_POLICY_MISMATCH: service_type violates the local access policy'
ports = arguments['ports']
names: set[str] = set()
node_ports: set[int] = set()
for port in ports:
name = port['name']
if name in names:
return 'INVALID_PORT_SPEC: port names must be unique within the service'
names.add(name)
if port.get('protocol') != requirements['protocol']:
return 'PORT_POLICY_MISMATCH: protocol violates the local traffic policy'
node_port = port.get('node_port')
if service_type == 'NodePort':
if node_port is None:
return 'INVALID_PORT_SPEC: NodePort services require node_port'
if node_port in node_ports:
return 'INVALID_PORT_SPEC: node_port values must be unique within the service'
node_ports.add(node_port)
elif node_port is not None:
return 'INVALID_PORT_SPEC: node_port is only allowed for NodePort services'
if requirements['external_dns'] == 'required' and (not str(arguments.get('external_dns') or '').strip()):
return 'INVALID_EXTERNAL_DNS: LoadBalancer services require external_dns'
if requirements['external_dns'] == 'forbidden' and arguments.get('external_dns') is not None:
return 'INVALID_EXTERNAL_DNS: the selected release policy forbids external_dns'
if node_ports:
for service in self._rows('service'):
if service.get('cluster_id') != deployment['cluster_id']:
continue
for port in service.get('ports') or []:
if port.get('node_port') in node_ports:
return 'NODE_PORT_CONFLICT: a requested node_port is already allocated in the cluster'
return None
def _kubernetes_binding_successor_init(self, source=CASE_DIR / 'raw', budget=120, **kwargs):
self.stale_pool_bindings = {}
self.binding_revalidation = {}
self._kubernetes_mixed_successor_init(source, budget, **kwargs)
self.policy_epoch = 'pre'
def _kubernetes_evolution_apply_event(self, event_id):
if event_id not in {'E1', 'E2'}:
raise ValueError('unknown Kubernetes event')
if event_id in self.applied_boundary_events:
return {'event_id': event_id, 'applied': False}
before = self.business_hash()
if event_id == 'E1':
for binding in DATA_CHANGED_S:
old = self.pool_bindings[binding]
self.pool_bindings[binding] = next((k for (k, p) in self.pools.items() if f"{p['cluster_id']}/{p['zone']}" == binding and k != old))
else:
if 'E1' not in self.applied_boundary_events:
raise ValueError('Kubernetes events must be applied in order')
self.policy_epoch = 'post'
self.applied_boundary_events.add(event_id)
return {'event_id': event_id, 'applied': True, 'before': before, 'after': self.business_hash()}
def _kubernetes_assignment_world_snapshot(self):
value = self._kubernetes_exact_namespace_world_snapshot()
if not getattr(self, '_restoring_assignment', False):
value['namespace_allocation_contract'] = {'case_version': 'k8s-namespace-allocation-evolution-v4', 'bindings': ext_deepcopy(self.namespace_pool_bindings), 'pools_sha256': fn_digest(self.pools)}
return value
def _kubernetes_assignment_world_restore(self, snapshot):
value = ext_deepcopy(snapshot)
contract = value.pop('namespace_allocation_contract', {})
if contract.get('case_version') != 'k8s-namespace-allocation-evolution-v4' or contract.get('pools_sha256') != fn_digest(self.pools):
raise ValueError('K8s namespace-allocation snapshot version or pool fixture differs')
bindings = contract['bindings']
if set(bindings) != set(self.namespace_pool_bindings) or any((pool not in self.pools for pool in bindings.values())):
raise ValueError('K8s namespace-allocation snapshot scope differs')
self.namespace_pool_bindings = ext_deepcopy(bindings)
self._restoring_assignment = True
try:
self._kubernetes_exact_namespace_world_restore(value)
finally:
self._restoring_assignment = False
if self.snapshot() != snapshot:
raise ValueError('K8s namespace-allocation snapshot did not round trip')
def _kubernetes_pool_successor_inspect_pool(self, arguments):
pool = self.pools.get(arguments['pool_id'])
if pool is None:
return self._result('inspect_worker_pool', 'error', 'POOL_NOT_FOUND: unknown worker pool')
assigned = self.pool_bindings[f"{pool['cluster_id']}/{pool['zone']}"] == pool['pool_id']
fields = ('node_id', 'cluster_id', 'zone', 'role', 'readiness', 'schedulable', 'active_pods', 'allocatable_pods')
members = [{k: self._get('node', n).get(k) for k in fields} for n in pool['node_ids']]
return self._result('inspect_worker_pool', 'success', 'OK', {'pool_id': pool['pool_id'], 'directory_id': pool['directory_id'], 'zone': pool['zone'], 'eligible_namespace_ids': self._namespace_members(pool['cluster_id']) if assigned else [], 'nodes': members})
def _kubernetes_pool_successor_dispatch(self, tool, arguments, actor='platform_release_operator'):
normalized = self._normalize(tool, arguments) if tool in DATA_SCHEMAS_3 else arguments
before_hash = self.business_hash() if self.receipt_hashes else None
if actor != 'platform_release_operator' or tool not in DATA_SCHEMAS_3:
result = self._result(tool, 'error', 'TOOL_FORBIDDEN: tool or actor is outside the compact release slice', {'error_code': 'TOOL_FORBIDDEN'})
return self._record(tool, actor, normalized, result, 0, before_hash)
cost = self._cost(tool, normalized)
if self.remaining < cost:
result = self._result(tool, 'error', 'WORK_QUOTA_EXHAUSTED: insufficient API-work quota', {'error_code': 'WORK_QUOTA_EXHAUSTED'})
return self._record(tool, actor, normalized, result, 0, before_hash)
error = fn__validate_value(normalized, DATA_SCHEMAS_3[tool], 'arguments')
if error:
self.remaining -= cost
result = self._result(tool, 'error', 'INVALID_ARGUMENTS: ' + error, {'error_code': 'INVALID_ARGUMENTS'})
return self._record(tool, actor, normalized, result, cost, before_hash)
if tool == 'list_namespaces':
self.remaining -= cost
try:
internal = self._internalize(normalized)
result = self._list_exact_namespaces(internal)
except (KeyError, TypeError, ValueError):
result = self._result(tool, 'error', 'INVALID_ARGUMENTS: an object handle was not issued by this environment', {'error_code': 'INVALID_ARGUMENTS'})
result = self.publicize(result)
return self._record(tool, actor, normalized, result, cost, before_hash)
return self._kubernetes_pool_successor_dispatch_2(tool, normalized, actor=actor)
def _kubernetes_release_adapter_publish(self, arguments):
namespace = self._get('namespace', arguments['namespace_id'])
if namespace is None:
return self._result('publish_deployment', 'error', 'NAMESPACE_NOT_FOUND: no namespace matches namespace_id')
if namespace.get('status') != 'active':
return self._result('publish_deployment', 'error', 'NAMESPACE_NOT_ACTIVE: namespace status is not active')
cluster = self._get('cluster', namespace['cluster_id'])
if cluster is None or cluster.get('status') == 'offline':
return self._result('publish_deployment', 'error', 'CLUSTER_OFFLINE: parent cluster is unavailable')
desired = int(arguments['desired_replicas'])
if desired > int(namespace.get('quota_pods') or 0) - int(namespace.get('active_pods') or 0):
return self._result('publish_deployment', 'error', 'QUOTA_EXCEEDED: requested replicas exceed namespace remaining quota')
deployment_id = self._deployment_id(arguments)
if self._get('deployment', deployment_id) is not None:
return self._result('publish_deployment', 'error', 'DUPLICATE_DEPLOYMENT: derived deployment identity already exists')
policy = self._workload_policy(arguments)
if policy is None:
return self._result('publish_deployment', 'error', 'RELEASE_POLICY_UNKNOWN: workload conditions do not select a local rollout policy')
requirements = policy['requirements']
if arguments['update_strategy'] != requirements['update_strategy']:
return self._result('publish_deployment', 'error', 'ROLLOUT_POLICY_MISMATCH: update_strategy violates the local workload policy')
placement_error = self._placement_error(cluster['cluster_id'], arguments['placement_node_ids'], desired)
if placement_error:
return self._result('publish_deployment', 'error', placement_error)
if requirements.get('distinct_worker_zones'):
zones = {self._get('node', node_id).get('zone') for node_id in arguments['placement_node_ids']}
if None in zones or len(zones) != desired:
return self._result('publish_deployment', 'error', 'PLACEMENT_POLICY_MISMATCH: zonal_pair requires one replica per distinct worker zone')
deployment = {'deployment_id': deployment_id, 'cluster_id': cluster['cluster_id'], 'namespace_id': namespace['namespace_id'], 'name': arguments['name'].strip(), 'app_label': fn__slug(arguments['app_label']), 'image': arguments['image'].strip(), 'image_tag': arguments['image_tag'].strip(), 'desired_replicas': desired, 'ready_replicas': 0, 'available_replicas': 0, 'update_strategy': arguments['update_strategy'], 'workload_class': arguments['workload_class'], 'change_window': arguments['change_window'], 'placement_class': arguments['placement_class'], 'release_policy_id': policy['policy_id'], 'rollout_status': 'progressing', 'service_account': f"svcacct-{fn__slug(arguments['app_label'])}", 'env_vars': {'APP_MODE': cluster.get('environment'), 'REGION': cluster.get('region'), 'OWNER_TEAM': fn__slug(namespace.get('owner_team'))}, 'config_asset_ids': [], 'service_count': 0, 'created_by': arguments['created_by'].strip(), 'created_at': '2026-05-27T12:00:00Z', 'updated_at': '2026-05-27T12:00:00Z'}
before = self.snapshot() if self.atomic_snapshots else None
try:
self._save('deployment', deployment)
pod_ids = [self._make_pod(deployment, f'runtime-{index:03d}', node_id)['pod_id'] for (index, node_id) in enumerate(arguments['placement_node_ids'])]
namespace['active_pods'] = int(namespace.get('active_pods') or 0) + desired
namespace['updated_at'] = '2026-05-27T12:00:00Z'
self._save('namespace', namespace)
cluster['pod_allocated'] = int(cluster.get('pod_allocated') or 0) + desired
cluster['updated_at'] = '2026-05-27T12:00:00Z'
self._save('cluster', cluster)
deployment = self._reconcile_deployment(deployment)
event = self._event(cluster_id=cluster['cluster_id'], namespace_id=namespace['namespace_id'], kind='Deployment', involved_id=deployment_id, severity='normal', reason='RolloutReady', message=f"Deployment {deployment['name']} reached its declared placement target.")
except Exception:
if before is not None:
self.restore(before)
return self._result('publish_deployment', 'error', 'ATOMIC_WRITE_FAILED: deployment transaction was rolled back')
return self._result('publish_deployment', 'success', 'OK', {'deployment_id': deployment_id, 'namespace_id': namespace['namespace_id'], 'cluster_id': cluster['cluster_id'], 'desired_replicas': desired, 'ready_replicas': deployment['ready_replicas'], 'rollout_status': deployment['rollout_status'], 'pod_ids': pod_ids, 'placement_node_ids': list(arguments['placement_node_ids']), 'event': event})
def _kubernetes_release_adapter_create_service(self, arguments):
guarded = self._service_guard(arguments)
if guarded:
return self._result('create_service', 'error', guarded)
before = self.snapshot() if self.atomic_snapshots else None
raw_arguments = {key: mod_copy.deepcopy(value) for (key, value) in arguments.items() if key not in {'access_class', 'traffic_class'}}
try:
raw = self.server.call_tool('create_service', state_manager=self.manager, **raw_arguments)
except Exception:
raw = None
result = fn__sanitize_raw_result('create_service', raw)
if result['content'].get('status') == 'success':
try:
service_id = result['content']['data']['service_id']
service = self._get('service', service_id)
if service is None:
raise RuntimeError('created service is missing')
service['access_class'] = arguments['access_class']
service['traffic_class'] = arguments['traffic_class']
policy = self._policy({'workload_class': self._get('deployment', arguments['deployment_id']).get('workload_class'), 'change_window': self._get('deployment', arguments['deployment_id']).get('change_window'), 'placement_class': self._get('deployment', arguments['deployment_id']).get('placement_class'), 'access_class': arguments['access_class'], 'traffic_class': arguments['traffic_class']})
service['release_policy_id'] = policy['policy_id']
self._save('service', service)
except Exception:
if before is not None:
self.restore(before)
return self._result('create_service', 'error', 'ATOMIC_WRITE_FAILED: service transaction was rolled back')
elif before is not None and self.business_hash() != self._business_hash_from_snapshot(before):
self.restore(before)
return result
def _kubernetes_release_adapter_normalize(self, tool, arguments):
if not isinstance(arguments, dict):
return arguments
normalized = mod_copy.deepcopy(arguments)
if tool in DATA_LIST_TOOLS:
normalized.setdefault('limit', 25)
normalized.setdefault('offset', 0)
if tool == 'inspect_node':
normalized.setdefault('include_pods', False)
normalized.setdefault('include_events', False)
if tool == 'inspect_deployment':
normalized.setdefault('include_pods', False)
normalized.setdefault('include_services', False)
if tool == 'update_deployment_replicas':
normalized.setdefault('placement_node_ids', [])
return normalized
def _kubernetes_release_adapter_cost(self, tool, arguments):
if tool in DATA_LIST_TOOLS:
return 2 + fn__bounded_int(arguments, 'limit', 25, 1, 100)
if tool == 'inspect_node':
if not isinstance(arguments, dict):
return 23
return 3 + (10 if arguments.get('include_pods', False) else 0) + (10 if arguments.get('include_events', False) else 0)
if tool == 'inspect_deployment':
if not isinstance(arguments, dict):
return 23
return 3 + (10 if arguments.get('include_pods', False) else 0) + (10 if arguments.get('include_services', False) else 0)
if tool == 'inspect_release_policy':
return 18
if tool == 'publish_deployment':
return 8 + 3 * fn__bounded_int(arguments, 'desired_replicas', 4, 1, 50)
if tool == 'update_deployment_replicas':
return 8 + 3 * max(1, fn__safe_len(arguments, 'placement_node_ids', 4, 100))
if tool == 'create_service':
return 8 + 2 * max(1, fn__safe_len(arguments, 'ports', 2, 8))
return 0
def _kubernetes_mixed_successor_init(self, source=CASE_DIR / 'raw', budget=120, **kwargs):
self.policy_epoch = 'pre'
self._kubernetes_pool_successor_init(source, budget, **kwargs)
def _kubernetes_exact_namespace_world_snapshot(self):
value = self._kubernetes_scope_balanced_world_snapshot()
if not getattr(self, '_restoring_exact_namespace', False):
value['exact_namespace_contract'] = 'k8s-exact-namespace-lifecycle-evolution-v3'
return value
def _kubernetes_exact_namespace_world_restore(self, snapshot):
value = ext_deepcopy(snapshot)
if value.pop('exact_namespace_contract', None) != 'k8s-exact-namespace-lifecycle-evolution-v3':
raise ValueError('K8s exact-namespace snapshot version differs')
self._restoring_exact_namespace = True
try:
self._kubernetes_scope_balanced_world_restore(value)
finally:
self._restoring_exact_namespace = False
if self.snapshot() != snapshot:
raise ValueError('K8s exact-namespace snapshot did not round trip')
def _kubernetes_pool_successor_dispatch_2(self, tool, arguments, actor='platform_release_operator'):
normalized = self._normalize(tool, arguments)
before_hash = self.business_hash() if self.receipt_hashes else None
if actor != 'platform_release_operator' or tool not in DATA_SCHEMAS_4:
result = self._result(tool, 'error', 'TOOL_FORBIDDEN: tool or actor is outside the release-operator slice')
return self._record(tool, actor, normalized, result, 0, before_hash)
cost = self._cost(tool, normalized)
if self.remaining < cost:
return self._record(tool, actor, normalized, self._result(tool, 'error', 'WORK_QUOTA_EXHAUSTED: insufficient API-work quota'), 0, before_hash)
self.remaining -= cost
error = fn__validate_value(normalized, DATA_SCHEMAS_4[tool], 'arguments')
try:
internal = self._internalize(normalized) if not error else None
except ValueError as exc:
error = str(exc)
internal = None
if error:
result = self._result(tool, 'error', 'INVALID_ARGUMENTS: ' + error)
elif tool == 'list_worker_pools':
result = self._list_pools(internal)
elif tool == 'inspect_worker_pool':
result = self._inspect_pool(internal)
elif tool == 'list_clusters':
result = self._list_clusters(internal)
elif tool == 'inspect_release_policy':
result = self._inspect_release_policy(internal)
elif tool == 'publish_deployment':
result = self._publish(internal)
elif tool == 'create_service':
result = self._create_service(internal)
elif tool == 'update_deployment_replicas':
result = self._scale(internal)
else:
try:
raw = self.server.call_tool(tool, state_manager=self.manager, **internal)
except Exception:
raw = None
result = fn__sanitize_raw_result(tool, raw)
if tool == 'list_namespaces' and result['content'].get('status') == 'success':
for row in result['content']['data'].get('namespaces', []):
cluster = self._get('namespace', row['namespace_id'])['cluster_id']
if cluster in DATA_ZONES:
row['directory_id'] = f'directory:{cluster}'
content = result['content']
if content.get('status') == 'error':
content.setdefault('data', {}).setdefault('error_code', content.get('message', 'TOOL_ERROR').split(':', 1)[0])
result = self.publicize(result)
return self._record(tool, actor, normalized, result, cost, before_hash)
def _kubernetes_pool_successor_init(self, source=CASE_DIR / 'raw', budget=120, **kwargs):
self._kubernetes_pool_successor_init_2(source, budget, **kwargs)
key = f"{'cluster-meridian-prod-eu-central'}/euc1c"
candidates = [node for node in self._rows('node') if node.get('cluster_id') == 'cluster-meridian-prod-eu-central' and node.get('zone') == 'euc1c' and (node.get('role') == 'worker') and (node.get('readiness') == 'ready') and (node.get('schedulable') is True) and (int(node.get('allocatable_pods') or 0) - int(node.get('active_pods') or 0) >= 48)]
candidates.sort(key=lambda node: fn_digest(['k8s-operations-structure-v6', 'worker-selection', node['node_id']]))
if len(candidates) < 4:
raise ValueError(f'insufficient independent worker candidates in {key}')
pair = []
for ordinal in range(2):
pool_id = f'pool:{key}:{ordinal}'
self.pools[pool_id] = {'pool_id': pool_id, 'directory_id': f"directory:{'cluster-meridian-prod-eu-central'}", 'cluster_id': 'cluster-meridian-prod-eu-central', 'zone': 'euc1c', 'node_ids': [node['node_id'] for node in candidates[ordinal * 2:ordinal * 2 + 2]]}
pair.append(pool_id)
self.pool_bindings[key] = pair[0]
self._refresh_ids()
def _kubernetes_scope_balanced_world_snapshot(self):
value = self._kubernetes_evolution_snapshot()
if not getattr(self, '_restoring_scope_balance', False):
value['scope_balance_contract'] = 'k8s-scope-balanced-lifecycle-evolution-v2'
return value
def _kubernetes_scope_balanced_world_restore(self, snapshot):
value = ext_deepcopy(snapshot)
if value.pop('scope_balance_contract', None) != 'k8s-scope-balanced-lifecycle-evolution-v2':
raise ValueError('K8s scope-balanced snapshot version differs')
self._restoring_scope_balance = True
try:
self._kubernetes_evolution_restore(value)
finally:
self._restoring_scope_balance = False
if self.snapshot() != snapshot:
raise ValueError('K8s scope-balanced snapshot did not round trip')
def _kubernetes_pool_successor_init_2(self, source=CASE_DIR / 'raw', budget=120, **kwargs):
self._kubernetes_structure_successor_init(source, budget, **kwargs)
self.directories = {f'directory:{cluster}': cluster for cluster in DATA_ZONES}
self.pools = {}
self.pool_bindings = {}
for (cluster, zones) in DATA_ZONES.items():
for zone in zones:
candidates = [n for n in self._rows('node') if n.get('cluster_id') == cluster and n.get('zone') == zone and (n.get('role') == 'worker') and (n.get('readiness') == 'ready') and (n.get('schedulable') is True) and (int(n.get('allocatable_pods') or 0) - int(n.get('active_pods') or 0) >= 48)]
candidates.sort(key=lambda n: fn_digest(['k8s-operations-structure-v5', 'worker-selection', n['node_id']]))
if len(candidates) < 4:
raise ValueError(f'insufficient independent worker candidates in {cluster}/{zone}')
key = f'{cluster}/{zone}'
pair = []
for ordinal in range(2):
pool_id = f'pool:{key}:{ordinal}'
self.pools[pool_id] = {'pool_id': pool_id, 'directory_id': f'directory:{cluster}', 'cluster_id': cluster, 'zone': zone, 'node_ids': [n['node_id'] for n in candidates[ordinal * 2:ordinal * 2 + 2]]}
pair.append(pool_id)
self.pool_bindings[key] = pair[0]
self.public_ids = {}
self.internal_ids = {}
self._refresh_ids()
def _kubernetes_evolution_snapshot(self):
value = self._kubernetes_binding_successor_snapshot()
value['evolution'] = {'case_version': 'k8s-two-event-lifecycle-evolution-v1', 'schedule': ext_deepcopy(DATA_SCHEDULE_2), 'policy_sha256': 'f0e7d2900c19ca712badfb4666088b7aa38c288f963d21c530e237ddfe4051b6'}
return value
def _kubernetes_evolution_restore(self, snapshot):
value = ext_deepcopy(snapshot)
metadata = value.pop('evolution')
if metadata != {'case_version': 'k8s-two-event-lifecycle-evolution-v1', 'schedule': DATA_SCHEDULE_2, 'policy_sha256': 'f0e7d2900c19ca712badfb4666088b7aa38c288f963d21c530e237ddfe4051b6'}:
raise ValueError('Kubernetes evolution contract differs')
stream = value['structure_successor']
active = stream['prepared_tasks']
if active != list(DATA_TASK_IDS[:len(active)]) or stream['current_task_id'] != (active[-1] if active else None):
raise ValueError('Kubernetes evolution checkpoint prefix differs')
self._kubernetes_binding_successor_restore(value)
expected = {e['event_id'] for e in DATA_SCHEDULE_2['events'] if e['before_task'] <= len(active)}
if self.applied_boundary_events != expected or self.policy_epoch != ('post' if len(active) >= 17 else 'pre'):
raise ValueError('Kubernetes evolution event state differs')
if self.snapshot() != snapshot:
raise ValueError('Kubernetes evolution snapshot did not round trip')
def _kubernetes_structure_successor_init(self, source=CASE_DIR / 'raw', budget=120, *, in_memory=True, receipt_hashes=True, atomic_snapshots=True):
source = ext_Path(source).resolve()
def initialize(modules):
server = modules[0]
server.cleanup_runtime()
server.init_database(str(source / 'data'))
server.load_tools()
return server.get_state_manager()
(modules, manager) = ext_load_isolated_modules(source, ('mcp_servers.server',), initialize=initialize)
self.source = source
self.server = modules[0]
self.manager = manager
if in_memory:
self.manager.db._flush = lambda _entity_type: None
self.initial_budget = int(budget)
self.remaining = int(budget)
self.receipts: list[dict[str, ext_Any]] = []
self.applied_boundary_events: set[str] = set()
self.receipt_hashes = bool(receipt_hashes)
self.atomic_snapshots = bool(atomic_snapshots)
self.prepared_tasks: list[str] = []
self.current_task_id: str | None = None
def _kubernetes_binding_successor_snapshot(self):
result = self._kubernetes_mixed_successor_snapshot()
result['schema'] = 'rescopebench-k8s-binding-snapshot/v9'
result['structure_successor']['provider_tools_sha256'] = '75b1c919a80d9e1402dd81859bce9618c5f623ccf5b21f2399dd30df368f679e'
result['binding_successor'] = {'stale_pool_bindings': ext_deepcopy(self.stale_pool_bindings), 'binding_revalidation': ext_deepcopy(self.binding_revalidation)}
return result
def _kubernetes_binding_successor_restore(self, snapshot):
if snapshot.get('schema') != 'rescopebench-k8s-binding-snapshot/v9':
raise ValueError('unsupported Kubernetes binding snapshot')
value = ext_deepcopy(snapshot)
state = value.pop('binding_successor', {})
self.stale_pool_bindings = ext_deepcopy(state.get('stale_pool_bindings', {}))
self.binding_revalidation = ext_deepcopy(state.get('binding_revalidation', {}))
value['schema'] = 'rescopebench-k8s-mixed-snapshot/v8'
value['structure_successor']['provider_tools_sha256'] = 'a2414103089c1534c4ea904dfc9e729818730ad6407251f0305bc37163e8bf8b'
self._kubernetes_mixed_successor_restore(value)
def _kubernetes_mixed_successor_snapshot(self):
result = self._kubernetes_pool_successor_snapshot()
result['schema'] = 'rescopebench-k8s-mixed-snapshot/v8'
result['mixed_successor'] = {'policy_epoch': self.policy_epoch}
result['structure_successor']['provider_tools_sha256'] = 'a2414103089c1534c4ea904dfc9e729818730ad6407251f0305bc37163e8bf8b'
return result
def _kubernetes_mixed_successor_restore(self, snapshot):
if snapshot.get('schema') != 'rescopebench-k8s-mixed-snapshot/v8':
raise ValueError('unsupported Kubernetes mixed snapshot')
mixed = snapshot.get('mixed_successor') or {}
base = ext_deepcopy(snapshot)
base.pop('mixed_successor', None)
base['schema'] = 'rescopebench-k8s-pool-snapshot/v7'
self.policy_epoch = mixed.get('policy_epoch', 'pre')
self._kubernetes_pool_successor_restore(base)
def _kubernetes_pool_successor_snapshot(self):
result = self._kubernetes_pool_successor_snapshot_2()
result['schema'] = 'rescopebench-k8s-pool-snapshot/v7'
result['structure_successor']['provider_tools_sha256'] = 'a2414103089c1534c4ea904dfc9e729818730ad6407251f0305bc37163e8bf8b'
return result
def _kubernetes_pool_successor_restore(self, snapshot):
if snapshot.get('schema') != 'rescopebench-k8s-pool-snapshot/v7':
raise ValueError('unsupported Kubernetes pool snapshot')
if snapshot.get('structure_successor', {}).get('provider_tools_sha256') != 'a2414103089c1534c4ea904dfc9e729818730ad6407251f0305bc37163e8bf8b':
raise ValueError('snapshot provider tool profile differs from V7')
base = ext_deepcopy(snapshot)
base['schema'] = 'rescopebench-k8s-pool-snapshot/v6'
self._kubernetes_pool_successor_restore_2(base)
def _kubernetes_pool_successor_snapshot_2(self):
result = self._kubernetes_pool_successor_snapshot_3()
result['schema'] = 'rescopebench-k8s-pool-snapshot/v6'
return result
def _kubernetes_pool_successor_restore_2(self, snapshot):
if snapshot.get('schema') != 'rescopebench-k8s-pool-snapshot/v6':
raise ValueError('unsupported Kubernetes pool snapshot')
base = ext_deepcopy(snapshot)
base['schema'] = 'rescopebench-k8s-pool-snapshot/v5'
self._kubernetes_pool_successor_restore_3(base)
def _kubernetes_pool_successor_snapshot_3(self):
result = self._kubernetes_structure_successor_snapshot()
result['schema'] = 'rescopebench-k8s-pool-snapshot/v5'
result['pool_successor'] = {'bindings': ext_deepcopy(self.pool_bindings)}
return result
def _kubernetes_pool_successor_restore_3(self, snapshot):
if snapshot.get('schema') != 'rescopebench-k8s-pool-snapshot/v5':
raise ValueError('unsupported Kubernetes pool snapshot')
self.pool_bindings = ext_deepcopy(snapshot['pool_successor']['bindings'])
base = ext_deepcopy(snapshot)
base['schema'] = 'rescopebench-k8s-structure-snapshot/v3'
base.pop('pool_successor')
self._kubernetes_structure_successor_restore(base)
self._refresh_ids()
def _kubernetes_structure_successor_snapshot(self):
value = self._kubernetes_release_adapter_snapshot()
value['schema'] = 'rescopebench-k8s-structure-snapshot/v3'
value['structure_successor'] = {'prepared_tasks': list(self.prepared_tasks), 'current_task_id': self.current_task_id, 'provider_tools_sha256': '773003f031c22e23ab9eff34715335034752a7c8b5547c8302789c248bbc2080'}
return value
def _kubernetes_structure_successor_restore(self, snapshot):
if snapshot.get('schema') != 'rescopebench-k8s-structure-snapshot/v3':
raise ValueError('unsupported Kubernetes structure snapshot')
stream = snapshot.get('structure_successor') or {}
base = ext_deepcopy(snapshot)
base.pop('schema', None)
base.pop('structure_successor', None)
self._kubernetes_release_adapter_restore(base)
self.prepared_tasks = list(stream.get('prepared_tasks') or [])
self.current_task_id = stream.get('current_task_id')
def _kubernetes_release_adapter_snapshot(self):
return {'raw': mod_copy.deepcopy(self.manager.snapshot()), 'remaining': self.remaining, 'receipts': mod_copy.deepcopy(self.receipts), 'applied_boundary_events': sorted(self.applied_boundary_events)}
def _kubernetes_release_adapter_restore(self, snapshot):
database = mod_copy.deepcopy(snapshot['raw']['database'])
self.manager.db._data = database
self.manager.db._id_counters = {}
for entity_type in database:
self.manager.db._flush(entity_type)
self.manager._counters = mod_copy.deepcopy(snapshot['raw'].get('counters', {}))
self.manager._core_state_cache = None
self.remaining = int(snapshot['remaining'])
self.receipts = mod_copy.deepcopy(snapshot['receipts'])
self.applied_boundary_events = set(snapshot.get('applied_boundary_events', []))
|